(x_set_alpha): Set alpha to -1 if nil given.
[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,
8cabe764 3 2005, 2006, 2007, 2008 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).
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 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:
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
ee78dc32
GV
75#include <config.h>
76#include "lisp.h"
fbd6baed 77#include "w32term.h" /* for all of the w32 includes */
52c7f9ee 78#include "w32heap.h" /* os_subtype */
ee78dc32 79#include "blockinput.h"
52c7f9ee 80#include "keyboard.h" /* cmd_error_internal() */
bbb059f3
AI
81#include "charset.h"
82#include "coding.h"
c949d9d0 83#include "character.h"
f7d05dc4 84#include "composite.h"
ee78dc32 85
52c7f9ee
JR
86
87static HGLOBAL convert_to_handle_as_ascii (void);
88static HGLOBAL convert_to_handle_as_coded (Lisp_Object coding_system);
89static Lisp_Object render (Lisp_Object oformat);
90static Lisp_Object render_locale (void);
91static Lisp_Object render_all (void);
92static void run_protected (Lisp_Object (*code) (), Lisp_Object arg);
93static Lisp_Object lisp_error_handler (Lisp_Object error);
94static LRESULT CALLBACK owner_callback (HWND win, UINT msg,
95 WPARAM wp, LPARAM lp);
96static HWND create_owner (void);
97
98static void setup_config (void);
99static BOOL WINAPI enum_locale_callback (/*const*/ char* loc_string);
100static UINT cp_from_locale (LCID lcid, UINT format);
101static Lisp_Object coding_from_cp (UINT codepage);
9a38f8d5
KH
102static Lisp_Object validate_coding_system (Lisp_Object coding_system);
103static void setup_windows_coding_system (Lisp_Object coding_system,
104 struct coding_system * coding);
52c7f9ee
JR
105
106
107/* A remnant from X11: Symbol for the CLIPBORD selection type. Other
108 selections are not used on Windows, so we don't need symbols for
109 PRIMARY and SECONDARY. */
9aa94bd5
KH
110Lisp_Object QCLIPBOARD;
111
52c7f9ee 112/* Coding system for communicating with other programs via the
bbb059f3 113 clipboard. */
72aca5fa 114static Lisp_Object Vselection_coding_system;
bbb059f3 115
52c7f9ee 116/* Coding system for the next communication with other programs. */
93cbf229
GV
117static Lisp_Object Vnext_selection_coding_system;
118
52c7f9ee
JR
119/* Internal pseudo-constants, initialized in globals_of_w32select()
120 based on current system parameters. */
121static LCID DEFAULT_LCID;
122static UINT ANSICP, OEMCP;
123static Lisp_Object QUNICODE, QANSICP, QOEMCP;
124
125/* A hidden window just for the clipboard management. */
126static HWND clipboard_owner;
127/* A flag to tell WM_DESTROYCLIPBOARD who is to blame this time (just
128 checking GetClipboardOwner() doesn't work, sadly). */
129static int modifying_clipboard = 0;
130
131/* Configured transfer parameters, based on the last inspection of
132 selection-coding-system. */
133static Lisp_Object cfg_coding_system;
134static UINT cfg_codepage;
135static LCID cfg_lcid;
136static UINT cfg_clipboard_type;
137
138/* The current state for delayed rendering. */
139static Lisp_Object current_text;
140static Lisp_Object current_coding_system;
141static int current_requires_encoding, current_num_nls;
142static UINT current_clipboard_type;
143static LCID current_lcid;
144
145#if TRACE
146#define ONTRACE(stmt) stmt
147#else
148#define ONTRACE(stmt) /*stmt*/
149#endif
150
151
152/* This function assumes that there is no multibyte character in
153 current_text, so we can short-cut encoding. */
154
155static HGLOBAL
156convert_to_handle_as_ascii (void)
ee78dc32 157{
52c7f9ee
JR
158 HGLOBAL htext = NULL;
159 int nbytes;
160 int truelen;
161 unsigned char *src;
162 unsigned char *dst;
41a48e45 163
52c7f9ee 164 ONTRACE (fprintf (stderr, "convert_to_handle_as_ascii\n"));
41a48e45 165
52c7f9ee
JR
166 nbytes = SBYTES (current_text) + 1;
167 src = SDATA (current_text);
41a48e45 168
52c7f9ee
JR
169 /* We need to add to the size the number of LF chars where we have
170 to insert CR chars (the standard CF_TEXT clipboard format uses
171 CRLF line endings, while Emacs uses just LF internally). */
41a48e45 172
52c7f9ee
JR
173 truelen = nbytes + current_num_nls;
174
175 if ((htext = GlobalAlloc (GMEM_MOVEABLE | GMEM_DDESHARE, truelen)) == NULL)
176 return NULL;
41a48e45 177
52c7f9ee
JR
178 if ((dst = (unsigned char *) GlobalLock (htext)) == NULL)
179 {
180 GlobalFree (htext);
181 return NULL;
182 }
183
184 /* convert to CRLF line endings expected by clipboard */
185 while (1)
186 {
187 unsigned char *next;
188 /* copy next line or remaining bytes including '\0' */
189 next = _memccpy (dst, src, '\n', nbytes);
190 if (next)
191 {
192 /* copied one line ending with '\n' */
193 int copied = next - dst;
194 nbytes -= copied;
195 src += copied;
196 /* insert '\r' before '\n' */
197 next[-1] = '\r';
198 next[0] = '\n';
199 dst = next + 1;
200 }
201 else
202 /* copied remaining partial line -> now finished */
203 break;
204 }
205
206 GlobalUnlock (htext);
207
208 return htext;
ee78dc32
GV
209}
210
52c7f9ee
JR
211/* This function assumes that there are multibyte or NUL characters in
212 current_text, or that we need to construct Unicode. It runs the
213 text through the encoding machinery. */
214
215static HGLOBAL
216convert_to_handle_as_coded (Lisp_Object coding_system)
ee78dc32 217{
9a38f8d5 218 HGLOBAL htext;
52c7f9ee 219 unsigned char *dst = NULL;
52c7f9ee 220 struct coding_system coding;
52c7f9ee
JR
221
222 ONTRACE (fprintf (stderr, "convert_to_handle_as_coded: %s\n",
223 SDATA (SYMBOL_NAME (coding_system))));
224
9a38f8d5
KH
225 setup_windows_coding_system (coding_system, &coding);
226 coding.dst_bytes = SBYTES(current_text) * 2;
227 coding.destination = (unsigned char *) xmalloc (coding.dst_bytes);
228 encode_coding_object (&coding, current_text, 0, 0,
229 SCHARS (current_text), SBYTES (current_text), Qnil);
41a48e45 230
9a38f8d5 231 htext = GlobalAlloc (GMEM_MOVEABLE | GMEM_DDESHARE, coding.produced +2);
41a48e45 232
52c7f9ee
JR
233 if (htext != NULL)
234 dst = (unsigned char *) GlobalLock (htext);
41a48e45 235
52c7f9ee
JR
236 if (dst != NULL)
237 {
9a38f8d5 238 memcpy (dst, coding.destination, coding.produced);
52c7f9ee
JR
239 /* Add the string terminator. Add two NULs in case we are
240 producing Unicode here. */
241 dst[coding.produced] = dst[coding.produced+1] = '\0';
52c7f9ee 242
9a38f8d5 243 GlobalUnlock (htext);
52c7f9ee
JR
244 }
245
9a38f8d5
KH
246 xfree (coding.destination);
247
52c7f9ee 248 return htext;
ee78dc32
GV
249}
250
52c7f9ee
JR
251static Lisp_Object
252render (Lisp_Object oformat)
ee78dc32 253{
52c7f9ee
JR
254 HGLOBAL htext = NULL;
255 UINT format = XFASTINT (oformat);
256
257 ONTRACE (fprintf (stderr, "render\n"));
258
259 if (NILP (current_text))
260 return Qnil;
261
262 if (current_requires_encoding || format == CF_UNICODETEXT)
263 {
264 if (format == current_clipboard_type)
265 htext = convert_to_handle_as_coded (current_coding_system);
266 else
267 switch (format)
268 {
269 case CF_UNICODETEXT:
270 htext = convert_to_handle_as_coded (QUNICODE);
271 break;
272 case CF_TEXT:
273 case CF_OEMTEXT:
274 {
275 Lisp_Object cs;
276 cs = coding_from_cp (cp_from_locale (current_lcid, format));
277 htext = convert_to_handle_as_coded (cs);
278 break;
279 }
280 }
281 }
282 else
283 htext = convert_to_handle_as_ascii ();
284
285 ONTRACE (fprintf (stderr, "render: htext = 0x%08X\n", (unsigned) htext));
286
287 if (htext == NULL)
288 return Qnil;
289
290 if (SetClipboardData (format, htext) == NULL)
291 {
292 GlobalFree(htext);
293 return Qnil;
294 }
295
296 return Qt;
ee78dc32
GV
297}
298
52c7f9ee
JR
299static Lisp_Object
300render_locale (void)
ee78dc32 301{
52c7f9ee
JR
302 HANDLE hlocale = NULL;
303 LCID * lcid_ptr;
304
305 ONTRACE (fprintf (stderr, "render_locale\n"));
306
307 if (current_lcid == LOCALE_NEUTRAL || current_lcid == DEFAULT_LCID)
308 return Qt;
309
310 hlocale = GlobalAlloc (GMEM_MOVEABLE | GMEM_DDESHARE, sizeof (current_lcid));
311 if (hlocale == NULL)
312 return Qnil;
313
314 if ((lcid_ptr = (LCID *) GlobalLock (hlocale)) == NULL)
315 {
316 GlobalFree(hlocale);
317 return Qnil;
318 }
319
320 *lcid_ptr = current_lcid;
321 GlobalUnlock (hlocale);
322
323 if (SetClipboardData (CF_LOCALE, hlocale) == NULL)
324 {
325 GlobalFree(hlocale);
326 return Qnil;
327 }
328
329 return Qt;
330}
331
332/* At the end of the program, we want to ensure that our clipboard
333 data survives us. This code will do that. */
334
335static Lisp_Object
336render_all (void)
337{
338 ONTRACE (fprintf (stderr, "render_all\n"));
339
340 /* According to the docs we should not call OpenClipboard() here,
341 but testing on W2K and working code in other projects shows that
342 it is actually necessary. */
343
344 OpenClipboard (NULL);
345
346 /* There is no usefull means to report errors here, there are none
347 expected anyway, and even if there were errors, they wouldn't do
348 any harm. So we just go ahead and do what has to be done without
349 bothering with error handling. */
350
351 ++modifying_clipboard;
352 EmptyClipboard ();
353 --modifying_clipboard;
354
355 /* For text formats that we don't render here, the OS can use its
356 own translation rules instead, so we don't really need to offer
357 everything. To minimize memory consumption we cover three
358 possible situations based on our primary format as detected from
359 selection-coding-system (see setup_config()):
360
361 - Post CF_TEXT only. Let the OS convert to CF_OEMTEXT and the OS
362 (on NT) or the application (on 9x/Me) convert to
363 CF_UNICODETEXT.
364
365 - Post CF_OEMTEXT only. Similar automatic conversions happen as
366 for CF_TEXT.
367
368 - Post CF_UNICODETEXT + CF_TEXT. 9x itself ignores
369 CF_UNICODETEXT, even though some applications can still handle
370 it.
371
372 Note 1: We render the less capable CF_TEXT *before* the more
373 capable CF_UNICODETEXT, to prevent clobbering through automatic
374 conversions, just in case.
375
376 Note 2: We could check os_subtype here and only render the
377 additional CF_TEXT on 9x/Me. But OTOH with
378 current_clipboard_type == CF_UNICODETEXT we don't involve the
379 automatic conversions anywhere else, so to get consistent
380 results, we probably don't want to rely on it here either. */
381
382 render_locale();
383
384 if (current_clipboard_type == CF_UNICODETEXT)
385 render (make_number (CF_TEXT));
386 render (make_number (current_clipboard_type));
387
388 CloseClipboard ();
389
390 return Qnil;
391}
392
393static void
394run_protected (Lisp_Object (*code) (), Lisp_Object arg)
395{
396 /* FIXME: This works but it doesn't feel right. Too much fiddling
397 with global variables and calling strange looking functions. Is
398 this really the right way to run Lisp callbacks? */
399
400 extern int waiting_for_input;
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;
52c7f9ee
JR
516
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 }
585
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. */)
52c7f9ee
JR
683 (string, ignored)
684 Lisp_Object string, ignored;
ee78dc32
GV
685{
686 BOOL ok = TRUE;
69cddef0 687 int nbytes;
69cddef0
GV
688 unsigned char *src;
689 unsigned char *dst;
52c7f9ee 690 unsigned char *end;
06466d9a 691
52c7f9ee
JR
692 /* This parameter used to be the current frame, but we don't use
693 that any more. */
694 (void) ignored;
41a48e45 695
b7826503 696 CHECK_STRING (string);
41a48e45 697
52c7f9ee 698 setup_config ();
41a48e45 699
52c7f9ee
JR
700 current_text = string;
701 current_coding_system = cfg_coding_system;
702 current_clipboard_type = cfg_clipboard_type;
703 current_lcid = cfg_lcid;
704 current_num_nls = 0;
705 current_requires_encoding = 0;
706
ee78dc32 707 BLOCK_INPUT;
69cddef0 708
52c7f9ee
JR
709 /* Check for non-ASCII characters. While we are at it, count the
710 number of LFs, so we know how many CRs we will have to add later
711 (just in the case where we can use our internal ASCII rendering,
712 see code and comment in convert_to_handle_as_ascii() above). */
713 nbytes = SBYTES (string);
d5db4077 714 src = SDATA (string);
0ece9ef6 715
52c7f9ee 716 for (dst = src, end = src+nbytes; dst < end; dst++)
0ece9ef6 717 {
52c7f9ee
JR
718 if (*dst == '\n')
719 current_num_nls++;
720 else if (*dst >= 0x80 || *dst == 0)
721 {
722 current_requires_encoding = 1;
723 break;
724 }
0ece9ef6 725 }
69cddef0 726
52c7f9ee
JR
727 if (!current_requires_encoding)
728 {
729 /* If all we have is ASCII we don't need to pretend we offer
730 anything fancy. */
731 current_coding_system = Qraw_text;
732 current_clipboard_type = CF_TEXT;
733 current_lcid = LOCALE_NEUTRAL;
734 }
0108f679 735
52c7f9ee 736 if (!OpenClipboard (clipboard_owner))
ee78dc32 737 goto error;
06466d9a 738
52c7f9ee
JR
739 ++modifying_clipboard;
740 ok = EmptyClipboard ();
741 --modifying_clipboard;
06466d9a 742
52c7f9ee
JR
743 /* If we have something non-ASCII we may want to set a locale. We
744 do that directly (non-delayed), as it's just a small bit. */
745 if (ok)
746 ok = !NILP(render_locale());
06466d9a 747
52c7f9ee
JR
748 if (ok)
749 {
750 if (clipboard_owner == NULL)
751 {
752 /* If for some reason we don't have a clipboard_owner, we
753 just set the text format as chosen by the configuration
754 and than forget about the whole thing. */
755 ok = !NILP(render (make_number (current_clipboard_type)));
756 current_text = Qnil;
757 current_coding_system = Qnil;
758 }
759 else
760 {
761 /* Advertise all supported formats so that whatever the
762 requester chooses, only one encoding step needs to be
763 made. This is intentionally different from what we do in
764 the handler for WM_RENDERALLFORMATS. */
765 SetClipboardData (CF_UNICODETEXT, NULL);
766 SetClipboardData (CF_TEXT, NULL);
767 SetClipboardData (CF_OEMTEXT, NULL);
768 }
769 }
41a48e45 770
6383ca22
JR
771 CloseClipboard ();
772
52c7f9ee
JR
773 /* With delayed rendering we haven't really "used" this coding
774 system yet, and it's even unclear if we ever will. But this is a
775 way to tell the upper level what we *would* use under ideal
776 circumstances.
41a48e45 777
52c7f9ee
JR
778 We don't signal the actually used coding-system later when we
779 finally render, because that can happen at any time and we don't
780 want to disturb the "foreground" action. */
781 if (ok)
782 Vlast_coding_system_used = current_coding_system;
6383ca22 783
52c7f9ee 784 Vnext_selection_coding_system = Qnil;
ee79d1aa 785
ee78dc32
GV
786 if (ok) goto done;
787
788 error:
41a48e45 789
ee78dc32 790 ok = FALSE;
52c7f9ee
JR
791 current_text = Qnil;
792 current_coding_system = Qnil;
ee79d1aa 793
ee78dc32
GV
794 done:
795 UNBLOCK_INPUT;
41a48e45 796
ee78dc32
GV
797 return (ok ? string : Qnil);
798}
799
52c7f9ee 800
33f09670
JR
801DEFUN ("w32-get-clipboard-data", Fw32_get_clipboard_data,
802 Sw32_get_clipboard_data, 0, 1, 0,
803 doc: /* This gets the clipboard data in text format. */)
52c7f9ee
JR
804 (ignored)
805 Lisp_Object ignored;
ee78dc32 806{
52c7f9ee 807 HGLOBAL htext;
ee78dc32 808 Lisp_Object ret = Qnil;
52c7f9ee
JR
809 UINT actual_clipboard_type;
810 int use_configured_coding_system = 1;
811
812 /* This parameter used to be the current frame, but we don't use
813 that any more. */
814 (void) ignored;
41a48e45 815
52c7f9ee
JR
816 /* Don't pass our own text from the clipboard (which might be
817 troublesome if the killed text includes null characters). */
818 if (!NILP (current_text))
819 return ret;
820
821 setup_config ();
822 actual_clipboard_type = cfg_clipboard_type;
41a48e45 823
ee78dc32 824 BLOCK_INPUT;
41a48e45 825
52c7f9ee 826 if (!OpenClipboard (clipboard_owner))
ee78dc32 827 goto done;
41a48e45 828
52c7f9ee
JR
829 if ((htext = GetClipboardData (actual_clipboard_type)) == NULL)
830 {
831 /* If we want CF_UNICODETEXT but can't get it, the current
832 coding system is useless. OTOH we can still try and decode
833 CF_TEXT based on the locale that the system gives us and that
834 we get down below. */
835 if (actual_clipboard_type == CF_UNICODETEXT)
836 {
837 htext = GetClipboardData (CF_TEXT);
838 if (htext != NULL)
839 {
840 actual_clipboard_type = CF_TEXT;
841 use_configured_coding_system = 0;
842 }
843 }
844 }
845 if (htext == NULL)
ee78dc32
GV
846 goto closeclip;
847
ee78dc32 848 {
69cddef0
GV
849 unsigned char *src;
850 unsigned char *dst;
ee78dc32 851 int nbytes;
69cddef0 852 int truelen;
c0ca703b 853 int require_decoding = 0;
41a48e45 854
69cddef0 855 if ((src = (unsigned char *) GlobalLock (htext)) == NULL)
ee78dc32 856 goto closeclip;
41a48e45 857
52c7f9ee
JR
858 /* If the clipboard data contains any non-ascii code, we need to
859 decode it with a coding system. */
860 if (actual_clipboard_type == CF_UNICODETEXT)
861 {
862 nbytes = lstrlenW ((WCHAR *)src) * 2;
863 require_decoding = 1;
864 }
865 else
866 {
867 int i;
06466d9a 868
52c7f9ee 869 nbytes = strlen (src);
aab7e392 870
52c7f9ee
JR
871 for (i = 0; i < nbytes; i++)
872 {
873 if (src[i] >= 0x80)
874 {
875 require_decoding = 1;
876 break;
877 }
878 }
879 }
93cbf229 880
c0ca703b 881 if (require_decoding)
69cddef0 882 {
bbb059f3 883 struct coding_system coding;
52c7f9ee 884 Lisp_Object coding_system = Qnil;
9a38f8d5 885 Lisp_Object dos_coding_system;
52c7f9ee
JR
886
887 /* `next-selection-coding-system' should override everything,
888 even when the locale passed by the system disagrees. The
889 only exception is when `next-selection-coding-system'
890 requested CF_UNICODETEXT and we couldn't get that. */
891 if (use_configured_coding_system
892 && !NILP (Vnext_selection_coding_system))
893 coding_system = Vnext_selection_coding_system;
894
895 /* If we have CF_TEXT or CF_OEMTEXT, we want to check out
896 CF_LOCALE, too. */
897 else if (actual_clipboard_type != CF_UNICODETEXT)
898 {
899 HGLOBAL hlocale;
900 LCID lcid = DEFAULT_LCID;
901 UINT cp;
902
903 /* Documentation says that the OS always generates
904 CF_LOCALE info automatically, so the locale handle
905 should always be present. Fact is that this is not
906 always true on 9x ;-(. */
907 hlocale = GetClipboardData (CF_LOCALE);
908 if (hlocale != NULL)
909 {
910 const LCID * lcid_ptr;
911 lcid_ptr = (const LCID *) GlobalLock (hlocale);
912 if (lcid_ptr != NULL)
913 {
914 lcid = *lcid_ptr;
915 GlobalUnlock (hlocale);
916 }
917
918 /* 9x has garbage as the sort order (to be exact there
919 is another instance of the language id in the upper
920 word). We don't care about sort order anyway, so
921 we just filter out the unneeded mis-information to
922 avoid irritations. */
923 lcid = MAKELCID (LANGIDFROMLCID (lcid), SORT_DEFAULT);
924 }
925
926 /* If we are using fallback from CF_UNICODETEXT, we can't
927 use the configured coding system. Also we don't want
928 to use it, if the system has supplied us with a locale
929 and it is not just the system default. */
930 if (!use_configured_coding_system || lcid != DEFAULT_LCID)
931 {
932 cp = cp_from_locale (lcid, actual_clipboard_type);
933 /* If it's just our current standard setting anyway,
934 use the coding system that the user has selected.
935 Otherwise create a new spec to match the locale
936 that was specified by the other side or the
937 system. */
938 if (!use_configured_coding_system || cp != cfg_codepage)
939 coding_system = coding_from_cp (cp);
940 }
941 }
942
943 if (NILP (coding_system))
944 coding_system = Vselection_coding_system;
945 Vnext_selection_coding_system = Qnil;
bbb059f3 946
9a38f8d5
KH
947 dos_coding_system = validate_coding_system (coding_system);
948 if (!NILP (dos_coding_system))
949 {
950 setup_windows_coding_system (dos_coding_system, &coding);
951 coding.source = src;
952 decode_coding_object (&coding, Qnil, 0, 0, nbytes, nbytes, Qt);
953 ret = coding.dst_object;
954
955 Vlast_coding_system_used = CODING_ID_NAME (coding.id);
956 }
69cddef0 957 }
bbb059f3
AI
958 else
959 {
52c7f9ee
JR
960 /* FIXME: We may want to repeat the code in this branch for
961 the Unicode case. */
962
963 /* Need to know final size after CR chars are removed because
964 we can't change the string size manually, and doing an
965 extra copy is silly. We only remove CR when it appears as
966 part of CRLF. */
bbb059f3
AI
967
968 truelen = nbytes;
969 dst = src;
970 /* avoid using strchr because it recomputes the length everytime */
971 while ((dst = memchr (dst, '\r', nbytes - (dst - src))) != NULL)
972 {
c0ca703b
GV
973 if (dst[1] == '\n') /* safe because of trailing '\0' */
974 truelen--;
bbb059f3
AI
975 dst++;
976 }
69cddef0 977
bbb059f3 978 ret = make_uninit_string (truelen);
69cddef0 979
c0ca703b
GV
980 /* Convert CRLF line endings (the standard CF_TEXT clipboard
981 format) to LF endings as used internally by Emacs. */
69cddef0 982
d5db4077 983 dst = SDATA (ret);
bbb059f3 984 while (1)
69cddef0 985 {
bbb059f3
AI
986 unsigned char *next;
987 /* copy next line or remaining bytes excluding '\0' */
988 next = _memccpy (dst, src, '\r', nbytes);
989 if (next)
990 {
991 /* copied one line ending with '\r' */
992 int copied = next - dst;
993 nbytes -= copied;
c0ca703b 994 dst += copied;
bbb059f3 995 src += copied;
c0ca703b
GV
996 if (*src == '\n')
997 dst--; /* overwrite '\r' with '\n' */
998 }
bbb059f3
AI
999 else
1000 /* copied remaining partial line -> now finished */
1001 break;
1002 }
0108f679
AI
1003
1004 Vlast_coding_system_used = Qraw_text;
69cddef0
GV
1005 }
1006
ee78dc32
GV
1007 GlobalUnlock (htext);
1008 }
1009
1010 closeclip:
1011 CloseClipboard ();
41a48e45 1012
ee78dc32
GV
1013 done:
1014 UNBLOCK_INPUT;
41a48e45 1015
ee78dc32
GV
1016 return (ret);
1017}
1018
9aa94bd5
KH
1019/* Support checking for a clipboard selection. */
1020
1021DEFUN ("x-selection-exists-p", Fx_selection_exists_p, Sx_selection_exists_p,
33f09670
JR
1022 0, 1, 0,
1023 doc: /* Whether there is an owner for the given X Selection.
1024The arg should be the name of the selection in question, typically one of
1025the symbols `PRIMARY', `SECONDARY', or `CLIPBOARD'.
1026\(Those are literal upper-case symbol names, since that's what X expects.)
1027For convenience, the symbol nil is the same as `PRIMARY',
1028and t is the same as `SECONDARY'. */)
9aa94bd5
KH
1029 (selection)
1030 Lisp_Object selection;
1031{
b7826503 1032 CHECK_SYMBOL (selection);
9aa94bd5
KH
1033
1034 /* Return nil for PRIMARY and SECONDARY selections; for CLIPBOARD, check
1035 if the clipboard currently has valid text format contents. */
1036
1037 if (EQ (selection, QCLIPBOARD))
1038 {
1039 Lisp_Object val = Qnil;
1040
9a38f8d5
KH
1041 setup_config ();
1042
9aa94bd5
KH
1043 if (OpenClipboard (NULL))
1044 {
52c7f9ee 1045 UINT format = 0;
52c7f9ee
JR
1046 while ((format = EnumClipboardFormats (format)))
1047 /* Check CF_TEXT in addition to cfg_clipboard_type,
1048 because we can fall back on that if CF_UNICODETEXT is
1049 not available. Actually a check for CF_TEXT only
1050 should be enough. */
1051 if (format == cfg_clipboard_type || format == CF_TEXT)
9aa94bd5
KH
1052 {
1053 val = Qt;
1054 break;
1055 }
1056 CloseClipboard ();
1057 }
1058 return val;
1059 }
1060 return Qnil;
1061}
1062
52c7f9ee
JR
1063/* One-time init. Called in the un-dumped Emacs, but not in the
1064 dumped version. */
1065
41a48e45 1066void
fbd6baed 1067syms_of_w32select ()
ee78dc32 1068{
fbd6baed
GV
1069 defsubr (&Sw32_set_clipboard_data);
1070 defsubr (&Sw32_get_clipboard_data);
9aa94bd5
KH
1071 defsubr (&Sx_selection_exists_p);
1072
72aca5fa 1073 DEFVAR_LISP ("selection-coding-system", &Vselection_coding_system,
33f09670 1074 doc: /* Coding system for communicating with other programs.
52c7f9ee
JR
1075When sending or receiving text via cut_buffer, selection, and
1076clipboard, the text is encoded or decoded by this coding system.
1077The default value is the current system default encoding on 9x/Me and
1078`utf-16le-dos' (Unicode) on NT/W2K/XP. */);
1079 /* The actual value is set dynamically in the dumped Emacs, see
1080 below. */
1081 Vselection_coding_system = Qnil;
bbb059f3 1082
93cbf229 1083 DEFVAR_LISP ("next-selection-coding-system", &Vnext_selection_coding_system,
33f09670
JR
1084 doc: /* Coding system for the next communication with other programs.
1085Usually, `selection-coding-system' is used for communicating with
3b32ae2c
JB
1086other programs. But, if this variable is set, it is used for the
1087next communication only. After the communication, this variable is
33f09670 1088set to nil. */);
93cbf229
GV
1089 Vnext_selection_coding_system = Qnil;
1090
9c9d6d8b 1091 DEFSYM (QCLIPBOARD, "CLIPBOARD");
52c7f9ee
JR
1092
1093 cfg_coding_system = Qnil; staticpro (&cfg_coding_system);
1094 current_text = Qnil; staticpro (&current_text);
1095 current_coding_system = Qnil; staticpro (&current_coding_system);
1096
9c9d6d8b 1097 DEFSYM (QUNICODE, "utf-16le-dos");
52c7f9ee
JR
1098 QANSICP = Qnil; staticpro (&QANSICP);
1099 QOEMCP = Qnil; staticpro (&QOEMCP);
1100}
1101
1102/* One-time init. Called in the dumped Emacs, but not in the
1103 un-dumped version. */
1104
1105void
1106globals_of_w32select ()
1107{
1108 DEFAULT_LCID = GetUserDefaultLCID ();
1109 /* Drop the sort order from the LCID, so we can compare this with
1110 CF_LOCALE objects that have the same fix on 9x. */
1111 DEFAULT_LCID = MAKELCID (LANGIDFROMLCID (DEFAULT_LCID), SORT_DEFAULT);
1112
1113 ANSICP = GetACP ();
1114 OEMCP = GetOEMCP ();
1115
1116 QANSICP = coding_from_cp (ANSICP);
1117 QOEMCP = coding_from_cp (OEMCP);
1118
1119 if (os_subtype == OS_NT)
1120 Vselection_coding_system = QUNICODE;
1121 else if (inhibit_window_system)
1122 Vselection_coding_system = QOEMCP;
1123 else
1124 Vselection_coding_system = QANSICP;
1125
1126 clipboard_owner = create_owner ();
ee78dc32 1127}
6b61353c
KH
1128
1129/* arch-tag: c96e9724-5eb1-4dad-be07-289f092fd2af
1130 (do not change this comment) */