Remove ancient trunk folder from svn repository
[synfig.git] / synfig-osx / launcher / utils / dumpkeymap.c
1 // $XFree86: xc/programs/Xserver/hw/darwin/utils/dumpkeymap.c,v 1.3 2000/12/05 21:18:34 dawes Exp $
2 //=============================================================================
3 //
4 // Copyright (C) 1999,2000 by Eric Sunshine <sunshine@sunshineco.com>
5 // All rights reserved.
6 //
7 // Redistribution and use in source and binary forms, with or without
8 // modification, are permitted provided that the following conditions are met:
9 //
10 //   1. Redistributions of source code must retain the above copyright
11 //      notice, this list of conditions and the following disclaimer.
12 //   2. Redistributions in binary form must reproduce the above copyright
13 //      notice, this list of conditions and the following disclaimer in the
14 //      documentation and/or other materials provided with the distribution.
15 //   3. The name of the author may not be used to endorse or promote products
16 //      derived from this software without specific prior written permission.
17 //
18 // THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
19 // IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
20 // OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN
21 // NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
22 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
23 // TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
24 // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
25 // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
26 // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
27 // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28 //
29 //=============================================================================
30 //-----------------------------------------------------------------------------
31 // dumpkeymap.c
32 //
33 //      Prints a textual representation of each Apple/NeXT .keymapping file
34 //      mentioned on the command-line.  If no files are mentioned and if the
35 //      local machine is an Apple or NeXT installation, then the key mapping
36 //      currently in use by the WindowServer and the AppKit is printed
37 //      instead.
38 //
39 //      Invoke dumpkeymap with one of the options listed below in order to
40 //      view detailed documentation about .keymapping files and the use of
41 //      this program.
42 //
43 //      --help: Usage summary.
44 //      --help-keymapping: Detailed discussion of the internal format of a
45 //          .keymapping file.
46 //      --help-output: Explanation of dumpkeymap's output.
47 //      --help-files: List of key mapping-related files and directories.
48 //      --help-diagnostics: Explanation of diagnostic messages.
49 //
50 // COMPILATION INSTRUCTIONS
51 //
52 //      MacOS/X, Darwin
53 //      cc -Wall -o dumpkeymap dumpkeymap.c -framework IOKit
54 //
55 //      MacOS/X DP4 (Developer Preview 4)
56 //      cc -Wall -o dumpkeymap dumpkeymap.c -FKernel -framework IOKit
57 //
58 //      MacOS/X Server, OpenStep, NextStep
59 //      cc -Wall -o dumpkeymap dumpkeymap.c
60 //
61 //      By default, dumpkeymap is configured to interface with the HID driver
62 //      (Apple) or event-status driver (NeXT), thus allowing it to dump the
63 //      key mapping which is currently in use by the WindowServer and AppKit.
64 //      However, these facilities are specific to Apple/NeXT.  In order to
65 //      build dumpkeymap for non-Apple/NeXT platforms, you must define the
66 //      DUMPKEYMAP_FILE_ONLY flag when compiling the program.  This flag
67 //      inhibits use of the HID and event-status drivers and configures
68 //      dumpkeymap to work strictly with raw key mapping files.
69 //
70 //      For example, to compile for Linux:
71 //      gcc -Wall -DDUMPKEYMAP_FILE_ONLY -o dumpkeymap dumpkeymap.c
72 //
73 // CONCLUSION
74 //
75 //      This program and its accompanying documentation were written by Eric
76 //      Sunshine and are copyright (C)1999,2000 by Eric Sunshine
77 //      <sunshine@sunshineco.com>.
78 //
79 //      The implementation of dumpkeymap is based upon information gathered
80 //      on September 3, 1997 by Eric Sunshine <sunshine@sunshineco.com> and
81 //      Paul S. McCarthy <zarnuk@zarnuk.com> during an effort to reverse
82 //      engineer the format of the NeXT .keymapping file.
83 //
84 // HISTORY
85 //
86 //      v4 2000/12/01 Eric Sunshine <sunshine@sunshineco.com>
87 //          Updated manual page to work with `rman', the `man' to `HTML'
88 //              translator.  Unfortunately, however, rman is missing important
89 //              roff features such as diversions, indentation, and tab stops,
90 //              and is also hideously buggy, so getting the manual to work with
91 //              rman required quite a few work-arounds.
92 //          The manual page has now been tested with nroff (plain text), troff
93 //              (PostScript, etc.), groff (PostScript), and rman (HTML, etc.)
94 //
95 //      v3 2000/11/28 Eric Sunshine <sunshine@sunshineco.com>
96 //          Considerably expanded the documentation.
97 //          Augmented the existing description of .keymapping internals.
98 //          Added these new documentation topics:
99 //              - Output: Very important section describing how to interpret
100 //                the output of dumpkeymap.
101 //              - Files: Lists files and directories related to key mappings.
102 //              - Diagnostics: Explains diagnostic messages issued by
103 //                dumpkeymap.
104 //          Created a manual page (dumpkeymap.1) which contains the complete
105 //              set of documentation for key mapping files and dumpkeymap.
106 //          Added command-line options (--help, --help-keymapping,
107 //              --help-output, --help-files, --help-diagnostics) which allow
108 //              access to all key mapping documentation.  Previously the
109 //              description of the internal layout of a .keymapping file was
110 //              only available as source code comments.
111 //          Added --version option.
112 //          Ported to non-Apple/NeXT platforms.  Defining the pre-processor
113 //              flag DUMPKEYMAP_FILE_ONLY at compilation time inhibits use of
114 //              Apple/NeXT-specific API.
115 //          Added a README file.
116 //
117 //      v2 2000/11/13 Eric Sunshine <sunshine@sunshineco.com>
118 //          Converted from C++ to plain-C.
119 //          Now parses and takes into account the "number-size" flag stored
120 //              with each key map.  This flag indicates the size, in bytes, of
121 //              all remaining numeric values in the mapping.  Updated all code
122 //              to respect this flag.  (Previously, the purpose of this field
123 //              was unknown, and it was thus denoted as
124 //              `KeyMapping::fill[2]'.)
125 //          Updated all documentation; especially the "KEY MAPPING
126 //              DESCRIPTION" section.  Added discussion of the "number-size"
127 //              flag and revamped all structure definitions to use the generic
128 //              data type `number' instead of `uchar' or 'byte'.  Clarified
129 //              several sections of the documentation and added missing
130 //              discussions about type definitions and the relationship of
131 //              `interface' and `handler_id' to .keymapping and .keyboard
132 //              files.
133 //          Updated compilation instructions to include directions for all
134 //              platforms on which this program might be built.
135 //          Now published under the formal BSD license rather than a
136 //              home-grown license.
137 //
138 //      v1 1999/09/08 Eric Sunshine <sunshine@sunshineco.com>
139 //          Created.
140 //-----------------------------------------------------------------------------
141 #include <ctype.h>
142 #include <stdio.h>
143 #include <stdlib.h>
144 #include <sys/stat.h>
145 #if !defined(DUMPKEYMAP_FILE_ONLY)
146 #include <drivers/event_status_driver.h>
147 #endif
148
149 #define PROG_NAME "dumpkeymap"
150 #define PROG_VERSION "4"
151 #define AUTHOR_NAME "Eric Sunshine"
152 #define AUTHOR_EMAIL "sunshine@sunshineco.com"
153 #define AUTHOR_INFO AUTHOR_NAME " <" AUTHOR_EMAIL ">"
154 #define COPYRIGHT "Copyright (C) 1999,2000 by " AUTHOR_INFO
155
156 typedef unsigned char byte;
157 typedef unsigned short word;
158 typedef unsigned int natural;
159 typedef unsigned long dword;
160 typedef dword number;
161
162 #define ASCII_SET 0x00
163 #define BIND_FUNCTION 0xfe
164 #define BIND_SPECIAL 0xff
165
166 #define OPT_SWITCH(X) { char const* switched_str__=(X); if (0) {
167 #define OPT_CASE(X,Y) } else if (strcmp(switched_str__,(#X)) == 0 || \
168     strcmp(switched_str__,(#Y)) == 0) {
169 #define OPT_DEFAULT } else {
170 #define OPT_SWITCH_END }}
171
172 //-----------------------------------------------------------------------------
173 // Translation Tables
174 //-----------------------------------------------------------------------------
175 static char const* const SPECIAL_CODE[] =
176     {
177     "sound-up",
178     "sound-down",
179     "brightness-up",
180     "brightness-down",
181     "alpha-lock",
182     "help",
183     "power",
184     "secondary-up-arrow",
185     "secondary-down-arrow"
186     };
187 #define N_SPECIAL_CODE (sizeof(SPECIAL_CODE) / sizeof(SPECIAL_CODE[0]))
188
189 static char const* const MODIFIER_CODE[] =
190     {
191     "alpha-lock",
192     "shift",
193     "control",
194     "alternate",
195     "command",
196     "keypad",
197     "help"
198     };
199 #define N_MODIFIER_CODE (sizeof(MODIFIER_CODE) / sizeof(MODIFIER_CODE[0]))
200
201 static char const* const MODIFIER_MASK[] =
202     {
203     "-----",    // R = carriage-return
204     "----L",    // A = alternate
205     "---S-",    // C = control
206     "---SL",    // S = shift
207     "--C--",    // L = alpha-lock
208     "--C-L",
209     "--CS-",
210     "--CSL",
211     "-A---",
212     "-A--L",
213     "-A-S-",
214     "-A-SL",
215     "-AC--",
216     "-AC-L",
217     "-ACS-",
218     "-ACSL",
219     "R----",
220     "R---L",
221     "R--S-",
222     "R--SL",
223     "R-C--",
224     "R-C-L",
225     "R-CS-",
226     "R-CSL",
227     "RA---",
228     "RA--L",
229     "RA-S-",
230     "RA-SL",
231     "RAC--",
232     "RAC-L",
233     "RACS-",
234     "RACSL",
235     };
236 #define N_MODIFIER_MASK (sizeof(MODIFIER_MASK) / sizeof(MODIFIER_MASK[0]))
237
238 #define FUNCTION_KEY_FIRST 0x20
239 static char const* const FUNCTION_KEY[] =
240     {
241     "F1",                       // 0x20
242     "F2",                       // 0x21
243     "F3",                       // 0x22
244     "F4",                       // 0x23
245     "F5",                       // 0x24
246     "F6",                       // 0x25
247     "F7",                       // 0x26
248     "F8",                       // 0x27
249     "F9",                       // 0x28
250     "F10",                      // 0x29
251     "F11",                      // 0x2a
252     "F12",                      // 0x2b
253     "insert",                   // 0x2c
254     "delete",                   // 0x2d
255     "home",                     // 0x2e
256     "end",                      // 0x2f
257     "page up",                  // 0x30
258     "page down",                // 0x31
259     "print screen",             // 0x32
260     "scroll lock",              // 0x33
261     "pause",                    // 0x34
262     "sys-request",              // 0x35
263     "break",                    // 0x36
264     "reset (HIL)",              // 0x37
265     "stop (HIL)",               // 0x38
266     "menu (HIL)",               // 0x39
267     "user (HIL)",               // 0x3a
268     "system (HIL)",             // 0x3b
269     "print (HIL)",              // 0x3c
270     "clear line (HIL)",         // 0x3d
271     "clear display (HIL)",      // 0x3e
272     "insert line (HIL)",        // 0x3f
273     "delete line (HIL)",        // 0x40
274     "insert char (HIL)",        // 0x41
275     "delete char (HIL)",        // 0x42
276     "prev (HIL)",               // 0x43
277     "next (HIL)",               // 0x44
278     "select (HIL)",             // 0x45
279     };
280 #define N_FUNCTION_KEY (sizeof(FUNCTION_KEY) / sizeof(FUNCTION_KEY[0]))
281
282
283 //-----------------------------------------------------------------------------
284 // Data Stream Object
285 //      Can be configured to treat embedded "numbers" as being composed of
286 //      either 1, 2, or 4 bytes, apiece.
287 //-----------------------------------------------------------------------------
288 typedef struct _DataStream
289     {
290     byte const* data;
291     byte const* data_end;
292     natural number_size; // Size in bytes of a "number" in the stream.
293     } DataStream;
294
295 static DataStream* new_data_stream( byte const* data, int size )
296     {
297     DataStream* s = (DataStream*)malloc( sizeof(DataStream) );
298     s->data = data;
299     s->data_end = data + size;
300     s->number_size = 1; // Default to byte-sized numbers.
301     return s;
302     }
303
304 static void destroy_data_stream( DataStream* s )
305     {
306     free(s);
307     }
308
309 static int end_of_stream( DataStream* s )
310     {
311     return (s->data >= s->data_end);
312     }
313
314 static void expect_nbytes( DataStream* s, int nbytes )
315     {
316     if (s->data + nbytes > s->data_end)
317         {
318         fputs( "Insufficient data in keymapping data stream.\n", stderr );
319         exit(-1);
320         }
321     }
322
323 static byte get_byte( DataStream* s )
324     {
325     expect_nbytes( s, 1 );
326     return *s->data++;
327     }
328
329 static word get_word( DataStream* s )
330     {
331     word hi, lo;
332     expect_nbytes( s, 2 );
333     hi = *s->data++;
334     lo = *s->data++;
335     return ((hi << 8) | lo);
336     }
337
338 static dword get_dword( DataStream* s )
339     {
340     dword b1, b2, b3, b4;
341     expect_nbytes( s, 4 );
342     b4 = *s->data++;
343     b3 = *s->data++;
344     b2 = *s->data++;
345     b1 = *s->data++;
346     return ((b4 << 24) | (b3 << 16) | (b2 << 8) | b1);
347     }
348
349 static number get_number( DataStream* s )
350     {
351     switch (s->number_size)
352         {
353         case 4:  return get_dword(s);
354         case 2:  return get_word(s);
355         default: return get_byte(s);
356         }
357     }
358
359
360 //-----------------------------------------------------------------------------
361 // Translation Utility Functions
362 //-----------------------------------------------------------------------------
363 static char const* special_code_desc( number n )
364     {
365     if (n < N_SPECIAL_CODE)
366         return SPECIAL_CODE[n];
367     else
368         return "invalid";
369     }
370
371 static char const* modifier_code_desc( number n )
372     {
373     if (n < N_MODIFIER_CODE)
374         return MODIFIER_CODE[n];
375     else
376         return "invalid";
377     }
378
379 static char const* modifier_mask_desc( number n )
380     {
381     if (n < N_MODIFIER_MASK)
382         return MODIFIER_MASK[n];
383     else
384         return "?????";
385     }
386
387 static char const* function_key_desc( number n )
388     {
389     if (n >= FUNCTION_KEY_FIRST && n < N_FUNCTION_KEY + FUNCTION_KEY_FIRST)
390         return FUNCTION_KEY[ n - FUNCTION_KEY_FIRST ];
391     else
392         return "unknown";
393     }
394
395 static number bits_set( number mask )
396     {
397     number n = 0;
398     for ( ; mask != 0; mask >>= 1)
399         if ((mask & 0x01) != 0)
400             n++;
401     return n;
402     }
403
404
405 //-----------------------------------------------------------------------------
406 // Unparse a list of Modifier records.
407 //-----------------------------------------------------------------------------
408 static void unparse_modifiers( DataStream* s )
409     {
410     number nmod = get_number(s); // Modifier count
411     printf( "MODIFIERS [%lu]\n", nmod );
412     while (nmod-- > 0)
413         {
414         number nscan;
415         number const code = get_number(s);
416         printf( "%s:", modifier_code_desc(code) );
417         nscan = get_number(s);
418         while (nscan-- > 0)
419             printf( " 0x%02x", (natural)get_number(s) );
420         putchar( '\n' );
421         }
422     putchar( '\n' );
423     }
424
425
426 //-----------------------------------------------------------------------------
427 // Unparse a list of Character records.
428 //-----------------------------------------------------------------------------
429 typedef void (*UnparseSpecialFunc)( number code );
430
431 static void unparse_char_codes(
432     DataStream* s, number ncodes, UnparseSpecialFunc unparse_special )
433     {
434     if (ncodes != 0)
435         {
436         while (ncodes-- > 0)
437             {
438             number const char_set = get_number(s);
439             number const code = get_number(s);
440             putchar(' ');
441             switch (char_set)
442                 {
443                 case ASCII_SET:
444                     {
445                     int const c = (int)code;
446                     if (isprint(c))
447                         printf( "\"%c\"", c );
448                     else if (code < ' ')
449                         printf( "\"^%c\"", c + '@' );
450                     else
451                         printf( "%02x", c );
452                     break;
453                     }
454                 case BIND_FUNCTION:
455                     printf( "[%s]", function_key_desc(code) );
456                     break;
457                 case BIND_SPECIAL:
458                     unparse_special( code );
459                     break;
460                 default:
461                     printf( "%02x/%02x", (natural)char_set, (natural)code );
462                     break;
463                 }
464             }
465         }
466     }
467
468
469 //-----------------------------------------------------------------------------
470 // Unparse a list of scan code bindings.
471 //-----------------------------------------------------------------------------
472 static void unparse_key_special( number code )
473     {
474     printf( "{seq#%lu}", code );
475     }
476
477 static void unparse_characters( DataStream* s )
478     {
479     number const NOT_BOUND = 0xff;
480     number const nscans = get_number(s);
481     number scan;
482     printf( "CHARACTERS [%lu]\n", nscans );
483     for (scan = 0; scan < nscans; scan++)
484         {
485         number const mask = get_number(s);
486         printf( "scan 0x%02x: ", (natural)scan );
487         if (mask == NOT_BOUND)
488             fputs( "not-bound\n", stdout );
489         else
490             {
491             number const bits = bits_set( mask );
492             number const codes = 1 << bits;
493             printf( "%s ", modifier_mask_desc(mask) );
494             unparse_char_codes( s, codes, unparse_key_special );
495             putchar( '\n' );
496             }
497         }
498     putchar( '\n' );
499     }
500
501
502 //-----------------------------------------------------------------------------
503 // Unparse a list of key sequences.
504 //-----------------------------------------------------------------------------
505 static void unparse_sequence_special( number code )
506     {
507     printf( "{%s}", (code == 0 ? "unmodify" : modifier_code_desc(code)) );
508     }
509
510 static void unparse_sequences( DataStream* s )
511     {
512     number const nseqs = get_number(s);
513     number seq;
514     printf( "SEQUENCES [%lu]\n", nseqs );
515     for (seq = 0; seq < nseqs; seq++)
516         {
517         number const nchars = get_number(s);
518         printf( "sequence %lu:", seq );
519         unparse_char_codes( s, nchars, unparse_sequence_special );
520         putchar( '\n' );
521         }
522     putchar( '\n' );
523     }
524
525
526 //-----------------------------------------------------------------------------
527 // Unparse a list of special keys.
528 //-----------------------------------------------------------------------------
529 static void unparse_specials( DataStream* s )
530     {
531     number nspecials = get_number(s);
532     printf( "SPECIALS [%lu]\n", nspecials );
533     while (nspecials-- > 0)
534         {
535         number const special = get_number(s);
536         number const scan = get_number(s);
537         printf( "%s: 0x%02x\n", special_code_desc(special), (natural)scan );
538         }
539     putchar( '\n' );
540     }
541
542
543 //-----------------------------------------------------------------------------
544 // Unparse the number-size flag.
545 //-----------------------------------------------------------------------------
546 static void unparse_numeric_size( DataStream* s )
547     {
548     word const numbers_are_shorts = get_word(s);
549     s->number_size = numbers_are_shorts ? 2 : 1;
550     }
551
552
553 //-----------------------------------------------------------------------------
554 // Unparse an entire key map.
555 //-----------------------------------------------------------------------------
556 static void unparse_keymap_data( DataStream* s )
557     {
558     unparse_numeric_size(s);
559     unparse_modifiers(s);
560     unparse_characters(s);
561     unparse_sequences(s);
562     unparse_specials(s);
563     }
564
565
566 //-----------------------------------------------------------------------------
567 // Unparse the active key map.
568 //-----------------------------------------------------------------------------
569 #if !defined(DUMPKEYMAP_FILE_ONLY)
570 static int unparse_active_keymap( void )
571     {
572     int rc = 1;
573     NXEventHandle const h = NXOpenEventStatus();
574     if (h == 0)
575         fputs( "Unable to open event status driver.\n", stderr );
576     else
577         {
578         NXKeyMapping km;
579         km.size = NXKeyMappingLength(h);
580         if (km.size <= 0)
581             fprintf( stderr, "Bad key mapping length (%d).\n", km.size );
582         else
583             {
584             km.mapping = (char*)malloc( km.size );
585             if (NXGetKeyMapping( h, &km ) == 0)
586                 fputs( "Unable to get current key mapping.\n", stderr );
587             else
588                 {
589                 DataStream* stream =
590                     new_data_stream( (byte const*)km.mapping, km.size );
591                 fputs( "=============\nACTIVE KEYMAP\n=============\n\n",
592                     stdout);
593                 unparse_keymap_data( stream );
594                 destroy_data_stream( stream );
595                 rc = 0;
596                 }
597             free( km.mapping );
598             }
599         NXCloseEventStatus(h);
600         }
601     return rc;
602     }
603 #endif
604
605
606 //-----------------------------------------------------------------------------
607 // Unparse one key map from a keymapping file.
608 //-----------------------------------------------------------------------------
609 static void unparse_keymap( DataStream* s )
610     {
611     dword const interface = get_dword(s);
612     dword const handler_id = get_dword(s);
613     dword const map_size = get_dword(s);
614     printf( "interface: 0x%02lx\nhandler_id: 0x%02lx\nmap_size: %lu bytes\n\n",
615         interface, handler_id, map_size );
616     unparse_keymap_data(s);
617     }
618
619
620 //-----------------------------------------------------------------------------
621 // Check the magic number of a keymapping file.
622 //-----------------------------------------------------------------------------
623 static int check_magic_number( DataStream* s )
624     {
625     return (get_byte(s) == 'K' &&
626             get_byte(s) == 'Y' &&
627             get_byte(s) == 'M' &&
628             get_byte(s) == '1');
629     }
630
631
632 //-----------------------------------------------------------------------------
633 // Unparse all key maps within a keymapping file.
634 //-----------------------------------------------------------------------------
635 static int unparse_keymaps( DataStream* s )
636     {
637     int rc = 0;
638     if (check_magic_number(s))
639         {
640         int n = 1;
641         while (!end_of_stream(s))
642             {
643             printf( "---------\nKEYMAP #%d\n---------\n", n++ );
644             unparse_keymap(s);
645             }
646         }
647     else
648         {
649         fputs( "Bad magic number.\n", stderr );
650         rc = 1;
651         }
652     return rc;
653     }
654
655
656 //-----------------------------------------------------------------------------
657 // Unparse a keymapping file.
658 //-----------------------------------------------------------------------------
659 static int unparse_keymap_file( char const* const path )
660     {
661     int rc = 1;
662     FILE* file;
663     printf( "===========\nKEYMAP FILE\n===========\n%s\n\n", path );
664     file = fopen( path, "rb" );
665     if (file == 0)
666         perror( "Unable to open key mapping file" );
667     else
668         {
669         struct stat st;
670         if (fstat( fileno(file), &st ) != 0)
671             perror( "Unable to determine key mapping file size" );
672         else
673             {
674             byte* buffer = (byte*)malloc( st.st_size );
675             if (fread( buffer, st.st_size, 1, file ) != 1)
676                 perror( "Unable to read key mapping file" );
677             else
678                 {
679                 DataStream* stream = new_data_stream(buffer, (int)st.st_size);
680                 fclose( file ); file = 0;
681                 rc = unparse_keymaps( stream );
682                 destroy_data_stream( stream );
683                 }
684             free( buffer );
685             }
686         if (file != 0)
687             fclose( file );
688         }
689     return rc;
690     }
691
692
693 //-----------------------------------------------------------------------------
694 // Handle the case when no documents are mentioned on the command-line.  For
695 // Apple/NeXT platforms, dump the currently active key mapping; else display
696 // an error message.
697 //-----------------------------------------------------------------------------
698 static int handle_empty_document_list( void )
699     {
700 #if !defined(DUMPKEYMAP_FILE_ONLY)
701     return unparse_active_keymap();
702 #else
703     fputs( "ERROR: Must specify at least one .keymapping file.\n\n", stderr );
704     return 1;
705 #endif
706     }
707
708
709 //-----------------------------------------------------------------------------
710 // Print a detailed description of the internal layout of a key mapping.
711 //-----------------------------------------------------------------------------
712 static void print_internal_layout_info( FILE* f )
713     {
714     fputs(
715 "What follows is a detailed descriptions of the internal layout of an\n"
716 "Apple/NeXT .keymapping file.\n"
717 "\n"
718 "Types and Data\n"
719 "--------------\n"
720 "The following type definitions are employed throughout this discussion:\n"
721 "\n"
722 "    typedef unsigned char  byte;\n"
723 "    typedef unsigned short word;\n"
724 "    typedef unsigned long  dword;\n"
725 "\n"
726 "Additionally, the type definition `number' is used generically to indicate\n"
727 "a numeric value.  The actual size of the `number' type may be one or two\n"
728 "bytes depending upon how the data is stored in the key map.  Although most\n"
729 "key maps use byte-sized numeric values, word-sized values are also allowed.\n"
730 "\n"
731 "Multi-byte values in a key mapping file are stored in big-endian byte\n"
732 "order.\n"
733 "\n"
734 "Key Mapping File and Device Mapping\n"
735 "-----------------------------------\n"
736 "A key mapping file begins with a magic-number and continues with a variable\n"
737 "number of device-specific key mappings.\n"
738 "\n"
739 "    struct KeyMappingFile {\n"
740 "        char magic_number[4];    // `KYM1'\n"
741 "        DeviceMapping maps[...]; // Variable number of maps\n"
742 "    };\n"
743 "\n"
744 "    struct DeviceMapping {\n"
745 "        dword interface;  // Interface type\n"
746 "        dword handler_id; // Interface subtype\n"
747 "        dword map_size;   // Byte count of `map' (below)\n"
748 "        KeyMapping map;\n"
749 "    };\n"
750 "\n"
751 "The value of `interface' represents a family of keyboard device types\n"
752 "(such as Intel PC, ADB, NeXT, Sun Type5, etc.), and is generally\n"
753 "specified as one of the constant values NX_EVS_DEVICE_INTERFACE_ADB,\n"
754 "NX_EVS_DEVICE_INTERFACE_ACE, etc., which are are defined in IOHIDTypes.h on\n"
755 "MacOS/X and Darwin, and in ev_types.h on MacOS/X Server, OpenStep, and\n"
756 "NextStep.\n"
757 "\n"
758 "The value of `handler_id' represents a specific keyboard layout within the\n"
759 "much broader `interface' family.  For instance, for a 101-key Intel PC\n"
760 "keyboard (of type NX_EVS_DEVICE_INTERFACE_ACE) the `handler_id' is '0',\n"
761 "whereas for a 102-key keyboard it is `1'.\n"
762 "\n"
763 "Together, `interface' and `handler_id' identify the exact keyboard hardware\n"
764 "to which this mapping applies.  Programs which display a visual\n"
765 "representation of a keyboard layout, match `interface' and `handler_id'\n"
766 "from the .keymapping file against the `interface' and `handler_id' values\n"
767 "found in each .keyboard file.\n"
768 "\n"
769 "Key Mapping\n"
770 "-----------\n"
771 "A key mapping completely defines the relationship of all scan codes with\n"
772 "their associated functionality.  A KeyMapping structure is embedded within\n"
773 "the DeviceMapping structure in a KeyMappingFile.  The key mapping currently\n"
774 "in use by the WindowServer and AppKit is also represented by a KeyMapping\n"
775 "structure, and can be referred to directly by calling NXGetKeyMapping() and\n"
776 "accessing the `mapping' data member of the returned NXKeyMapping structure.\n"
777 "\n"
778 "    struct KeyMapping {\n"
779 "        word number_size;                   // 0=1 byte, non-zero=2 bytes\n"
780 "        number num_modifier_groups;         // Modifier groups\n"
781 "        ModifierGroup modifier_groups[...];\n"
782 "        number num_scan_codes;              // Scan groups\n"
783 "        ScanGroup scan_table[...];\n"
784 "        number num_sequence_lists;          // Sequence lists\n"
785 "        Sequence sequence_lists[...];\n"
786 "        number num_special_keys;            // Special keys\n"
787 "        SpecialKey special_key[...];\n"
788 "    };\n"
789 "\n"
790 "The `number_size' flag determines the size, in bytes, of all remaining\n"
791 "numeric values (denoted by the type definition `number') within the key\n"
792 "mapping.  If its value is zero, then numbers are represented by a single\n"
793 "byte.  If it is non-zero, then numbers are represented by a word (two\n"
794 "bytes).\n"
795 "\n"
796 "Modifier Group\n"
797 "--------------\n"
798 "A modifier group defines all scan codes which map to a particular type of\n"
799 "modifier, such as `shift', `control', etc.\n"
800 "\n"
801 "    enum Modifier {\n"
802 "        ALPHALOCK = 0,\n"
803 "        SHIFT,\n"
804 "        CONTROL,\n"
805 "        ALTERNATE,\n"
806 "        COMMAND,\n"
807 "        KEYPAD,\n"
808 "        HELP\n"
809 "    };\n"
810 "\n"
811 "    struct ModifierGroup {\n"
812 "        number modifier;        // A Modifier constant\n"
813 "        number num_scan_codes;\n"
814 "        number scan_codes[...]; // Variable number of scan codes\n"
815 "    };\n"
816 "\n"
817 "The scan_codes[] array contains a list of all scan codes which map to the\n"
818 "specified modifier.  The `shift', `command', and `alternate' modifiers are\n"
819 "frequently mapped to two different scan codes, apiece, since these\n"
820 "modifiers often appear on both the left and right sides of the keyboard.\n"
821 "\n"
822 "Scan Group\n"
823 "----------\n"
824 "There is one ScanGroup for each scan code generated by the given keyboard.\n"
825 "This number is given by KeyMapping::num_scan_codes.  The first scan group\n"
826 "represents hardware scan code 0, the second represents scan code 1, etc.\n"
827 "\n"
828 "    enum ModifierMask {\n"
829 "        ALPHALOCK_MASK       = 1 << 0,\n"
830 "        SHIFT_MASK           = 1 << 1,\n"
831 "        CONTROL_MASK         = 1 << 2,\n"
832 "        ALTERNATE_MASK       = 1 << 3,\n"
833 "        CARRIAGE_RETURN_MASK = 1 << 4\n"
834 "    };\n"
835 "    #define NOT_BOUND 0xff\n"
836 "\n"
837 "    struct ScanGroup {\n"
838 "        number mask;\n"
839 "        Character characters[...];\n"
840 "    };\n"
841 "\n"
842 "For each scan code, `mask' defines which modifier combinations generate\n"
843 "characters.  If `mask' is NOT_BOUND (0xff) then then this scan code does\n"
844 "not generate any characters ever, and its characters[] array is zero\n"
845 "length.  Otherwise, the characters[] array contains one Character record\n"
846 "for each modifier combination.\n"
847 "\n"
848 "The number of records in characters[] is determined by computing (1 <<\n"
849 "bits_set_in_mask).  In other words, if mask is zero, then zero bits are\n"
850 "set, so characters[] contains only one record.  If `mask' is (SHIFT_MASK |\n"
851 "CONTROL_MASK), then two bits are set, so characters[] contains four\n"
852 "records.\n"
853 "\n"
854 "The first record always represents the character which is generated by that\n"
855 "key when no modifiers are active.  The remaining records represent\n"
856 "characters generated by the various modifier combinations.  Using the\n"
857 "example with the `shift' and `control' masks set, record two would\n"
858 "represent the character with the `shift' modifier active; record three, the\n"
859 "`control' modifier active; and record four, both the `shift' and `control'\n"
860 "modifiers active.\n"
861 "\n"
862 "As a special case, ALPHALOCK_MASK implies SHIFT_MASK, though only\n"
863 "ALPHALOCK_MASK appears in `mask'.  In this case the same character is\n"
864 "generated for both the `shift' and `alpha-lock' modifiers, but only needs\n"
865 "to appear once in the characters[] array.\n"
866 "\n"
867 "CARRIAGE_RETURN_MASK does not actually refer to a modifier key.  Instead,\n"
868 "it is used to distinguish the scan code which is given the special\n"
869 "pseudo-designation of `carriage return' key.  Typically, this mask appears\n"
870 "solo in a ScanGroup record and only the two Character records for control-M\n"
871 "and control-C follow.  This flag may be a throwback to an earlier time or\n"
872 "may be specially interpreted by the low-level keyboard driver, but its\n"
873 "purpose is otherwise enigmatic.\n"
874 "Character\n"
875 "---------\n"
876 "Each Character record indicates the character generated when this key is\n"
877 "pressed, as well as the character set which contains the character.  Well\n"
878 "known character sets are `ASCII' and `Symbol'.  The character set can also\n"
879 "be one of the meta values FUNCTION_KEY or KEY_SEQUENCE.  If it is\n"
880 "FUNCTION_KEY then `char_code' represents a generally well-known function\n"
881 "key such as those enumerated by FunctionKey.  If the character set is\n"
882 "KEY_SEQUENCE then `char_code' represents a zero-base index into\n"
883 "KeyMapping::sequence_lists[].\n"
884 "\n"
885 "    enum CharacterSet {\n"
886 "        ASCII        = 0x00,\n"
887 "        SYMBOL       = 0x01,\n"
888 "        ...\n"
889 "        FUNCTION_KEY = 0xfe,\n"
890 "        KEY_SEQUENCE = 0xff\n"
891 "    };\n"
892 "\n"
893 "    struct Character {\n"
894 "        number set;       // CharacterSet of generated character\n"
895 "        number char_code; // Actual character generated\n"
896 "    };\n"
897 "\n"
898 "    enum FunctionKey {\n"
899 "        F1 = 0x20, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12,\n"
900 "        INSERT, DELETE, HOME, END, PAGE_UP, PAGE_DOWN, PRINT_SCREEN,\n"
901 "        SCROLL_LOCK, PAUSE, SYS_REQUEST, BREAK, RESET, STOP, MENU, USER,\n"
902 "        SYSTEM, PRINT, CLEAR_LINE, CLEAR_DISPLAY, INSERT_LINE,\n"
903 "        DELETE_LINE, INSERT_CHAR, DELETE_CHAR, PREV, NEXT, SELECT\n"
904 "    };\n"
905 "\n"
906 "Sequence\n"
907 "--------\n"
908 "When Character::set contains the meta value KEY_SEQUENCE, the scan code is\n"
909 "bound to a sequence of keys rather than a single character.  A sequence is\n"
910 "a series of modifiers and characters which are automatically generated when\n"
911 "the associated key is depressed.\n"
912 "\n"
913 "    #define MODIFIER_KEY 0xff\n"
914 "\n"
915 "    struct Sequence {\n"
916 "        number num_chars;\n"
917 "        Character characters[...];\n"
918 "    };\n"
919 "\n"
920 "Each generated Character is represented as previously described, with the\n"
921 "exception that MODIFIER_KEY may appear in place of KEY_SEQUENCE.  When the\n"
922 "value of Character::set is MODIFIER_KEY then Character::char_code\n"
923 "represents a modifier key rather than an actual character.  If the modifier\n"
924 "represented by `char_code' is non-zero, then it indicates that the\n"
925 "associated modifier key has been depressed.  In this case, the value is one\n"
926 "of the constants enumerated by Modifier (SHIFT, CONTROL, ALTERNATE, etc.).\n"
927 "If the value is zero then it means that the modifier keys have been\n"
928 "released.\n"
929 "\n"
930 "Special Key\n"
931 "-----------\n"
932 "A special key is one which is scanned directly by the Mach kernel rather\n"
933 "than by the WindowServer.  In general, events are not generated for special\n"
934 "keys.\n"
935 "\n"
936 "    enum SpecialKeyType {\n"
937 "        VOLUME_UP = 0,\n"
938 "        VOLUME_DOWN,\n"
939 "        BRIGHTNESS_UP,\n"
940 "        BRIGHTNESS_DOWN,\n"
941 "        ALPHA_LOCK,\n"
942 "        HELP,\n"
943 "        POWER,\n"
944 "        SECONDARY_ARROW_UP,\n"
945 "        SECONDARY_ARROW_DOWN\n"
946 "    };\n"
947 "\n"
948 "    struct SpecialKey {\n"
949 "        number type;      // A SpecialKeyType constant\n"
950 "        number scan_code; // Actual scan code\n"
951 "    };\n"
952 "\n", f );
953     }
954
955
956 //-----------------------------------------------------------------------------
957 // Print an explanation of the output generated by this program.
958 //-----------------------------------------------------------------------------
959 static void print_output_info( FILE* f )
960     {
961     fputs(
962 "What follows is an explanation and description of the various pieces of\n"
963 "information emitted by dumpkeymap.\n"
964 "\n"
965 "For a more thorough discussion of any particular piece of information\n"
966 "described here, refer to the detailed description of the internal layout of\n"
967 "a key mapping given by the --help-layout option.\n"
968 "\n"
969 "Conventions\n"
970 "-----------\n"
971 "Depending upon context, some numeric values are displayed in decimal\n"
972 "notation, whereas others are displayed in hexadecimal notation.\n"
973 "Hexadecimal numbers are denoted by a `0x' prefix (for instance, `0x7b'),\n"
974 "except when explicitly noted otherwise.\n"
975 "\n"
976 "Key Mapping Source\n"
977 "------------------\n"
978 "The first piece of information presented about a particular key mapping is\n"
979 "the source from which the data was gleaned.  For a .keymapping file, the\n"
980 "title `KEYMAP FILE' is emitted along with the path and name of the file in\n"
981 "question.  For the key mapping currently in use by the WindowServer and\n"
982 "AppKit, the title `ACTIVE KEYMAP' is emitted instead.\n"
983 "\n"
984 "Device Information\n"
985 "------------------\n"
986 "Each .keymapping file may contain one or more raw key mappings.  For\n"
987 "example, a file which maps keys to a Dvorak-style layout might contain raw\n"
988 "mappings for Intel PC, ADB, NeXT, and Sun Type5 keyboards.\n"
989 "\n"
990 "For each raw mapping, the following information is emitted:\n"
991 "\n"
992 "    o The title `KEYMAP' along with the mapping's relative position in the\n"
993 "      .keymapping file.\n"
994 "    o The `interface' identifier.\n"
995 "    o The `handler_id' sub-identifier.\n"
996 "    o The size of the raw mapping resource counted in bytes.\n"
997 "\n"
998 "The `interface' and `handler_id' values, taken together, define a specific\n"
999 "keyboard device.  A .keyboard file, which describes the visual layout of a\n"
1000 "keyboard, also contains `interface' and `handler_id' identifiers.  The\n"
1001 ".keyboard file corresponding to a particular key mapping can be found by\n"
1002 "matching the `interface' and `handler_id' values from each resource.\n"
1003 "\n"
1004 "Modifiers\n"
1005 "---------\n"
1006 "Each mapping may contain zero or more modifier records which associate\n"
1007 "hardware scan codes with modifier descriptions such as `shift', `control',\n"
1008 "`alternate', etc.  The title `MODIFIERS' is printed along with the count of\n"
1009 "modifier records which follow.  For each modifier record, the modifier's\n"
1010 "name is printed along with a list of scan codes, in hexadecimal format,\n"
1011 "which generate that modifier value.  For example:\n"
1012 "\n"
1013 "    MODIFIERS [4]\n"
1014 "    alternate: 0x1d 0x60\n"
1015 "    control: 0x3a\n"
1016 "    keypad: 0x52 0x53 ... 0x63 0x62\n"
1017 "    shift: 0x2a 0x36\n"
1018 "\n"
1019 "Characters\n"
1020 "----------\n"
1021 "Each mapping may contain zero or more character records which associate\n"
1022 "hardware scan codes with the actual characters generated by those scan\n"
1023 "codes in the presence or absence of various modifier combinations.  The\n"
1024 "title `CHARACTERS' is printed along with the count of character records\n"
1025 "which follow.  Here is a highly abbreviated example:\n"
1026 "\n"
1027 "    CHARACTERS [9]\n"
1028 "    scan 0x00: -AC-L  \"a\" \"A\" \"^A\" \"^A\" ca c7 \"^A\" \"^A\"\n"
1029 "    scan 0x07: -AC-L  \"x\" \"X\" \"^X\" \"^X\" 01/b4 01/ce \"^X\" \"^X\"\n"
1030 "    scan 0x0a: ---S-  \"<\" \">\"\n"
1031 "    scan 0x13: -ACS-  \"2\" \"@\" \"^@\" \"^@\" b2 b3 \"^@\" \"^@\"\n"
1032 "    scan 0x24: R----  \"^M\" \"^C\"\n"
1033 "    scan 0x3e: -----  [F4]\n"
1034 "    scan 0x4a: -----  [page up]\n"
1035 "    scan 0x60: -----  {seq#3}\n"
1036 "    scan 0x68: not-bound\n"
1037 "\n"
1038 "For each record, the hexadecimal value of the hardware scan code is\n"
1039 "printed, followed by a list of modifier flag combinations and the actual\n"
1040 "characters generated by this scan code with and without modifiers applied.\n"
1041 "\n"
1042 "The modifier flags field is composed of a combination of single letter\n"
1043 "representations of the various modifier types.  The letters stand for:\n"
1044 "\n"
1045 "    L - alpha-lock\n"
1046 "    S - shift\n"
1047 "    C - control\n"
1048 "    A - alternate\n"
1049 "    R - carriage-return\n"
1050 "\n"
1051 "As a special case, the `alpha-lock' flag also implies the `shift' flag, so\n"
1052 "these two flags never appear together in the same record.\n"
1053 "\n"
1054 "The combination of modifier flags determines the meaning and number of\n"
1055 "fields which follow.  The first field after the modifier flags always\n"
1056 "represents the character that will be generated if no modifier keys are\n"
1057 "depressed.  The remaining fields represent characters generated by the\n"
1058 "various modifier combinations.  The order of the fields follows this\n"
1059 "general pattern:\n"
1060 "\n"
1061 "    o The character generated by this scan code when no modifiers are in\n"
1062 "      effect is listed first.\n"
1063 "\n"
1064 "    o If the `L' or `S' flag is active, then the shifted character\n"
1065 "      generated by this scan code is listed next.\n"
1066 "\n"
1067 "    o If the `C' flag is active, then the control-character generated by\n"
1068 "      this scan code is listed next.  Furthermore, if the `L' or `S' flag\n"
1069 "      is also active, then the shifted control-character is listed after\n"
1070 "      that.\n"
1071 "\n"
1072 "    o If the `A' flag is active, then the alternate-character generated by\n"
1073 "      this scan code is listed next.  Furthermore, if the `L' or `S' flag\n"
1074 "      is active, then the shifted alternate-character is listed after that.\n"
1075 "      If the `C' flag is also active, then the alternate-control-character\n"
1076 "      is listed next.  Finally, if the `C' and `L' or `C' and `S' flags are\n"
1077 "      also active, then the shifted alternate-control-character is listed.\n"
1078 "\n"
1079 "The `R' flag does not actually refer to a modifier key.  Instead, it is\n"
1080 "used to distinguish the scan code which is given the special\n"
1081 "pseudo-designation of `carriage return' key.  Typically, this mask appears\n"
1082 "solo and only the two fields for control-M and control-C follow.  This flag\n"
1083 "may be a throwback to an earlier time or may be specially interpreted by\n"
1084 "the low-level keyboard driver, but its purpose is otherwise enigmatic.\n"
1085 "\n"
1086 "Recalling the example from above, the following fields can be identified:\n"
1087 "\n"
1088 "    scan 0x00: -AC-L  \"a\" \"A\" \"^A\" \"^A\" ca c7 \"^A\" \"^A\"\n"
1089 "\n"
1090 "    o Lower-case `a' is generated when no modifiers are active.\n"
1091 "    o Upper-case `A' is generated when `shift' or `alpha-lock' are active.\n"
1092 "    o Control-A is generated when `control' is active.\n"
1093 "    o Control-A is generated when `control' and `shift' are active.\n"
1094 "    o The character represented by the hexadecimal code 0xca is generated\n"
1095 "      when `alternate' is active.\n"
1096 "    o The character represented by 0xc7 is generated when `alternate' and\n"
1097 "      `shift' (or `alpha-lock') are active.\n"
1098 "    o Control-A is generated when `alternate' and `control' are active.\n"
1099 "    o Control-A is generated when `alternate', `control' and `shift' (or\n"
1100 "      `alpha-lock') are active.\n"
1101 "\n"
1102 "The notation used to represent a particular generated character varies.\n"
1103 "\n"
1104 "    o Printable ASCII characters are quoted, as in \"x\" or \"X\".\n"
1105 "\n"
1106 "    o Control-characters are quoted and prefixed with `^', as in \"^X\".\n"
1107 "\n"
1108 "    o Characters with values greater than 127 (0x7f) are displayed as\n"
1109 "      hexadecimal values without the `0x' prefix.\n"
1110 "\n"
1111 "    o Characters in a non-ASCII character set (such as `Symbol') are\n"
1112 "      displayed as two hexadecimal numbers separated by a slash, as in\n"
1113 "      `01/4a'.  The first number is the character set's identification code\n"
1114 "      (such as `01' for the `Symbol' set), and the second number is the\n"
1115 "      value of the generated character.\n"
1116 "\n"
1117 "    o Non-printing special function characters are displayed with the\n"
1118 "      function's common name enclosed in brackets, as in `[page up]' or\n"
1119 "      `[F4]'.\n"
1120 "\n"
1121 "    o If the binding represents a key sequence rather than a single\n"
1122 "      character, then the sequence's identification number is enclosed in\n"
1123 "      braces, as in `{seq#3}'.\n"
1124 "\n"
1125 "Recalling a few examples from above, the following interpretations can be\n"
1126 "made:\n"
1127 "\n"
1128 "    scan 0x07: -AC-L  \"x\" \"X\" \"^X\" \"^X\" 01/b4 01/ce \"^X\" \"^X\"\n"
1129 "    scan 0x3e: -----  [F4]\n"
1130 "    scan 0x4a: -----  [page up]\n"
1131 "    scan 0x60: -----  {seq#3}\n"
1132 "\n"
1133 "    o \"x\" and \"X\" are printable ASCII characters.\n"
1134 "    o \"^X\" is a control-character.\n"
1135 "    o `01/b4' and `01/ce' represent the character codes 0xb4 and 0xce in\n"
1136 "      the `Symbol' character set.\n"
1137 "    o Scan code 0x3e generates function-key `F4', and scan code 0x4a\n"
1138 "      generates function-key `page up'.\n"
1139 "    o Scan code 0x60 is bound to key sequence #3.\n"
1140 "\n"
1141 "Finally, if a scan code is not bound to any characters, then it is\n"
1142 "annotated with the label `not-bound', as with example scan code 0x68 from\n"
1143 "above.\n"
1144 "\n"
1145 "Sequences\n"
1146 "---------\n"
1147 "A scan code (modified and unmodified) can be bound to a key sequence rather\n"
1148 "than generating a single character or acting as a modifier.  When it is\n"
1149 "bound to a key sequence, a series of character invocations and modifier\n"
1150 "actions are automatically generated rather than a single keystroke.\n"
1151 "\n"
1152 "Each mapping may contain zero or more key sequence records.  The title\n"
1153 "`SEQUENCES' is printed along with the count of sequence records which\n"
1154 "follow.  For example:\n"
1155 "\n"
1156 "    SEQUENCES [3]\n"
1157 "    sequence 0: \"f\" \"o\" \"o\"\n"
1158 "    sequence 1: {alternate} \"b\" \"a\" \"r\" {unmodify}\n"
1159 "    sequence 2: [home] \"b\" \"a\" \"z\"\n"
1160 "\n"
1161 "The notation used to represent the sequence of generated characters is\n"
1162 "identical to the notation already described in the `Characters' section\n"
1163 "above, with the exception that modifier actions may be interposed between\n"
1164 "generated characters.  Such modifier actions are represented by the\n"
1165 "modifier's name enclosed in braces.  The special name `{unmodify}'\n"
1166 "indicates the release of the modifier keys.\n"
1167 "\n"
1168 "Thus, the sequences in the above example can be interpreted as follows:\n"
1169 "\n"
1170 "    o Sequence #0 generates `foo'.\n"
1171 "    o Sequence #1 invokes the `alternate' modifier, generates `bar', and\n"
1172 "      then releases `alternate'.\n"
1173 "    o Sequence #2 invokes the `home' key and then generates `baz'.  In a\n"
1174 "      text editor, this would probably result in `baz' being prepended to\n"
1175 "      the line of text on which the cursor resides.\n"
1176 "\n"
1177 "Special Keys\n"
1178 "------------\n"
1179 "Certain keyboards feature keys which perform some type of special purpose\n"
1180 "function rather than generating a character or acting as a modifier.  For\n"
1181 "instance, Apple keyboards often contain a `power' key, and NeXT keyboards\n"
1182 "have historically featured screen brightness and volume control keys.\n"
1183 "\n"
1184 "Each mapping may contain zero or more special-key records which associate\n"
1185 "hardware scan codes with such special purpose functions.  The title\n"
1186 "`SPECIALS' is printed along with the count of records which follow.  For\n"
1187 "each record, the special function's name is printed along with a list of\n"
1188 "scan codes, in hexadecimal format, which are bound to that function.  For\n"
1189 "example:\n"
1190 "\n"
1191 "    SPECIALS [6]\n"
1192 "    alpha-lock: 0x39\n"
1193 "    brightness-down: 0x79\n"
1194 "    brightness-up: 0x74\n"
1195 "    power: 0x7f\n"
1196 "    sound-down: 0x77\n"
1197 "    sound-up: 0x73\n"
1198 "\n", f );
1199     }
1200
1201
1202 //-----------------------------------------------------------------------------
1203 // Print a summary of the various files and directories which are related to
1204 // key mappings.
1205 //-----------------------------------------------------------------------------
1206 static void print_files_info( FILE* f )
1207     {
1208     fputs(
1209 "This is a summary of the various files and directories which are related to\n"
1210 "key mappings.\n"
1211 "\n"
1212 "*.keymapping\n"
1213 "    A key mapping file which precisely defines the relationship of all\n"
1214 "    hardware-specific keyboard scan-codes with their associated\n"
1215 "    functionality.\n"
1216 "\n"
1217 "*.keyboard\n"
1218 "    A file describing the physical layout of keys on a particular type of\n"
1219 "    keyboard.  Each `key' token in this file defines the position and shape\n"
1220 "    of the key on the keyboard, as well as the associated scan code which\n"
1221 "    that key generates.  A .keymapping file, on the other hand, defines the\n"
1222 "    characters which are generated by a particular scan code depending upon\n"
1223 "    the state of the various modifier keys (such as shift, control, etc.).\n"
1224 "    The `interface' and `handler_id' values from a .keymapping file are\n"
1225 "    matched against those in each .keyboard file in order to associate a\n"
1226 "    particular .keyboard file with a key mapping.  Various GUI programs use\n"
1227 "    the .keyboard file to display a visual representation of a keyboard for\n"
1228 "    the user.  Since these files are just plain text, they can be easily\n"
1229 "    viewed and interpreted without the aid of a specialized program, thus\n"
1230 "    dumpkeymap leaves these files alone.\n"
1231 "\n"
1232 "/System/Library/Keyboards\n"
1233 "/Network/Library/Keyboards\n"
1234 "/Local/Library/Keyboards\n"
1235 "/Library/Keyboards\n"
1236 "    Repositories for .keymapping and .keyboard files for MacOS/X, Darwin,\n"
1237 "    and MacOS/X Server.\n"
1238 "\n"
1239 "/NextLibrary/Keyboards\n"
1240 "/LocalLibrary/Keyboards\n"
1241 "    Repositories for .keymapping and .keyboard files for OpenStep and\n"
1242 "    NextStep.\n"
1243 "\n"
1244 "$(HOME)/Library/Keyboards\n"
1245 "    Repository for personal .keymapping and .keyboard files.\n"
1246 "\n", f );
1247     }
1248
1249
1250 //-----------------------------------------------------------------------------
1251 // Print a list of the various diagnostic messages which may be emitted.
1252 //-----------------------------------------------------------------------------
1253 static void print_diagnostics_info( FILE* f )
1254     {
1255     fputs(
1256 "The following diagnostic messages may be issued to the standard error\n"
1257 "stream.\n"
1258 "\n"
1259 "Unrecognized option.\n"
1260 "    An unrecognized option was specified on the command-line.  Invoke\n"
1261 "    dumpkeymap with the --help option to view a list of valid options.\n"
1262 "\n"
1263 "Insufficient data in keymapping data stream.\n"
1264 "    The key mapping file or data stream is corrupt.  Either the file has\n"
1265 "    been incorrectly truncated or a field, such as those which indicates\n"
1266 "    the number of variable records which follow, contains a corrupt value.\n"
1267 "\n"
1268 "The following diagnostic messages have significance only when trying to\n"
1269 "print .keymapping files mentioned on the command-line.\n"
1270 "\n"
1271 "Bad magic number.\n"
1272 "    The mentioned file is not a .keymapping file.  The file's content does\n"
1273 "    not start with the string `KYM1'.\n"
1274 "\n"
1275 "Unable to open key mapping file.\n"
1276 "    The call to fopen() failed; probably because the specified path is\n"
1277 "    invalid or dumpkeymap does not have permission to read the file.\n"
1278 "\n"
1279 "Unable to determine key mapping file size.\n"
1280 "    The call to fstat() failed, thus memory can not be allocated for\n"
1281 "    loading the file.\n"
1282 "\n"
1283 "Unable to read key mapping file.\n"
1284 "    The call to fread() failed.\n"
1285 "\n"
1286 "The following diagnostic messages have significance only when trying to\n"
1287 "print the currently active key mapping when no .keymapping files have been\n"
1288 "mentioned on the command-line.\n"
1289 "\n"
1290 "Unable to open event status driver.\n"
1291 "    The call to NXOpenEventStatus() failed.\n"
1292 "\n"
1293 "Bad key mapping length.\n"
1294 "    The call to NXKeyMappingLength() returned a bogus value.\n"
1295 "\n"
1296 "Unable to get current key mapping.\n"
1297 "    The call to NXGetKeyMapping() failed.\n"
1298 "\n"
1299 "The following diagnostic messages have significance only when using\n"
1300 "dumpkeymap on a non-Apple/NeXT platform.\n"
1301 "\n"
1302 "Must specify at least one .keymapping file.\n"
1303 "    No .keymapping files were mentioned on the command-line.  On\n"
1304 "    non-Apple/NeXT platforms, there is no concept of a currently active\n"
1305 "    .keymapping file, so at least one file must be mentioned on the\n"
1306 "    command-line.\n"
1307 "\n", f );
1308     }
1309
1310
1311 //-----------------------------------------------------------------------------
1312 // Print warranty.
1313 //-----------------------------------------------------------------------------
1314 static void print_warranty( FILE* f )
1315     {
1316     fputs(
1317 "This software is provided by the author `AS IS' and any express or implied\n"
1318 "WARRANTIES, including, but not limited to, the implied warranties of\n"
1319 "MERCHANTABILITY and FITNESS FOR A PARTICULAR PURPOSE are DISCLAIMED.  In NO\n"
1320 "EVENT shall the author be LIABLE for any DIRECT, INDIRECT, INCIDENTAL,\n"
1321 "SPECIAL, EXEMPLARY, or CONSEQUENTIAL damages (including, but not limited\n"
1322 "to, procurement of substitute goods or services; loss of use, data, or\n"
1323 "profits; or business interruption) however caused and on any theory of\n"
1324 "liability, whether in contract, strict liability, or tort (including\n"
1325 "negligence or otherwise) arising in any way out of the use of this\n"
1326 "software, even if advised of the possibility of such damage.\n"
1327 "\n", f );
1328     }
1329
1330
1331 //-----------------------------------------------------------------------------
1332 // Print this program's version number.
1333 //-----------------------------------------------------------------------------
1334 static void print_version( FILE* f )
1335     {
1336     fputs( "Version " PROG_VERSION " (built " __DATE__ ")\n\n", f );
1337     }
1338
1339
1340 //-----------------------------------------------------------------------------
1341 // Print a usage summary.
1342 //-----------------------------------------------------------------------------
1343 static void print_usage( FILE* f )
1344     {
1345     fputs(
1346 "Usage: dumpkeymap [options] [-] [file ...]\n"
1347 "\n"
1348 "Prints a textual representation of each Apple/NeXT .keymapping file\n"
1349 "mentioned on the command-line.  If no files are mentioned and if the local\n"
1350 "machine is an Apple or NeXT installation, then the key mapping currently in\n"
1351 "use by the WindowServer and the AppKit is printed instead.\n"
1352 "\n"
1353 "Options:\n"
1354 "    -h --help\n"
1355 "        Display general program instructions and option summary.\n"
1356 "\n"
1357 "    -k --help-keymapping\n"
1358 "        Display a detailed description of the internal layout of a\n"
1359 "        .keymapping file.\n"
1360 "\n"
1361 "    -o --help-output\n"
1362 "        Display an explanation of the output generated by dumpkeymap when\n"
1363 "        dissecting a .keymapping file.\n"
1364 "\n"
1365 "    -f --help-files\n"
1366 "        Display a summary of the various files and directories which are\n"
1367 "        related to key mappings.\n"
1368 "\n"
1369 "    -d --help-diagnostics\n"
1370 "        Display a list of the various diagnostic messages which may be\n"
1371 "        emitted by dumpkeymap.\n"
1372 "\n"
1373 "    -v --version\n"
1374 "        Display the dumpkeymap version number and warranty information.\n"
1375 "\n"
1376 "    - --\n"
1377 "        Inhibit processing of options at this point in the argument list.\n"
1378 "        An occurrence of `-' or `--' in the argument list causes all\n"
1379 "        following arguments to be treated as file names even if an argument\n"
1380 "        begins with a `-' character.\n"
1381 "\n", f );
1382     }
1383
1384
1385 //-----------------------------------------------------------------------------
1386 // Print an informational banner.
1387 //-----------------------------------------------------------------------------
1388 static void print_banner( FILE* f )
1389     {
1390     fputs( "\n" PROG_NAME " v" PROG_VERSION " by " AUTHOR_INFO "\n"
1391         COPYRIGHT "\n\n", f );
1392     }
1393
1394
1395 //-----------------------------------------------------------------------------
1396 // Process command-line arguments.  Examine options first; collecting files
1397 // along the way.  If all is well, process collected file list.
1398 //-----------------------------------------------------------------------------
1399 int main( int const argc, char const* const argv[] )
1400     {
1401     int rc = 0, i, nfiles = 0, more_options = 1, process_files = 1;
1402     int* files = (int*)calloc( argc - 1, sizeof(int) );
1403     print_banner( stdout );
1404
1405     for (i = 1; i < argc; i++)
1406         {
1407         char const* const s = argv[i];
1408         if (!more_options || *s != '-')
1409             files[ nfiles++ ] = i;
1410         else
1411             {
1412             OPT_SWITCH(s)
1413                 OPT_CASE(-,--)
1414                     more_options = 0;
1415                 OPT_CASE(-h,--help)
1416                     print_usage( stdout );
1417                     process_files = 0;
1418                 OPT_CASE(-k,--help-keymapping)
1419                     print_internal_layout_info( stdout );
1420                     process_files = 0;
1421                 OPT_CASE(-o,--help-output)
1422                     print_output_info( stdout );
1423                     process_files = 0;
1424                 OPT_CASE(-f,--help-files)
1425                     print_files_info( stdout );
1426                     process_files = 0;
1427                 OPT_CASE(-d,--help-diagnostics)
1428                     print_diagnostics_info( stdout );
1429                     process_files = 0;
1430                 OPT_CASE(-v,--version)
1431                     print_version( stdout );
1432                     print_warranty( stdout );
1433                     process_files = 0;
1434                 OPT_DEFAULT
1435                     fprintf( stderr, "ERROR: Unrecognized option: %s\n\n", s );
1436                     process_files = 0;
1437                     rc = 1;
1438             OPT_SWITCH_END
1439             }
1440         }
1441
1442     if (process_files)
1443         {
1444         if (nfiles == 0)
1445             rc = handle_empty_document_list();
1446         else
1447             for (i = 0; i < nfiles; i++)
1448                 rc |= unparse_keymap_file( argv[files[i]] );
1449         }
1450
1451     free( files );
1452     return rc;
1453     }