]> git.sesse.net Git - vlc/blob - src/interface/intf_cmd.c
Encore un commit venu tout droit des abysses de l'enfer, d�sol� pour
[vlc] / src / interface / intf_cmd.c
1 /*****************************************************************************
2  * intf_cmd.c: interface commands parsing and executions functions
3  * This file implements the interface commands execution functions. It is used
4  * by command-line oriented interfaces and scripts. The commands themselves are
5  * implemented in intf_ctrl.
6  *****************************************************************************
7  * Copyright (C) 1998, 1999, 2000 VideoLAN
8  *
9  * Authors:
10  *
11  * This program is free software; you can redistribute it and/or modify
12  * it under the terms of the GNU General Public License as published by
13  * the Free Software Foundation; either version 2 of the License, or
14  * (at your option) any later version.
15  *
16  * This program is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
19  * General Public License for more details.
20  *
21  * You should have received a copy of the GNU General Public
22  * License along with this program; if not, write to the
23  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
24  * Boston, MA 02111-1307, USA.
25  *****************************************************************************/
26
27 /*****************************************************************************
28  * Preamble
29  *****************************************************************************/
30 #include <errno.h>                                                  /* errno */
31 #include <stdio.h>                                                   /* FILE */
32 #include <stdlib.h>                                    /* strtod(), strtol() */
33 #include <string.h>                                            /* strerror() */
34
35 #include "config.h"
36 #include "common.h"
37 #include "mtime.h"
38 #include "threads.h"
39
40 #include "interface.h"
41 #include "intf_msg.h"
42 #include "intf_cmd.h"
43 #include "intf_ctrl.h"
44 #include "main.h"
45
46 /*
47  * Local prototypes
48  */
49 static int  ParseCommandArguments   ( char *psz_argv[INTF_MAX_ARGS], char *psz_cmd );
50 static int  CheckCommandArguments   ( intf_arg_t argv[INTF_MAX_ARGS], int i_argc,
51                                       char *psz_argv[INTF_MAX_ARGS], char *psz_format );
52 static void ParseFormatString       ( intf_arg_t format[INTF_MAX_ARGS], char *psz_format );
53 static int  ConvertArgument         ( intf_arg_t *p_arg, int i_flags, char *psz_str );
54
55 /*****************************************************************************
56  * intf_ExecCommand: parse and execute a command
57  *****************************************************************************
58  * This function is called when a command needs to be executed. It parse the
59  * command line, build an argument array, find the command in control commands
60  * array and run the command. It returns the return value of the command, or
61  * EINVAL if no command could be executed. Command line is modified by this
62  * function.
63  * Note that this function may terminate abruptly the program or signify it's
64  * end to the interface thread.
65  *****************************************************************************/
66 int intf_ExecCommand( char *psz_cmd )
67 {
68     char *          psz_argv[INTF_MAX_ARGS];           /* arguments pointers */
69     intf_arg_t      argv[INTF_MAX_ARGS];              /* converted arguments */
70     int             i_argc;                           /* number of arguments */
71     int             i_index;                         /* multi-purposes index */
72     int             i_return;                        /* command return value */
73
74     intf_DbgMsg("command `%s'\n", psz_cmd);
75
76     /* Parse command line (separate arguments). If nothing has been found,
77      * the function returns without error */
78     i_argc = ParseCommandArguments( psz_argv, psz_cmd );
79     if( !i_argc )
80     {
81         return( 0 );
82     }
83
84     /* Find command. Command is always the first token on the line */
85     for( i_index = 0;
86          control_command[i_index].psz_name && strcmp( psz_argv[0], control_command[i_index].psz_name );
87          i_index++ )
88     {
89         ;
90     }
91     if( !control_command[i_index].psz_name )              /* unknown command */
92     {
93         /* Print error message */
94         intf_IntfMsg( "error: unknown command `%s'. Try `help'", psz_argv[0] );
95         return( INTF_USAGE_ERROR );
96     }
97
98     /* Check arguments validity */
99     if( CheckCommandArguments( argv, i_argc, psz_argv, control_command[i_index].psz_format ) )
100     {
101         /* The given arguments does not match the format string. An error message has
102          * already been displayed, so only the usage string is printed */
103         intf_IntfMsg( "usage: %s", control_command[i_index].psz_usage );
104         return( INTF_USAGE_ERROR );
105     }
106
107     /* Execute command */
108     i_return = control_command[i_index].function( i_argc, argv );
109
110     /* Manage special error codes */
111     switch( i_return )
112     {
113     case INTF_FATAL_ERROR:                                    /* fatal error */
114         /* Print message and terminates the interface thread */
115         intf_ErrMsg( "fatal error in command `%s'\n", psz_argv[0] );
116         p_main->p_intf->b_die = 1;
117         break;
118
119     case INTF_CRITICAL_ERROR:                              /* critical error */
120         /* Print message, flush messages queue and exit. Note that this
121          * error should be very rare since it does not even try to cancel other
122          * threads... */
123         intf_ErrMsg("critical error in command `%s'. Please report this error !\n", psz_argv[0] );
124         intf_FlushMsg();
125         exit( INTF_CRITICAL_ERROR );
126         break;
127
128     case INTF_USAGE_ERROR:                                    /* usage error */
129         /* Print error message and usage */
130         intf_IntfMsg( "usage: %s", control_command[i_index].psz_usage );
131         break;
132     }
133
134     /* Return error code */
135     return( i_return );
136 }
137
138 /*****************************************************************************
139  * intf_ExecScript: parse and execute a command script
140  *****************************************************************************
141  * This function, based on ExecCommand read a file and tries to execute each
142  * of its line as a command. It returns 0 if everything succeeded, a negative
143  * number if the script could not be executed and a positive one if an error
144  * occured during execution.
145  *****************************************************************************/
146 int intf_ExecScript( char *psz_filename )
147 {
148     FILE *  p_file;                                                  /* file */
149     char    psz_line[INTF_MAX_CMD_SIZE];                             /* line */
150     char *  psz_index;                                    /* index in string */
151     int     i_err;                                        /* error indicator */
152
153     /* Open file */
154     i_err = 0;
155     p_file = fopen( psz_filename, "r" );
156     if( p_file == NULL )
157     {
158         intf_ErrMsg("warning: %s: %s\n", psz_filename, strerror(errno));
159         return( -1 );
160     }
161
162     /* For each line: read and execute */
163     while( fgets( psz_line, INTF_MAX_CMD_SIZE, p_file ) != NULL )
164     {
165         /* If line begins with a '#', it is a comment and shoule be ignored,
166          * else, execute it */
167         if( psz_line[0] != '#' )
168         {
169             /* The final '\n' needs to be removed before execution */
170             for( psz_index = psz_line; *psz_index && (*psz_index != '\n'); psz_index++ )
171             {
172                 ;
173             }
174             if( *psz_index == '\n' )
175             {
176                 *psz_index = '\0';
177             }
178
179             /* Execute command */
180             i_err |= intf_ExecCommand( psz_line );
181         }
182     }
183     if( !feof( p_file ) )
184     {
185         intf_ErrMsg("error: %s: %s\n", psz_filename, strerror(errno));
186         return( -1 );
187     }
188
189     /* Close file */
190     fclose( p_file );
191     return( i_err != 0 );
192 }
193
194 /* following functions are local */
195
196 /*****************************************************************************
197  * ParseCommandArguments: isolate arguments in a command line
198  *****************************************************************************
199  * This function modify the original command line, adding '\0' and completes
200  * an array of pointers to beginning of arguments. It return the number of
201  * arguments.
202  *****************************************************************************/
203 static int ParseCommandArguments( char *psz_argv[INTF_MAX_ARGS], char *psz_cmd )
204 {
205     int         i_argc;                               /* number of arguments */
206     char *      psz_index;                                          /* index */
207     boolean_t   b_block;                       /* block (argument) indicator */
208
209     /* Initialize parser state */
210     b_block = 0;   /* we start outside a block to remove spaces at beginning */
211     i_argc = 0;
212
213     /* Go through command until end has been reached or maximal number of
214      * arguments has been reached */
215     for( psz_index = psz_cmd; *psz_index && (i_argc < INTF_MAX_ARGS); psz_index++ )
216     {
217         /* Inside a block, end of blocks are marked by spaces */
218         if( b_block )
219         {
220             if( *psz_index == ' ' )
221             {
222                 *psz_index = '\0';               /* mark the end of argument */
223                 b_block = 0;                               /* exit the block */
224             }
225
226         }
227         /* Outside a block, beginning of blocks are marked by any character
228          * different from space */
229         else
230         {
231             if( *psz_index != ' ' )
232             {
233                 psz_argv[i_argc++] = psz_index;            /* store argument */
234                 b_block = 1;                              /* enter the block */
235             }
236         }
237     }
238
239     /* Return number of arguments found */
240     return( i_argc );
241 }
242
243 /*****************************************************************************
244  * CheckCommandArguments: check arguments agains format
245  *****************************************************************************
246  * This function parse each argument and tries to find a match in the format
247  * string. It fills the argv array.
248  * If all arguments have been sucessfuly identified and converted, it returns
249  * 0, else, an error message is issued and non 0 is returned.
250  * Note that no memory is allocated by this function, but that the arguments
251  * can be modified.
252  *****************************************************************************/
253 static int CheckCommandArguments( intf_arg_t argv[INTF_MAX_ARGS], int i_argc,
254                                   char *psz_argv[INTF_MAX_ARGS], char *psz_format )
255 {
256     intf_arg_t  format[INTF_MAX_ARGS];           /* parsed format indicators */
257     int         i_arg;                                     /* argument index */
258     int         i_format;                                    /* format index */
259     char *      psz_index;                                   /* string index */
260     char *      psz_cmp_index;                   /* string comparaison index */
261     int         i_index;                                    /* generic index */
262     boolean_t   b_found;                            /* `argument found' flag */
263
264
265     /* Build format array */
266     ParseFormatString( format, psz_format );
267
268     /* Initialize parser: i_format must be the first non named formatter */
269     for( i_format = 0; ( i_format < INTF_MAX_ARGS )
270              && (format[i_format].i_flags & INTF_NAMED_ARG);
271          i_format++ )
272     {
273         ;
274     }
275
276     /* Scan all arguments */
277     for( i_arg = 1; i_arg < i_argc; i_arg++ )
278     {
279         b_found = 0;
280
281         /* Test if argument can be taken as a named argument: try to find a
282          * '=' in the string */
283         for( psz_index = psz_argv[i_arg]; *psz_index && ( *psz_index != '=' ); psz_index++ )
284         {
285             ;
286         }
287         if( *psz_index == '=' )                                 /* '=' found */
288         {
289             /* Browse all named arguments to check if there is one matching */
290             for( i_index = 0; (i_index < INTF_MAX_ARGS)
291                      && ( format[i_index].i_flags & INTF_NAMED_ARG )
292                      && !b_found;
293                  i_index++ )
294             {
295                 /* Current format string is named... compare start of two
296                  * names. A local inline ntation of a strcmp is used since
297                  * string isn't ended by '\0' but by '=' */
298                 for( psz_index = psz_argv[i_arg], psz_cmp_index = format[i_index].ps_name;
299                      (*psz_index == *psz_cmp_index) && (*psz_index != '=') && (*psz_cmp_index != '=');
300                      psz_index++, psz_cmp_index++ )
301                 {
302                     ;
303                 }
304                 if( *psz_index == *psz_cmp_index )        /* the names match */
305                 {
306                     /* The argument is a named argument which name match the
307                      * named argument i_index. To be valid, the argument should
308                      * not have been already encountered and the type must
309                      * match. Before going further, the '=' is replaced by
310                      * a '\0'. */
311                     *psz_index = '\0';
312
313                     /* Check unicity. If the argument has already been encountered,
314                      * print an error message and return. */
315                     if( format[i_index].i_flags & INTF_PRESENT_ARG )/* present */
316                     {
317                         intf_IntfMsg("error: `%s' has already been encountered", psz_argv[i_arg] );
318                         return( 1 );
319                     }
320
321                      /* Register argument and prepare exit */
322                     b_found = 1;
323                     format[i_index].i_flags |= INTF_PRESENT_ARG;
324                     argv[i_arg].i_flags = INTF_NAMED_ARG;
325                     argv[i_arg].i_index = i_index;
326                     argv[i_arg].ps_name = psz_argv[i_arg];
327
328                     /* Check type and store value */
329                     psz_index++;
330                     if( ConvertArgument( &argv[i_arg], format[i_index].i_flags, psz_index ) )
331                     {
332                         /* An error occured during conversion */
333                         intf_IntfMsg( "error: invalid type for `%s'", psz_index );
334                     }
335                 }
336             }
337         }
338
339         /* If argument is not a named argument, the format string will
340          * be browsed starting from last position until the argument is
341          * found or an error occurs. */
342         if( !b_found )
343         {
344             /* Reset type indicator */
345             argv[i_arg].i_flags = 0;
346
347             /* If argument is not a named argument, the format string will
348              * be browsed starting from last position until the argument is
349              * found, an error occurs or the last format argument is
350              * reached */
351             while( !b_found && (i_format < INTF_MAX_ARGS) && format[i_format].i_flags )
352             {
353                 /* Try to convert argument */
354                 if( !ConvertArgument( &argv[i_arg], format[i_format].i_flags, psz_argv[i_arg] ) )
355                 {
356                     /* Matching format has been found */
357                     b_found = 1;
358                     format[i_format].i_flags |= INTF_PRESENT_ARG;
359                     argv[i_arg].i_index = i_format;
360
361                     /* If argument is repeatable, dot not increase format counter */
362                     if( !(format[i_format].i_flags & INTF_REP_ARG) )
363                     {
364                         i_format++;
365                     }
366                 }
367                 else
368                 {
369                     /* Argument does not match format. This can be an error, or
370                      * just a missing optionnal parameter, or the end of a
371                      * repeated argument */
372                     if( (format[i_format].i_flags & INTF_OPT_ARG)
373                         || (format[i_format].i_flags & INTF_PRESENT_ARG) )
374                     {
375                         /* This is not an error */
376                         i_format++;
377                     }
378                     else
379                     {
380                         /* The present format argument is mandatory and does
381                          * not match the argument */
382                         intf_IntfMsg("error: missing argument before `%s'", psz_argv[i_arg] );
383                         return( 1 );
384                     }
385                 }
386             }
387         }
388
389         /* If argument is not a named argument and hasn't been found in
390          * format string, then it is an usage error and the function can
391          * return */
392         if( !b_found )
393         {
394             intf_IntfMsg("error: `%s' does not match any argument", psz_argv[i_arg] );
395             return( 1 );
396         }
397
398         intf_DbgMsg("argument flags=0x%x (index=%d) name=%s str=%s int=%d float=%f\n",
399                     argv[i_arg].i_flags,
400                     argv[i_arg].i_index,
401                     (argv[i_arg].i_flags & INTF_NAMED_ARG) ? argv[i_arg].ps_name : "NA",
402                     (argv[i_arg].i_flags & INTF_STR_ARG) ? argv[i_arg].psz_str : "NA",
403                     (argv[i_arg].i_flags & INTF_INT_ARG) ? argv[i_arg].i_num : 0,
404                     (argv[i_arg].i_flags & INTF_FLOAT_ARG) ? argv[i_arg].f_num : 0);
405     }
406
407     /* Parse all remaining format specifier to verify they are all optionnal */
408     for( ;  (i_format < INTF_MAX_ARGS) && format[i_format].i_flags ; i_format++ )
409     {
410         if( !(( format[i_format].i_flags & INTF_OPT_ARG)
411               || ( format[i_format].i_flags & INTF_PRESENT_ARG)) )
412         {
413             /* Format has not been used and is neither optionnal nor multiple
414              * and present */
415             intf_IntfMsg("error: missing argument(s)\n");
416             return( 1 );
417         }
418     }
419
420     /* If an error occured, the function already exited, so if this point is
421      * reached, everything is fine */
422     return( 0 );
423 }
424
425 /*****************************************************************************
426  * ConvertArgument: try to convert an argument to a given type
427  *****************************************************************************
428  * This function tries to convert the string argument given in psz_str to
429  * a type specified in i_flags. It updates p_arg and returns O on success,
430  * or 1 on error. No error message is issued.
431  *****************************************************************************/
432 static int ConvertArgument( intf_arg_t *p_arg, int i_flags, char *psz_str )
433 {
434     char *psz_end;                   /* end pointer for conversion functions */
435
436     if( i_flags & INTF_STR_ARG )                                   /* string */
437     {
438         /* A conversion from a string to a string will always succeed... */
439         p_arg->psz_str = psz_str;
440         p_arg->i_flags |= INTF_STR_ARG;
441     }
442     else if( i_flags & INTF_INT_ARG )                             /* integer */
443     {
444         p_arg->i_num = strtol( psz_str, &psz_end, 0 );     /* convert string */
445         /* If the conversion failed, return 1 and do not modify argument
446          * flags. Else, add 'int' flag and continue. */
447         if( !*psz_str || *psz_end )
448         {
449             return( 1 );
450         }
451         p_arg->i_flags |= INTF_INT_ARG;
452     }
453     else if( i_flags & INTF_FLOAT_ARG )                             /* float */
454     {
455         p_arg->f_num = strtod( psz_str, &psz_end );        /* convert string */
456         /* If the conversion failed, return 1 and do not modify argument
457          * flags. Else, add 'float' flag and continue. */
458         if( !*psz_str || *psz_end )
459         {
460             return( 1 );
461         }
462         p_arg->i_flags |= INTF_FLOAT_ARG;
463     }
464 #ifdef DEBUG
465     else                                    /* error: missing type specifier */
466     {
467         intf_ErrMsg("error: missing type specifier for `%s' (0x%x)\n", psz_str, i_flags);
468         return( 1 );
469     }
470 #endif
471
472     return( 0 );
473 }
474
475 /*****************************************************************************
476  * ParseFormatString: parse a format string                              (ok ?)
477  *****************************************************************************
478  * This function read a format string, as specified in the control_command
479  * array, and fill a format array, to allow easier argument identification.
480  * Note that no memory is allocated by this function, but that, in a named
481  * argument, the name field does not end with a '\0' but with an '='.
482  * See command.h for format string specifications.
483  * Note that this function is designed to be efficient, not to check everything
484  * in a format string, which should be entered by a developper and therefore
485  * should be correct (TRUST !).
486  *****************************************************************************/
487 static void ParseFormatString( intf_arg_t format[INTF_MAX_ARGS], char *psz_format )
488 {
489     char *  psz_index;                                /* format string index */
490     char *  psz_start;                              /* argument format start */
491     char *  psz_item;                                          /* item index */
492     int     i_index;                                         /* format index */
493
494     /* Initialize parser */
495     i_index = 0;
496     psz_start = psz_format;
497
498     /* Reset first format indicator */
499     format[ 0 ].i_flags = 0;
500
501     /* Parse format string */
502     for( psz_index = psz_format; *psz_index && (i_index < INTF_MAX_ARGS) ; psz_index++ )
503     {
504         /* A space is always an item terminator */
505         if( *psz_index == ' ' )
506         {
507             /* Parse format item. Items are parsed from end to beginning or to
508              * first '=' */
509             for( psz_item = psz_index - 1;
510                  (psz_item >= psz_start) && !( format[i_index].i_flags & INTF_NAMED_ARG);
511                  psz_item-- )
512             {
513                 switch( *psz_item )
514                 {
515                 case 's':                                          /* string */
516                     format[i_index].i_flags |= INTF_STR_ARG;
517                     break;
518                 case 'i':                                         /* integer */
519                     format[i_index].i_flags |= INTF_INT_ARG;
520                     break;
521                 case 'f':                                           /* float */
522                     format[i_index].i_flags |= INTF_FLOAT_ARG;
523                     break;
524                 case '*':                                 /* can be repeated */
525                     format[i_index].i_flags |= INTF_REP_ARG;
526                     break;
527                 case '?':                              /* optionnal argument */
528                     format[i_index].i_flags |= INTF_OPT_ARG;
529                     break;
530                 case '=':                                   /* name argument */
531                     format[i_index].i_flags |= INTF_NAMED_ARG;
532                     format[i_index].ps_name = psz_start;
533                     break;
534 #ifdef DEBUG
535                 default:/* error which should never happen: incorrect format */
536                     intf_DbgMsg("error: incorrect format string `%s'\n", psz_format);
537                     break;
538 #endif
539                 }
540             }
541
542             /* Mark next item start, increase items counter and reset next
543              * format indicator, if it wasn't the last one. */
544             i_index++;
545             psz_start = psz_index + 1;
546             if( i_index != INTF_MAX_ARGS )       /* end of array not reached */
547             {
548                 format[ i_index ].i_flags = 0;
549             }
550         }
551     }
552 }