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