]> code.delx.au - gnu-emacs/blob - src/w32select.c
Merge from emacs--devo--0
[gnu-emacs] / src / w32select.c
1 /* Selection processing for Emacs on the Microsoft W32 API.
2 Copyright (C) 1993, 1994, 2001, 2002, 2003, 2004,
3 2005, 2006, 2007 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 2, or (at your option)
10 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; see the file COPYING. If not, write to
19 the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
20 Boston, MA 02110-1301, USA. */
21
22 /* Written by Kevin Gallo, Benjamin Riefenstahl */
23
24
25 /*
26 * Notes on usage of selection-coding-system and
27 * next-selection-coding-system on MS Windows:
28 *
29 * The selection coding system variables apply only to the version of
30 * the clipboard data that is closest in type, i.e. when a 16-bit
31 * Unicode coding system is given, they apply to he Unicode clipboard
32 * (CF_UNICODETEXT), when a well-known console codepage is given, they
33 * apply to the console version of the clipboard data (CF_OEMTEXT),
34 * else they apply to the normal 8-bit text clipboard (CF_TEXT).
35 *
36 * When pasting (getting data from the OS), the clipboard format that
37 * matches the {next-}selection-coding-system is retrieved. If
38 * Unicode is requested, but not available, 8-bit text (CF_TEXT) is
39 * used. In all other cases the OS will transparently convert
40 * formats, so no other fallback is needed.
41 *
42 * When copying or cutting (sending data to the OS), the data is
43 * announced and stored internally, but only actually rendered on
44 * request. The requester determines the format provided. The
45 * {next-}selection-coding-system is only used, when its corresponding
46 * clipboard type matches the type requested.
47 *
48 * Scenarios to use the facilities for customizing the selection
49 * coding system are:
50 *
51 * ;; Generally use KOI8-R instead of the russian MS codepage for
52 * ;; the 8-bit clipboard.
53 * (set-selection-coding-system 'koi8-r-dos)
54 *
55 * Or
56 *
57 * ;; Create a special clipboard copy function that uses codepage
58 * ;; 1253 (Greek) to copy Greek text to a specific non-Unicode
59 * ;; application.
60 * (defun greek-copy (beg end)
61 * (interactive "r")
62 * (set-next-selection-coding-system 'cp1253-dos)
63 * (copy-region-as-kill beg end))
64 * (global-set-key "\C-c\C-c" 'greek-copy)
65 */
66
67 /*
68 * Ideas for further directions:
69 *
70 * The encoding and decoding routines could be moved to Lisp code
71 * similar to how xselect.c does it (using well-known routine names
72 * for the delayed rendering). If the definition of which clipboard
73 * types should be supported is also moved to Lisp, functionality
74 * could be expanded to CF_HTML, CF_RTF and maybe other types.
75 */
76
77 #include <config.h>
78 #include "lisp.h"
79 #include "w32term.h" /* for all of the w32 includes */
80 #include "w32heap.h" /* os_subtype */
81 #include "blockinput.h"
82 #include "keyboard.h" /* cmd_error_internal() */
83 #include "charset.h"
84 #include "coding.h"
85 #include "composite.h"
86
87
88 static HGLOBAL convert_to_handle_as_ascii (void);
89 static HGLOBAL convert_to_handle_as_coded (Lisp_Object coding_system);
90 static Lisp_Object render (Lisp_Object oformat);
91 static Lisp_Object render_locale (void);
92 static Lisp_Object render_all (void);
93 static void run_protected (Lisp_Object (*code) (), Lisp_Object arg);
94 static Lisp_Object lisp_error_handler (Lisp_Object error);
95 static LRESULT CALLBACK owner_callback (HWND win, UINT msg,
96 WPARAM wp, LPARAM lp);
97 static HWND create_owner (void);
98
99 static void setup_config (void);
100 static BOOL WINAPI enum_locale_callback (/*const*/ char* loc_string);
101 static UINT cp_from_locale (LCID lcid, UINT format);
102 static Lisp_Object coding_from_cp (UINT codepage);
103 static Lisp_Object validate_coding_system (Lisp_Object coding_system);
104 static void setup_windows_coding_system (Lisp_Object coding_system,
105 struct coding_system * coding);
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. */
111 Lisp_Object QCLIPBOARD;
112
113 /* Coding system for communicating with other programs via the
114 clipboard. */
115 static Lisp_Object Vselection_coding_system;
116
117 /* Coding system for the next communication with other programs. */
118 static Lisp_Object Vnext_selection_coding_system;
119
120 /* Internal pseudo-constants, initialized in globals_of_w32select()
121 based on current system parameters. */
122 static LCID DEFAULT_LCID;
123 static UINT ANSICP, OEMCP;
124 static Lisp_Object QUNICODE, QANSICP, QOEMCP;
125
126 /* A hidden window just for the clipboard management. */
127 static HWND clipboard_owner;
128 /* A flag to tell WM_DESTROYCLIPBOARD who is to blame this time (just
129 checking GetClipboardOwner() doesn't work, sadly). */
130 static int modifying_clipboard = 0;
131
132 /* Configured transfer parameters, based on the last inspection of
133 selection-coding-system. */
134 static Lisp_Object cfg_coding_system;
135 static UINT cfg_codepage;
136 static LCID cfg_lcid;
137 static UINT cfg_clipboard_type;
138
139 /* The current state for delayed rendering. */
140 static Lisp_Object current_text;
141 static Lisp_Object current_coding_system;
142 static int current_requires_encoding, current_num_nls;
143 static UINT current_clipboard_type;
144 static 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
156 static HGLOBAL
157 convert_to_handle_as_ascii (void)
158 {
159 HGLOBAL htext = NULL;
160 int nbytes;
161 int truelen;
162 unsigned char *src;
163 unsigned char *dst;
164
165 ONTRACE (fprintf (stderr, "convert_to_handle_as_ascii\n"));
166
167 nbytes = SBYTES (current_text) + 1;
168 src = SDATA (current_text);
169
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). */
173
174 truelen = nbytes + current_num_nls;
175
176 if ((htext = GlobalAlloc (GMEM_MOVEABLE | GMEM_DDESHARE, truelen)) == NULL)
177 return NULL;
178
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;
210 }
211
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
216 static HGLOBAL
217 convert_to_handle_as_coded (Lisp_Object coding_system)
218 {
219 HGLOBAL htext;
220 unsigned char *dst = NULL;
221 struct coding_system coding;
222
223 ONTRACE (fprintf (stderr, "convert_to_handle_as_coded: %s\n",
224 SDATA (SYMBOL_NAME (coding_system))));
225
226 setup_windows_coding_system (coding_system, &coding);
227 coding.dst_bytes = SBYTES(current_text) * 2;
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);
231
232 htext = GlobalAlloc (GMEM_MOVEABLE | GMEM_DDESHARE, coding.produced +2);
233
234 if (htext != NULL)
235 dst = (unsigned char *) GlobalLock (htext);
236
237 if (dst != NULL)
238 {
239 memcpy (dst, coding.destination, coding.produced);
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';
243
244 GlobalUnlock (htext);
245 }
246
247 xfree (coding.destination);
248
249 return htext;
250 }
251
252 static Lisp_Object
253 render (Lisp_Object oformat)
254 {
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 {
293 GlobalFree(htext);
294 return Qnil;
295 }
296
297 return Qt;
298 }
299
300 static Lisp_Object
301 render_locale (void)
302 {
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 {
317 GlobalFree(hlocale);
318 return Qnil;
319 }
320
321 *lcid_ptr = current_lcid;
322 GlobalUnlock (hlocale);
323
324 if (SetClipboardData (CF_LOCALE, hlocale) == NULL)
325 {
326 GlobalFree(hlocale);
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
336 static Lisp_Object
337 render_all (void)
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
383 render_locale();
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
394 static void
395 run_protected (Lisp_Object (*code) (), Lisp_Object arg)
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
401 extern int waiting_for_input;
402 int owfi;
403
404 BLOCK_INPUT;
405
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;
414
415 UNBLOCK_INPUT;
416 }
417
418 static Lisp_Object
419 lisp_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;
425 }
426
427
428 static LRESULT CALLBACK
429 owner_callback (HWND win, UINT msg, WPARAM wp, LPARAM lp)
430 {
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;
455
456 case WM_DESTROY:
457 if (win == clipboard_owner)
458 clipboard_owner = NULL;
459 break;
460 }
461
462 return DefWindowProc (win, msg, wp, lp);
463 }
464
465 static HWND
466 create_owner (void)
467 {
468 static const char CLASSNAME[] = "Emacs Clipboard";
469 WNDCLASS wc;
470
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
482 void
483 term_w32select (void)
484 {
485 /* This is needed to trigger WM_RENDERALLFORMATS. */
486 if (clipboard_owner != NULL)
487 DestroyWindow (clipboard_owner);
488 }
489
490 static void
491 setup_config (void)
492 {
493 const char *coding_name;
494 const char *cp;
495 char *end;
496 int slen;
497 Lisp_Object coding_system;
498 Lisp_Object dos_coding_system;
499
500 CHECK_SYMBOL (Vselection_coding_system);
501
502 coding_system = NILP (Vnext_selection_coding_system) ?
503 Vselection_coding_system : Vnext_selection_coding_system;
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 */
513 if (!NILP (cfg_coding_system)
514 && EQ (cfg_coding_system, dos_coding_system))
515 return;
516 cfg_coding_system = dos_coding_system;
517
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] == '-'))
529 {
530 cfg_clipboard_type = CF_UNICODETEXT;
531 return;
532 }
533
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 }
553
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 }
565
566 /* Else determine a suitable locale the hard way. */
567 EnumSystemLocales (enum_locale_callback, LCID_INSTALLED);
568 }
569
570 static BOOL WINAPI
571 enum_locale_callback (/*const*/ char* loc_string)
572 {
573 LCID lcid;
574 UINT codepage;
575
576 lcid = strtoul (loc_string, NULL, 16);
577
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 }
586
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 }
595
596 return TRUE; /* Continue enumeration */
597 }
598
599 static UINT
600 cp_from_locale (LCID lcid, UINT format)
601 {
602 char buffer[20] = "";
603 UINT variant, cp;
604
605 variant =
606 format == CF_TEXT ? LOCALE_IDEFAULTANSICODEPAGE : LOCALE_IDEFAULTCODEPAGE;
607
608 GetLocaleInfo (lcid, variant, buffer, sizeof (buffer));
609 cp = strtoul (buffer, NULL, 10);
610
611 if (cp == CP_ACP)
612 return ANSICP;
613 else if (cp == CP_OEMCP)
614 return OEMCP;
615 else
616 return cp;
617 }
618
619 static Lisp_Object
620 coding_from_cp (UINT codepage)
621 {
622 char buffer[30];
623 sprintf (buffer, "cp%d-dos", (int) codepage);
624 return intern (buffer);
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. */
628 }
629
630 static Lisp_Object
631 validate_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
658 static void
659 setup_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
680
681 DEFUN ("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. */)
684 (string, ignored)
685 Lisp_Object string, ignored;
686 {
687 BOOL ok = TRUE;
688 int nbytes;
689 unsigned char *src;
690 unsigned char *dst;
691 unsigned char *end;
692
693 /* This parameter used to be the current frame, but we don't use
694 that any more. */
695 (void) ignored;
696
697 CHECK_STRING (string);
698
699 setup_config ();
700
701 current_text = string;
702 current_coding_system = cfg_coding_system;
703 current_clipboard_type = cfg_clipboard_type;
704 current_lcid = cfg_lcid;
705 current_num_nls = 0;
706 current_requires_encoding = 0;
707
708 BLOCK_INPUT;
709
710 /* Check for non-ASCII characters. While we are at it, count the
711 number of LFs, so we know how many CRs we will have to add later
712 (just in the case where we can use our internal ASCII rendering,
713 see code and comment in convert_to_handle_as_ascii() above). */
714 nbytes = SBYTES (string);
715 src = SDATA (string);
716
717 for (dst = src, end = src+nbytes; dst < end; dst++)
718 {
719 if (*dst == '\n')
720 current_num_nls++;
721 else if (*dst >= 0x80 || *dst == 0)
722 {
723 current_requires_encoding = 1;
724 break;
725 }
726 }
727
728 if (!current_requires_encoding)
729 {
730 /* If all we have is ASCII we don't need to pretend we offer
731 anything fancy. */
732 current_coding_system = Qraw_text;
733 current_clipboard_type = CF_TEXT;
734 current_lcid = LOCALE_NEUTRAL;
735 }
736
737 if (!OpenClipboard (clipboard_owner))
738 goto error;
739
740 ++modifying_clipboard;
741 ok = EmptyClipboard ();
742 --modifying_clipboard;
743
744 /* If we have something non-ASCII we may want to set a locale. We
745 do that directly (non-delayed), as it's just a small bit. */
746 if (ok)
747 ok = !NILP(render_locale());
748
749 if (ok)
750 {
751 if (clipboard_owner == NULL)
752 {
753 /* If for some reason we don't have a clipboard_owner, we
754 just set the text format as chosen by the configuration
755 and than forget about the whole thing. */
756 ok = !NILP(render (make_number (current_clipboard_type)));
757 current_text = Qnil;
758 current_coding_system = Qnil;
759 }
760 else
761 {
762 /* Advertise all supported formats so that whatever the
763 requester chooses, only one encoding step needs to be
764 made. This is intentionally different from what we do in
765 the handler for WM_RENDERALLFORMATS. */
766 SetClipboardData (CF_UNICODETEXT, NULL);
767 SetClipboardData (CF_TEXT, NULL);
768 SetClipboardData (CF_OEMTEXT, NULL);
769 }
770 }
771
772 CloseClipboard ();
773
774 /* With delayed rendering we haven't really "used" this coding
775 system yet, and it's even unclear if we ever will. But this is a
776 way to tell the upper level what we *would* use under ideal
777 circumstances.
778
779 We don't signal the actually used coding-system later when we
780 finally render, because that can happen at any time and we don't
781 want to disturb the "foreground" action. */
782 if (ok)
783 Vlast_coding_system_used = current_coding_system;
784
785 Vnext_selection_coding_system = Qnil;
786
787 if (ok) goto done;
788
789 error:
790
791 ok = FALSE;
792 current_text = Qnil;
793 current_coding_system = Qnil;
794
795 done:
796 UNBLOCK_INPUT;
797
798 return (ok ? string : Qnil);
799 }
800
801
802 DEFUN ("w32-get-clipboard-data", Fw32_get_clipboard_data,
803 Sw32_get_clipboard_data, 0, 1, 0,
804 doc: /* This gets the clipboard data in text format. */)
805 (ignored)
806 Lisp_Object ignored;
807 {
808 HGLOBAL htext;
809 Lisp_Object ret = Qnil;
810 UINT actual_clipboard_type;
811 int use_configured_coding_system = 1;
812
813 /* This parameter used to be the current frame, but we don't use
814 that any more. */
815 (void) ignored;
816
817 /* Don't pass our own text from the clipboard (which might be
818 troublesome if the killed text includes null characters). */
819 if (!NILP (current_text))
820 return ret;
821
822 setup_config ();
823 actual_clipboard_type = cfg_clipboard_type;
824
825 BLOCK_INPUT;
826
827 if (!OpenClipboard (clipboard_owner))
828 goto done;
829
830 if ((htext = GetClipboardData (actual_clipboard_type)) == NULL)
831 {
832 /* If we want CF_UNICODETEXT but can't get it, the current
833 coding system is useless. OTOH we can still try and decode
834 CF_TEXT based on the locale that the system gives us and that
835 we get down below. */
836 if (actual_clipboard_type == CF_UNICODETEXT)
837 {
838 htext = GetClipboardData (CF_TEXT);
839 if (htext != NULL)
840 {
841 actual_clipboard_type = CF_TEXT;
842 use_configured_coding_system = 0;
843 }
844 }
845 }
846 if (htext == NULL)
847 goto closeclip;
848
849 {
850 unsigned char *src;
851 unsigned char *dst;
852 int nbytes;
853 int truelen;
854 int require_decoding = 0;
855
856 if ((src = (unsigned char *) GlobalLock (htext)) == NULL)
857 goto closeclip;
858
859 /* If the clipboard data contains any non-ascii code, we need to
860 decode it with a coding system. */
861 if (actual_clipboard_type == CF_UNICODETEXT)
862 {
863 nbytes = lstrlenW ((WCHAR *)src) * 2;
864 require_decoding = 1;
865 }
866 else
867 {
868 int i;
869
870 nbytes = strlen (src);
871
872 for (i = 0; i < nbytes; i++)
873 {
874 if (src[i] >= 0x80)
875 {
876 require_decoding = 1;
877 break;
878 }
879 }
880 }
881
882 if (require_decoding)
883 {
884 struct coding_system coding;
885 Lisp_Object coding_system = Qnil;
886 Lisp_Object dos_coding_system;
887
888 /* `next-selection-coding-system' should override everything,
889 even when the locale passed by the system disagrees. The
890 only exception is when `next-selection-coding-system'
891 requested CF_UNICODETEXT and we couldn't get that. */
892 if (use_configured_coding_system
893 && !NILP (Vnext_selection_coding_system))
894 coding_system = Vnext_selection_coding_system;
895
896 /* If we have CF_TEXT or CF_OEMTEXT, we want to check out
897 CF_LOCALE, too. */
898 else if (actual_clipboard_type != CF_UNICODETEXT)
899 {
900 HGLOBAL hlocale;
901 LCID lcid = DEFAULT_LCID;
902 UINT cp;
903
904 /* Documentation says that the OS always generates
905 CF_LOCALE info automatically, so the locale handle
906 should always be present. Fact is that this is not
907 always true on 9x ;-(. */
908 hlocale = GetClipboardData (CF_LOCALE);
909 if (hlocale != NULL)
910 {
911 const LCID * lcid_ptr;
912 lcid_ptr = (const LCID *) GlobalLock (hlocale);
913 if (lcid_ptr != NULL)
914 {
915 lcid = *lcid_ptr;
916 GlobalUnlock (hlocale);
917 }
918
919 /* 9x has garbage as the sort order (to be exact there
920 is another instance of the language id in the upper
921 word). We don't care about sort order anyway, so
922 we just filter out the unneeded mis-information to
923 avoid irritations. */
924 lcid = MAKELCID (LANGIDFROMLCID (lcid), SORT_DEFAULT);
925 }
926
927 /* If we are using fallback from CF_UNICODETEXT, we can't
928 use the configured coding system. Also we don't want
929 to use it, if the system has supplied us with a locale
930 and it is not just the system default. */
931 if (!use_configured_coding_system || lcid != DEFAULT_LCID)
932 {
933 cp = cp_from_locale (lcid, actual_clipboard_type);
934 /* If it's just our current standard setting anyway,
935 use the coding system that the user has selected.
936 Otherwise create a new spec to match the locale
937 that was specified by the other side or the
938 system. */
939 if (!use_configured_coding_system || cp != cfg_codepage)
940 coding_system = coding_from_cp (cp);
941 }
942 }
943
944 if (NILP (coding_system))
945 coding_system = Vselection_coding_system;
946 Vnext_selection_coding_system = Qnil;
947
948 dos_coding_system = validate_coding_system (coding_system);
949 if (!NILP (dos_coding_system))
950 {
951 setup_windows_coding_system (dos_coding_system, &coding);
952 coding.source = src;
953 decode_coding_object (&coding, Qnil, 0, 0, nbytes, nbytes, Qt);
954 ret = coding.dst_object;
955
956 Vlast_coding_system_used = CODING_ID_NAME (coding.id);
957 }
958 }
959 else
960 {
961 /* FIXME: We may want to repeat the code in this branch for
962 the Unicode case. */
963
964 /* Need to know final size after CR chars are removed because
965 we can't change the string size manually, and doing an
966 extra copy is silly. We only remove CR when it appears as
967 part of CRLF. */
968
969 truelen = nbytes;
970 dst = src;
971 /* avoid using strchr because it recomputes the length everytime */
972 while ((dst = memchr (dst, '\r', nbytes - (dst - src))) != NULL)
973 {
974 if (dst[1] == '\n') /* safe because of trailing '\0' */
975 truelen--;
976 dst++;
977 }
978
979 ret = make_uninit_string (truelen);
980
981 /* Convert CRLF line endings (the standard CF_TEXT clipboard
982 format) to LF endings as used internally by Emacs. */
983
984 dst = SDATA (ret);
985 while (1)
986 {
987 unsigned char *next;
988 /* copy next line or remaining bytes excluding '\0' */
989 next = _memccpy (dst, src, '\r', nbytes);
990 if (next)
991 {
992 /* copied one line ending with '\r' */
993 int copied = next - dst;
994 nbytes -= copied;
995 dst += copied;
996 src += copied;
997 if (*src == '\n')
998 dst--; /* overwrite '\r' with '\n' */
999 }
1000 else
1001 /* copied remaining partial line -> now finished */
1002 break;
1003 }
1004
1005 Vlast_coding_system_used = Qraw_text;
1006 }
1007
1008 GlobalUnlock (htext);
1009 }
1010
1011 closeclip:
1012 CloseClipboard ();
1013
1014 done:
1015 UNBLOCK_INPUT;
1016
1017 return (ret);
1018 }
1019
1020 /* Support checking for a clipboard selection. */
1021
1022 DEFUN ("x-selection-exists-p", Fx_selection_exists_p, Sx_selection_exists_p,
1023 0, 1, 0,
1024 doc: /* Whether there is an owner for the given X Selection.
1025 The arg should be the name of the selection in question, typically one of
1026 the symbols `PRIMARY', `SECONDARY', or `CLIPBOARD'.
1027 \(Those are literal upper-case symbol names, since that's what X expects.)
1028 For convenience, the symbol nil is the same as `PRIMARY',
1029 and t is the same as `SECONDARY'. */)
1030 (selection)
1031 Lisp_Object selection;
1032 {
1033 CHECK_SYMBOL (selection);
1034
1035 /* Return nil for PRIMARY and SECONDARY selections; for CLIPBOARD, check
1036 if the clipboard currently has valid text format contents. */
1037
1038 if (EQ (selection, QCLIPBOARD))
1039 {
1040 Lisp_Object val = Qnil;
1041
1042 setup_config ();
1043
1044 if (OpenClipboard (NULL))
1045 {
1046 UINT format = 0;
1047 while ((format = EnumClipboardFormats (format)))
1048 /* Check CF_TEXT in addition to cfg_clipboard_type,
1049 because we can fall back on that if CF_UNICODETEXT is
1050 not available. Actually a check for CF_TEXT only
1051 should be enough. */
1052 if (format == cfg_clipboard_type || format == CF_TEXT)
1053 {
1054 val = Qt;
1055 break;
1056 }
1057 CloseClipboard ();
1058 }
1059 return val;
1060 }
1061 return Qnil;
1062 }
1063
1064 /* One-time init. Called in the un-dumped Emacs, but not in the
1065 dumped version. */
1066
1067 void
1068 syms_of_w32select ()
1069 {
1070 defsubr (&Sw32_set_clipboard_data);
1071 defsubr (&Sw32_get_clipboard_data);
1072 defsubr (&Sx_selection_exists_p);
1073
1074 DEFVAR_LISP ("selection-coding-system", &Vselection_coding_system,
1075 doc: /* Coding system for communicating with other programs.
1076 When sending or receiving text via cut_buffer, selection, and
1077 clipboard, the text is encoded or decoded by this coding system.
1078 The default value is the current system default encoding on 9x/Me and
1079 `utf-16le-dos' (Unicode) on NT/W2K/XP. */);
1080 /* The actual value is set dynamically in the dumped Emacs, see
1081 below. */
1082 Vselection_coding_system = Qnil;
1083
1084 DEFVAR_LISP ("next-selection-coding-system", &Vnext_selection_coding_system,
1085 doc: /* Coding system for the next communication with other programs.
1086 Usually, `selection-coding-system' is used for communicating with
1087 other programs. But, if this variable is set, it is used for the
1088 next communication only. After the communication, this variable is
1089 set to nil. */);
1090 Vnext_selection_coding_system = Qnil;
1091
1092 QCLIPBOARD = intern ("CLIPBOARD"); staticpro (&QCLIPBOARD);
1093
1094 cfg_coding_system = Qnil; staticpro (&cfg_coding_system);
1095 current_text = Qnil; staticpro (&current_text);
1096 current_coding_system = Qnil; staticpro (&current_coding_system);
1097
1098 QUNICODE = intern ("utf-16le-dos"); staticpro (&QUNICODE);
1099 QANSICP = Qnil; staticpro (&QANSICP);
1100 QOEMCP = Qnil; staticpro (&QOEMCP);
1101 }
1102
1103 /* One-time init. Called in the dumped Emacs, but not in the
1104 un-dumped version. */
1105
1106 void
1107 globals_of_w32select ()
1108 {
1109 DEFAULT_LCID = GetUserDefaultLCID ();
1110 /* Drop the sort order from the LCID, so we can compare this with
1111 CF_LOCALE objects that have the same fix on 9x. */
1112 DEFAULT_LCID = MAKELCID (LANGIDFROMLCID (DEFAULT_LCID), SORT_DEFAULT);
1113
1114 ANSICP = GetACP ();
1115 OEMCP = GetOEMCP ();
1116
1117 QANSICP = coding_from_cp (ANSICP);
1118 QOEMCP = coding_from_cp (OEMCP);
1119
1120 if (os_subtype == OS_NT)
1121 Vselection_coding_system = QUNICODE;
1122 else if (inhibit_window_system)
1123 Vselection_coding_system = QOEMCP;
1124 else
1125 Vselection_coding_system = QANSICP;
1126
1127 clipboard_owner = create_owner ();
1128 }
1129
1130 /* arch-tag: c96e9724-5eb1-4dad-be07-289f092fd2af
1131 (do not change this comment) */