MagickWand 7.1.1-43
Convert, Edit, Or Compose Bitmap Images
Loading...
Searching...
No Matches
magick-cli.c
1/*
2%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3% %
4% %
5% %
6% M M AAA GGGG IIIII CCCC K K %
7% MM MM A A G I C K K %
8% M M M AAAAA G GGG I C KKK %
9% M M A A G G I C K K %
10% M M A A GGGG IIIII CCCC K K %
11% %
12% CCCC L IIIII %
13% C L I %
14% C L I %
15% C L I %
16% CCCC LLLLL IIIII %
17% %
18% Perform "Magick" on Images via the Command Line Interface %
19% %
20% Dragon Computing %
21% Anthony Thyssen %
22% January 2012 %
23% %
24% %
25% Copyright @ 1999 ImageMagick Studio LLC, a non-profit organization %
26% dedicated to making software imaging solutions freely available. %
27% %
28% You may not use this file except in compliance with the License. You may %
29% obtain a copy of the License at %
30% %
31% https://imagemagick.org/script/license.php %
32% %
33% Unless required by applicable law or agreed to in writing, software %
34% distributed under the License is distributed on an "AS IS" BASIS, %
35% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
36% See the License for the specific language governing permissions and %
37% limitations under the License. %
38% %
39%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
40%
41% Read CLI arguments, script files, and pipelines, to provide options that
42% manipulate images from many different formats.
43%
44*/
45
46/*
47 Include declarations.
48*/
49#include "MagickWand/studio.h"
50#include "MagickWand/MagickWand.h"
51#include "MagickWand/magick-wand-private.h"
52#include "MagickWand/wandcli.h"
53#include "MagickWand/wandcli-private.h"
54#include "MagickWand/operation.h"
55#include "MagickWand/magick-cli.h"
56#include "MagickWand/script-token.h"
57#include "MagickCore/policy-private.h"
58#include "MagickCore/string-private.h"
59#include "MagickCore/thread-private.h"
60#include "MagickCore/utility-private.h"
61#include "MagickCore/exception-private.h"
62#include "MagickCore/version.h"
63
64/* verbose debugging,
65 0 - no debug lines
66 3 - show option details (better to use -debug Command now)
67 5 - image counts (after option runs)
68*/
69#define MagickCommandDebug 0
70
71
72/*
73%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
74% %
75% %
76% %
77% M a g i c k C o m m a n d G e n e s i s %
78% %
79% %
80% %
81%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
82%
83% MagickCommandGenesis() applies image processing options to an image as
84% prescribed by command line options.
85%
86% It wiil look for special options like "-debug", "-bench", and
87% "-distribute-cache" that needs to be applied even before the main
88% processing begins, and may completely overrule normal command processing.
89% Such 'Genesis' Options can only be given on the CLI, (not in a script)
90% and are typically ignored (as they have been handled) if seen later.
91%
92% The format of the MagickCommandGenesis method is:
93%
94% MagickBooleanType MagickCommandGenesis(ImageInfo *image_info,
95% MagickCommand command,int argc,char **argv,char **metadata,
96% ExceptionInfo *exception)
97%
98% A description of each parameter follows:
99%
100% o image_info: the image info.
101%
102% o command: Choose from ConvertImageCommand, IdentifyImageCommand,
103% MogrifyImageCommand, CompositeImageCommand, CompareImagesCommand,
104% ConjureImageCommand, StreamImageCommand, ImportImageCommand,
105% DisplayImageCommand, or AnimateImageCommand.
106%
107% o argc: Specifies a pointer to an integer describing the number of
108% elements in the argument vector.
109%
110% o argv: Specifies a pointer to a text array containing the command line
111% arguments.
112%
113% o metadata: any metadata is returned here.
114%
115% o exception: return any errors or warnings in this structure.
116%
117*/
118WandExport MagickBooleanType MagickCommandGenesis(ImageInfo *image_info,
119 MagickCommand command,int argc,char **argv,char **metadata,
120 ExceptionInfo *exception)
121{
122 char
123 client_name[MagickPathExtent],
124 *option;
125
126 double
127 duration,
128 serial;
129
130 MagickBooleanType
131 concurrent,
132 regard_warnings,
133 status;
134
135 size_t
136 iterations,
137 number_threads;
138
139 ssize_t
140 i,
141 n;
142
143 (void) setlocale(LC_ALL,"");
144 (void) setlocale(LC_NUMERIC,"C");
145 GetPathComponent(argv[0],TailPath,client_name);
146 (void) SetClientName(client_name);
147 concurrent=MagickFalse;
148 duration=(-1.0);
149 iterations=1;
150 status=MagickTrue;
151 regard_warnings=MagickFalse;
152 for (i=1; i < (ssize_t) (argc-1); i++)
153 {
154 option=argv[i];
155 if ((strlen(option) == 1) || ((*option != '-') && (*option != '+')))
156 continue;
157 if (LocaleCompare("-bench",option) == 0)
158 iterations=StringToUnsignedLong(argv[++i]);
159 if (LocaleCompare("-concurrent",option) == 0)
160 concurrent=MagickTrue;
161 if (LocaleCompare("-debug",option) == 0)
162 (void) SetLogEventMask(argv[++i]);
163 if (LocaleCompare("-distribute-cache",option) == 0)
164 {
165 DistributePixelCacheServer(StringToInteger(argv[++i]),exception);
166 exit(0);
167 }
168 if (LocaleCompare("-duration",option) == 0)
169 duration=StringToDouble(argv[++i],(char **) NULL);
170 if (LocaleCompare("-regard-warnings",option) == 0)
171 regard_warnings=MagickTrue;
172 }
173 if (iterations == 1)
174 {
175 char
176 *text;
177
178 text=(char *) NULL;
179 status=command(image_info,argc,argv,&text,exception);
180 if (exception->severity != UndefinedException)
181 {
182 if ((exception->severity > ErrorException) ||
183 (regard_warnings != MagickFalse))
184 status=MagickFalse;
185 CatchException(exception);
186 }
187 if (text != (char *) NULL)
188 {
189 if (metadata != (char **) NULL)
190 (void) ConcatenateString(&(*metadata),text);
191 text=DestroyString(text);
192 }
193 return(status);
194 }
195 number_threads=GetOpenMPMaximumThreads();
196 serial=0.0;
197 for (n=1; n <= (ssize_t) number_threads; n++)
198 {
199 double
200 e,
201 parallel,
202 user_time;
203
204 TimerInfo
205 *timer;
206
207 (void) SetMagickResourceLimit(ThreadResource,(MagickSizeType) n);
208 timer=AcquireTimerInfo();
209 if (concurrent == MagickFalse)
210 {
211 for (i=0; i < (ssize_t) iterations; i++)
212 {
213 char
214 *text;
215
216 text=(char *) NULL;
217 if (status == MagickFalse)
218 continue;
219 if (duration > 0)
220 {
221 if (GetElapsedTime(timer) > duration)
222 continue;
223 (void) ContinueTimer(timer);
224 }
225 status=command(image_info,argc,argv,&text,exception);
226 if (exception->severity != UndefinedException)
227 {
228 if ((exception->severity > ErrorException) ||
229 (regard_warnings != MagickFalse))
230 status=MagickFalse;
231 CatchException(exception);
232 }
233 if (text != (char *) NULL)
234 {
235 if (metadata != (char **) NULL)
236 (void) ConcatenateString(&(*metadata),text);
237 text=DestroyString(text);
238 }
239 }
240 }
241 else
242 {
243 SetOpenMPNested(1);
244#if defined(MAGICKCORE_OPENMP_SUPPORT)
245 # pragma omp parallel for shared(status)
246#endif
247 for (i=0; i < (ssize_t) iterations; i++)
248 {
249 char
250 *text;
251
252 text=(char *) NULL;
253 if (status == MagickFalse)
254 continue;
255 if (duration > 0)
256 {
257 if (GetElapsedTime(timer) > duration)
258 continue;
259 (void) ContinueTimer(timer);
260 }
261 status=command(image_info,argc,argv,&text,exception);
262#if defined(MAGICKCORE_OPENMP_SUPPORT)
263 # pragma omp critical (MagickCore_MagickCommandGenesis)
264#endif
265 {
266 if (exception->severity != UndefinedException)
267 {
268 if ((exception->severity > ErrorException) ||
269 (regard_warnings != MagickFalse))
270 status=MagickFalse;
271 CatchException(exception);
272 }
273 if (text != (char *) NULL)
274 {
275 if (metadata != (char **) NULL)
276 (void) ConcatenateString(&(*metadata),text);
277 text=DestroyString(text);
278 }
279 }
280 }
281 }
282 user_time=GetUserTime(timer);
283 parallel=GetElapsedTime(timer);
284 e=1.0;
285 if (n == 1)
286 serial=parallel;
287 else
288 e=((1.0/(1.0/((serial/(serial+parallel))+(1.0-(serial/(serial+parallel)))/
289 (double) n)))-(1.0/(double) n))/(1.0-1.0/(double) n);
290 (void) FormatLocaleFile(stderr,
291 " Performance[%.20g]: %.20gi %0.3fips %0.6fe %0.6fu %lu:%02lu.%03lu\n",
292 (double) n,(double) iterations,(double) iterations/parallel,e,user_time,
293 (unsigned long) (parallel/60.0),(unsigned long) floor(fmod(parallel,
294 60.0)),(unsigned long) (1000.0*(parallel-floor(parallel))+0.5));
295 timer=DestroyTimerInfo(timer);
296 }
297 return(status);
298}
299
300/*
301%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
302% %
303% %
304% %
305+ P r o c e s s S c r i p t O p t i o n s %
306% %
307% %
308% %
309%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
310%
311% ProcessScriptOptions() reads options and processes options as they are
312% found in the given file, or pipeline. The filename to open and read
313% options is given as the 'index' argument of the argument array given.
314%
315% Other arguments following index may be read by special script options
316% as settings (strings), images, or as operations to be processed in various
317% ways. How they are treated is up to the script being processed.
318%
319% Note that a script not 'return' to the command line processing, nor can
320% they call (and return from) other scripts. At least not at this time.
321%
322% There are no 'ProcessOptionFlags' control flags at this time.
323%
324% The format of the ProcessScriptOptions method is:
325%
326% void ProcessScriptOptions(MagickCLI *cli_wand,const char *filename,
327% int argc,char **argv,int index)
328%
329% A description of each parameter follows:
330%
331% o cli_wand: the main CLI Wand to use.
332%
333% o filename: the filename of script to process
334%
335% o argc: the number of elements in the argument vector. (optional)
336%
337% o argv: A text array containing the command line arguments. (optional)
338%
339% o index: offset of next argument in argv (script arguments) (optional)
340%
341*/
342WandExport void ProcessScriptOptions(MagickCLI *cli_wand,const char *filename,
343 int magick_unused(argc),char **magick_unused(argv),int magick_unused(index))
344{
346 *token_info;
347
348 CommandOptionFlags
349 option_type;
350
351 int
352 count;
353
354 char
355 *option,
356 *arg1,
357 *arg2;
358
359 magick_unreferenced(argc);
360 magick_unreferenced(argv);
361 magick_unreferenced(index);
362 assert(filename != (char *) NULL ); /* at least one argument - script name */
363 assert(cli_wand != (MagickCLI *) NULL);
364 assert(cli_wand->signature == MagickWandSignature);
365 if (cli_wand->wand.debug != MagickFalse)
366 (void) LogMagickEvent(CommandEvent,GetMagickModule(),
367 "Processing script \"%s\"", filename);
368
369 /* open file script or stream, and set up tokenizer */
370 token_info = AcquireScriptTokenInfo(filename);
371 if (token_info == (ScriptTokenInfo *) NULL) {
372 CLIWandExceptionFile(OptionFatalError,"UnableToOpenScript",filename);
373 return;
374 }
375
376 /* define the error location string for use in exceptions
377 order of location format escapes: filename, line, column */
378 cli_wand->location="in \"%s\" at line %u,column %u";
379 if ( LocaleCompare("-", filename) == 0 )
380 cli_wand->filename="stdin";
381 else
382 cli_wand->filename=filename;
383
384 /* Process Options from Script */
385 option = arg1 = arg2 = (char*) NULL;
386DisableMSCWarning(4127)
387 while (1) {
388RestoreMSCWarning
389
390 { MagickBooleanType status = GetScriptToken(token_info);
391 cli_wand->line=token_info->token_line;
392 cli_wand->column=token_info->token_column;
393 if (status == MagickFalse)
394 break; /* error or end of options */
395 }
396
397 do { /* use break to loop to exception handler and loop */
398
399 /* save option details */
400 CloneString(&option,token_info->token);
401
402 /* get option, its argument count, and option type */
403 cli_wand->command = GetCommandOptionInfo(option);
404 count=cli_wand->command->type;
405 option_type=(CommandOptionFlags) cli_wand->command->flags;
406#if 0
407 (void) FormatLocaleFile(stderr, "Script: %u,%u: \"%s\" matched \"%s\"\n",
408 cli_wand->line, cli_wand->line, option, cli_wand->command->mnemonic );
409#endif
410
411 /* handle a undefined option - image read - always for "magick-script" */
412 if ( option_type == UndefinedOptionFlag ||
413 (option_type & NonMagickOptionFlag) != 0 ) {
414#if MagickCommandDebug >= 3
415 (void) FormatLocaleFile(stderr, "Script %u,%u Non-Option: \"%s\"\n",
416 cli_wand->line, cli_wand->line, option);
417#endif
418 if (IsCommandOption(option) == MagickFalse) {
419 /* non-option -- treat as a image read */
420 cli_wand->command=(const OptionInfo *) NULL;
421 CLIOption(cli_wand,"-read",option);
422 break; /* next option */
423 }
424 CLIWandException(OptionFatalError,"UnrecognizedOption",option);
425 break; /* next option */
426 }
427
428 if ( count >= 1 ) {
429 if (GetScriptToken(token_info) == MagickFalse)
430 CLIWandException(OptionFatalError,"MissingArgument",option);
431 CloneString(&arg1,token_info->token);
432 }
433 else
434 CloneString(&arg1,(char *) NULL);
435
436 if ( count >= 2 ) {
437 if (GetScriptToken(token_info) == MagickFalse)
438 CLIWandExceptionBreak(OptionFatalError,"MissingArgument",option);
439 CloneString(&arg2,token_info->token);
440 }
441 else
442 CloneString(&arg2,(char *) NULL);
443
444 /*
445 Process Options
446 */
447#if MagickCommandDebug >= 3
448 (void) FormatLocaleFile(stderr,
449 "Script %u,%u Option: \"%s\" Count: %d Flags: %04x Args: \"%s\" \"%s\"\n",
450 cli_wand->line,cli_wand->line,option,count,option_type,arg1,arg2);
451#endif
452 /* Hard Deprecated Options, no code to execute - error */
453 if ( (option_type & DeprecateOptionFlag) != 0 ) {
454 CLIWandException(OptionError,"DeprecatedOptionNoCode",option);
455 break; /* next option */
456 }
457
458 /* MagickCommandGenesis() options have no place in a magick script */
459 if ( (option_type & GenesisOptionFlag) != 0 ) {
460 CLIWandException(OptionError,"InvalidUseOfOption",option);
461 break; /* next option */
462 }
463
464 /* handle any special 'script' options */
465 if ( (option_type & SpecialOptionFlag) != 0 ) {
466 if ( LocaleCompare(option,"-exit") == 0 ) {
467 goto loop_exit; /* break out of loop - return from script */
468 }
469 if ( LocaleCompare(option,"-script") == 0 ) {
470 /* FUTURE: call new script from this script - error for now */
471 CLIWandException(OptionError,"InvalidUseOfOption",option);
472 break; /* next option */
473 }
474 /* FUTURE: handle special script-argument options here */
475 /* handle any other special operators now */
476 CLIWandException(OptionError,"InvalidUseOfOption",option);
477 break; /* next option */
478 }
479
480 /* Process non-specific Option */
481 CLIOption(cli_wand, option, arg1, arg2);
482 (void) fflush(stdout);
483 (void) fflush(stderr);
484
485DisableMSCWarning(4127)
486 } while (0); /* break block to next option */
487RestoreMSCWarning
488
489#if MagickCommandDebug >= 5
490 fprintf(stderr, "Script Image Count = %ld\n",
491 GetImageListLength(cli_wand->wand.images) );
492#endif
493 if (CLICatchException(cli_wand, MagickFalse) != MagickFalse)
494 break; /* exit loop */
495 }
496
497 /*
498 Loop exit - check for some tokenization error
499 */
500loop_exit:
501#if MagickCommandDebug >= 3
502 (void) FormatLocaleFile(stderr, "Script End: %d\n", token_info->status);
503#endif
504 switch( token_info->status ) {
505 case TokenStatusOK:
506 case TokenStatusEOF:
507 if (cli_wand->image_list_stack != (CLIStack *) NULL)
508 CLIWandException(OptionError,"UnbalancedParenthesis", "(eof)");
509 else if (cli_wand->image_info_stack != (CLIStack *) NULL)
510 CLIWandException(OptionError,"UnbalancedBraces", "(eof)");
511 break;
512 case TokenStatusBadQuotes:
513 /* Ensure last token has a sane length for error report */
514 if( strlen(token_info->token) > INITAL_TOKEN_LENGTH-1 ) {
515 token_info->token[INITAL_TOKEN_LENGTH-4] = '.';
516 token_info->token[INITAL_TOKEN_LENGTH-3] = '.';
517 token_info->token[INITAL_TOKEN_LENGTH-2] = '.';
518 token_info->token[INITAL_TOKEN_LENGTH-1] = '\0';
519 }
520 CLIWandException(OptionFatalError,"ScriptUnbalancedQuotes",
521 token_info->token);
522 break;
523 case TokenStatusMemoryFailed:
524 CLIWandException(OptionFatalError,"ScriptTokenMemoryFailed","");
525 break;
526 case TokenStatusBinary:
527 CLIWandException(OptionFatalError,"ScriptIsBinary","");
528 break;
529 }
530 (void) fflush(stdout);
531 (void) fflush(stderr);
532 if (cli_wand->wand.debug != MagickFalse)
533 (void) LogMagickEvent(CommandEvent,GetMagickModule(),
534 "Script End \"%s\"", filename);
535
536 /* Clean up */
537 token_info = DestroyScriptTokenInfo(token_info);
538
539 CloneString(&option,(char *) NULL);
540 CloneString(&arg1,(char *) NULL);
541 CloneString(&arg2,(char *) NULL);
542
543 return;
544}
545
546/*
547%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
548% %
549% %
550% %
551+ P r o c e s s C o m m a n d O p t i o n s %
552% %
553% %
554% %
555%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
556%
557% ProcessCommandOptions() reads and processes arguments in the given
558% command line argument array. The 'index' defines where in the array we
559% should begin processing
560%
561% The 'process_flags' can be used to control and limit option processing.
562% For example, to only process one option, or how unknown and special options
563% are to be handled, and if the last argument in array is to be regarded as a
564% final image write argument (filename or special coder).
565%
566% The format of the ProcessCommandOptions method is:
567%
568% int ProcessCommandOptions(MagickCLI *cli_wand,int argc,char **argv,
569% int index)
570%
571% A description of each parameter follows:
572%
573% o cli_wand: the main CLI Wand to use.
574%
575% o argc: the number of elements in the argument vector.
576%
577% o argv: A text array containing the command line arguments.
578%
579% o process_flags: What type of arguments will be processed, ignored
580% or return errors.
581%
582% o index: index in the argv array to start processing from
583%
584% The function returns the index ot the next option to be processed. This
585% is really only relevant if process_flags contains a ProcessOneOptionOnly
586% flag.
587%
588*/
589WandExport int ProcessCommandOptions(MagickCLI *cli_wand,int argc,char **argv,
590 int index)
591{
592 const char
593 *option,
594 *arg1,
595 *arg2;
596
597 int
598 i,
599 end,
600 count;
601
602 CommandOptionFlags
603 option_type;
604
605 assert(argc>=index); /* you may have no arguments left! */
606 assert(argv != (char **) NULL);
607 assert(argv[index] != (char *) NULL);
608 assert(argv[argc-1] != (char *) NULL);
609 assert(cli_wand != (MagickCLI *) NULL);
610 assert(cli_wand->signature == MagickWandSignature);
611
612 /* define the error location string for use in exceptions
613 order of location format escapes: filename, line, column */
614 cli_wand->location="at %s arg %u";
615 cli_wand->filename="CLI";
616 cli_wand->line=(size_t) index; /* note first argument we will process */
617
618 if (cli_wand->wand.debug != MagickFalse)
619 (void) CLILogEvent(cli_wand,CommandEvent,GetMagickModule(),
620 "- Starting (\"%s\")", argv[index]);
621
622 end = argc;
623 if ( (cli_wand->process_flags & ProcessImplicitWrite) != 0 )
624 end--; /* the last argument is an implied write, do not process directly */
625
626 for (i=index; i < end; i += count +1) {
627 /* Finished processing one option? */
628 if ( (cli_wand->process_flags & ProcessOneOptionOnly) != 0 && i != index )
629 return(i);
630
631 do { /* use break to loop to exception handler and loop */
632
633 option=argv[i];
634 cli_wand->line=(size_t) i; /* note the argument for this option */
635
636 /* get option, its argument count, and option type */
637 cli_wand->command = GetCommandOptionInfo(argv[i]);
638 count=cli_wand->command->type;
639 option_type=(CommandOptionFlags) cli_wand->command->flags;
640#if 0
641 (void) FormatLocaleFile(stderr, "CLI %d: \"%s\" matched \"%s\"\n",
642 i, argv[i], cli_wand->command->mnemonic );
643#endif
644
645 if ( option_type == UndefinedOptionFlag ||
646 (option_type & NonMagickOptionFlag) != 0 ) {
647#if MagickCommandDebug >= 3
648 (void) FormatLocaleFile(stderr, "CLI arg %d Non-Option: \"%s\"\n",
649 i, option);
650#endif
651 if (IsCommandOption(option) == MagickFalse) {
652 if ( (cli_wand->process_flags & ProcessImplicitRead) != 0 ) {
653 /* non-option -- treat as a image read */
654 cli_wand->command=(const OptionInfo *) NULL;
655 CLIOption(cli_wand,"-read",option);
656 break; /* next option */
657 }
658 }
659 CLIWandException(OptionFatalError,"UnrecognizedOption",option);
660 break; /* next option */
661 }
662
663 if ( ((option_type & SpecialOptionFlag) != 0 ) &&
664 ((cli_wand->process_flags & ProcessScriptOption) != 0) &&
665 (LocaleCompare(option,"-script") == 0) ) {
666 /* Call Script from CLI, with a filename as a zeroth argument.
667 NOTE: -script may need to use the 'implicit write filename' argument
668 so it must be handled specially to prevent a 'missing argument' error.
669 */
670 if ( (i+count) >= argc )
671 CLIWandException(OptionFatalError,"MissingArgument",option);
672 ProcessScriptOptions(cli_wand,argv[i+1],argc,argv,i+count);
673 return(argc); /* Script does not return to CLI -- Yet */
674 /* FUTURE: when it does, their may be no write arg! */
675 }
676
677 if ((i+count) >= end ) {
678 CLIWandException(OptionFatalError,"MissingArgument",option);
679 if ( CLICatchException(cli_wand, MagickFalse) != MagickFalse )
680 return(end);
681 break; /* next option - not that their is any! */
682 }
683
684 arg1 = ( count >= 1 ) ? argv[i+1] : (char *) NULL;
685 arg2 = ( count >= 2 ) ? argv[i+2] : (char *) NULL;
686
687 /*
688 Process Known Options
689 */
690#if MagickCommandDebug >= 3
691 (void) FormatLocaleFile(stderr,
692 "CLI arg %u Option: \"%s\" Count: %d Flags: %04x Args: \"%s\" \"%s\"\n",
693 i,option,count,option_type,arg1,arg2);
694#endif
695 /* ignore 'genesis options' in command line args */
696 if ( (option_type & GenesisOptionFlag) != 0 )
697 break; /* next option */
698
699 /* Handle any special options for CLI (-script handled above) */
700 if ( (option_type & SpecialOptionFlag) != 0 ) {
701 if ( (cli_wand->process_flags & ProcessExitOption) != 0
702 && LocaleCompare(option,"-exit") == 0 )
703 return(i+count);
704 break; /* next option */
705 }
706
707 /* Process standard image option */
708 CLIOption(cli_wand, option, arg1, arg2);
709
710DisableMSCWarning(4127)
711 } while (0); /* break block to next option */
712RestoreMSCWarning
713
714#if MagickCommandDebug >= 5
715 (void) FormatLocaleFile(stderr, "CLI-post Image Count = %ld\n",
716 (long) GetImageListLength(cli_wand->wand.images) );
717#endif
718 if ( CLICatchException(cli_wand, MagickFalse) != MagickFalse )
719 return(i+count);
720 }
721 assert(i==end);
722
723 if ( (cli_wand->process_flags & ProcessImplicitWrite) == 0 )
724 return(end); /* no implied write -- just return to caller */
725
726 assert(end==argc-1); /* end should not include last argument */
727
728 /*
729 Implicit Write of images to final CLI argument
730 */
731 option=argv[i];
732 cli_wand->line=(size_t) i;
733
734 /* check that stacks are empty - or cause exception */
735 if (cli_wand->image_list_stack != (CLIStack *) NULL)
736 CLIWandException(OptionError,"UnbalancedParenthesis", "(end of cli)");
737 else if (cli_wand->image_info_stack != (CLIStack *) NULL)
738 CLIWandException(OptionError,"UnbalancedBraces", "(end of cli)");
739 if ( CLICatchException(cli_wand, MagickFalse) != MagickFalse )
740 return(argc);
741
742#if MagickCommandDebug >= 3
743 (void) FormatLocaleFile(stderr,"CLI arg %d Write File: \"%s\"\n",i,option);
744#endif
745
746 /* Valid 'do no write' replacement option (instead of "null:") */
747 if (LocaleCompare(option,"-exit") == 0 )
748 return(argc); /* just exit, no image write */
749
750 /* If filename looks like an option,
751 Or the common 'end of line' error of a single space.
752 -- produce an error */
753 if (IsCommandOption(option) != MagickFalse ||
754 (option[0] == ' ' && option[1] == '\0') ) {
755 CLIWandException(OptionError,"MissingOutputFilename",option);
756 return(argc);
757 }
758
759 cli_wand->command=(const OptionInfo *) NULL;
760 CLIOption(cli_wand,"-write",option);
761 return(argc);
762}
763
764/*
765%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
766% %
767% %
768% %
769+ M a g i c k I m a g e C o m m a n d %
770% %
771% %
772% %
773%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
774%
775% MagickImageCommand() Handle special use CLI arguments and prepare a
776% CLI MagickCLI to process the command line or directly specified script.
777%
778% This is essentially interface function between the MagickCore library
779% initialization function MagickCommandGenesis(), and the option MagickCLI
780% processing functions ProcessCommandOptions() or ProcessScriptOptions()
781%
782% The format of the MagickImageCommand method is:
783%
784% MagickBooleanType MagickImageCommand(ImageInfo *image_info,int argc,
785% char **argv,char **metadata,ExceptionInfo *exception)
786%
787% A description of each parameter follows:
788%
789% o image_info: the starting image_info structure
790% (for compatibility with MagickCommandGenisis())
791%
792% o argc: the number of elements in the argument vector.
793%
794% o argv: A text array containing the command line arguments.
795%
796% o metadata: any metadata (for VBS) is returned here.
797% (for compatibility with MagickCommandGenisis())
798%
799% o exception: return any errors or warnings in this structure.
800%
801*/
802
803static MagickBooleanType MagickCommandUsage(void)
804{
805 static const char
806 channel_operators[] =
807 " -channel-fx expression\n"
808 " exchange, extract, or transfer one or more image channels\n"
809 " -separate separate an image channel into a grayscale image",
810 miscellaneous[] =
811 " -debug events display copious debugging information\n"
812 " -distribute-cache port\n"
813 " distributed pixel cache spanning one or more servers\n"
814 " -help print program options\n"
815 " -list type print a list of supported option arguments\n"
816 " -log format format of debugging information\n"
817 " -usage print program usage\n"
818 " -version print version information",
819 operators[] =
820 " -adaptive-blur geometry\n"
821 " adaptively blur pixels; decrease effect near edges\n"
822 " -adaptive-resize geometry\n"
823 " adaptively resize image using 'mesh' interpolation\n"
824 " -adaptive-sharpen geometry\n"
825 " adaptively sharpen pixels; increase effect near edges\n"
826 " -alpha option on, activate, off, deactivate, set, opaque, copy\n"
827 " transparent, extract, background, or shape\n"
828 " -annotate geometry text\n"
829 " annotate the image with text\n"
830 " -auto-gamma automagically adjust gamma level of image\n"
831 " -auto-level automagically adjust color levels of image\n"
832 " -auto-orient automagically orient (rotate) image\n"
833 " -auto-threshold method\n"
834 " automatically perform image thresholding\n"
835 " -bench iterations measure performance\n"
836 " -bilateral-blur geometry\n"
837 " non-linear, edge-preserving, and noise-reducing smoothing filter\n"
838 " -black-threshold value\n"
839 " force all pixels below the threshold into black\n"
840 " -blue-shift factor simulate a scene at nighttime in the moonlight\n"
841 " -blur geometry reduce image noise and reduce detail levels\n"
842 " -border geometry surround image with a border of color\n"
843 " -bordercolor color border color\n"
844 " -brightness-contrast geometry\n"
845 " improve brightness / contrast of the image\n"
846 " -canny geometry detect edges in the image\n"
847 " -cdl filename color correct with a color decision list\n"
848 " -channel mask set the image channel mask\n"
849 " -charcoal radius simulate a charcoal drawing\n"
850 " -chop geometry remove pixels from the image interior\n"
851 " -clahe geometry contrast limited adaptive histogram equalization\n"
852 " -clamp keep pixel values in range (0-QuantumRange)\n"
853 " -colorize value colorize the image with the fill color\n"
854 " -color-matrix matrix apply color correction to the image\n"
855 " -colors value preferred number of colors in the image\n"
856 " -connected-components connectivity\n"
857 " connected-components uniquely labeled\n"
858 " -contrast enhance or reduce the image contrast\n"
859 " -contrast-stretch geometry\n"
860 " improve contrast by 'stretching' the intensity range\n"
861 " -convolve coefficients\n"
862 " apply a convolution kernel to the image\n"
863 " -cycle amount cycle the image colormap\n"
864 " -decipher filename convert cipher pixels to plain pixels\n"
865 " -deskew threshold straighten an image\n"
866 " -despeckle reduce the speckles within an image\n"
867 " -distort method args\n"
868 " distort images according to given method and args\n"
869 " -draw string annotate the image with a graphic primitive\n"
870 " -edge radius apply a filter to detect edges in the image\n"
871 " -encipher filename convert plain pixels to cipher pixels\n"
872 " -emboss radius emboss an image\n"
873 " -enhance apply a digital filter to enhance a noisy image\n"
874 " -equalize perform histogram equalization to an image\n"
875 " -evaluate operator value\n"
876 " evaluate an arithmetic, relational, or logical expression\n"
877 " -extent geometry set the image size\n"
878 " -extract geometry extract area from image\n"
879 " -fft implements the discrete Fourier transform (DFT)\n"
880 " -flip flip image vertically\n"
881 " -floodfill geometry color\n"
882 " floodfill the image with color\n"
883 " -flop flop image horizontally\n"
884 " -frame geometry surround image with an ornamental border\n"
885 " -function name parameters\n"
886 " apply function over image values\n"
887 " -gamma value level of gamma correction\n"
888 " -gaussian-blur geometry\n"
889 " reduce image noise and reduce detail levels\n"
890 " -geometry geometry preferred size or location of the image\n"
891 " -grayscale method convert image to grayscale\n"
892 " -hough-lines geometry\n"
893 " identify lines in the image\n"
894 " -identify identify the format and characteristics of the image\n"
895 " -ift implements the inverse discrete Fourier transform (DFT)\n"
896 " -implode amount implode image pixels about the center\n"
897 " -integral calculate the sum of values (pixel values) in the image\n"
898 " -interpolative-resize geometry\n"
899 " resize image using interpolation\n"
900 " -kmeans geometry K means color reduction\n"
901 " -kuwahara geometry edge preserving noise reduction filter\n"
902 " -lat geometry local adaptive thresholding\n"
903 " -level value adjust the level of image contrast\n"
904 " -level-colors color,color\n"
905 " level image with the given colors\n"
906 " -linear-stretch geometry\n"
907 " improve contrast by 'stretching with saturation'\n"
908 " -liquid-rescale geometry\n"
909 " rescale image with seam-carving\n"
910 " -local-contrast geometry\n"
911 " enhance local contrast\n"
912 " -mean-shift geometry delineate arbitrarily shaped clusters in the image\n"
913 " -median geometry apply a median filter to the image\n"
914 " -mode geometry make each pixel the 'predominant color' of the\n"
915 " neighborhood\n"
916 " -modulate value vary the brightness, saturation, and hue\n"
917 " -monochrome transform image to black and white\n"
918 " -morphology method kernel\n"
919 " apply a morphology method to the image\n"
920 " -motion-blur geometry\n"
921 " simulate motion blur\n"
922 " -negate replace every pixel with its complementary color \n"
923 " -noise geometry add or reduce noise in an image\n"
924 " -normalize transform image to span the full range of colors\n"
925 " -opaque color change this color to the fill color\n"
926 " -ordered-dither NxN\n"
927 " add a noise pattern to the image with specific\n"
928 " amplitudes\n"
929 " -paint radius simulate an oil painting\n"
930 " -perceptible epsilon\n"
931 " pixel value less than |epsilon| become epsilon or\n"
932 " -epsilon\n"
933 " -polaroid angle simulate a Polaroid picture\n"
934 " -posterize levels reduce the image to a limited number of color levels\n"
935 " -profile filename add, delete, or apply an image profile\n"
936 " -quantize colorspace reduce colors in this colorspace\n"
937 " -raise value lighten/darken image edges to create a 3-D effect\n"
938 " -random-threshold low,high\n"
939 " random threshold the image\n"
940 " -range-threshold values\n"
941 " perform either hard or soft thresholding within some range of values in an image\n"
942 " -region geometry apply options to a portion of the image\n"
943 " -render render vector graphics\n"
944 " -resample geometry change the resolution of an image\n"
945 " -reshape geometry reshape the image\n"
946 " -resize geometry resize the image\n"
947 " -roll geometry roll an image vertically or horizontally\n"
948 " -rotate degrees apply Paeth rotation to the image\n"
949 " -rotational-blur angle\n"
950 " rotational blur the image\n"
951 " -sample geometry scale image with pixel sampling\n"
952 " -scale geometry scale the image\n"
953 " -segment values segment an image\n"
954 " -selective-blur geometry\n"
955 " selectively blur pixels within a contrast threshold\n"
956 " -sepia-tone threshold\n"
957 " simulate a sepia-toned photo\n"
958 " -set property value set an image property\n"
959 " -shade degrees shade the image using a distant light source\n"
960 " -shadow geometry simulate an image shadow\n"
961 " -sharpen geometry sharpen the image\n"
962 " -shave geometry shave pixels from the image edges\n"
963 " -shear geometry slide one edge of the image along the X or Y axis\n"
964 " -sigmoidal-contrast geometry\n"
965 " increase the contrast without saturating highlights or\n"
966 " shadows\n"
967 " -sketch geometry simulate a pencil sketch\n"
968 " -solarize threshold negate all pixels above the threshold level\n"
969 " -sort-pixels sort each scanline in ascending order of intensity\n"
970 " -sparse-color method args\n"
971 " fill in a image based on a few color points\n"
972 " -splice geometry splice the background color into the image\n"
973 " -spread radius displace image pixels by a random amount\n"
974 " -statistic type geometry\n"
975 " replace each pixel with corresponding statistic from the\n"
976 " neighborhood\n"
977 " -strip strip image of all profiles and comments\n"
978 " -swirl degrees swirl image pixels about the center\n"
979 " -threshold value threshold the image\n"
980 " -thumbnail geometry create a thumbnail of the image\n"
981 " -tile filename tile image when filling a graphic primitive\n"
982 " -tint value tint the image with the fill color\n"
983 " -transform affine transform image\n"
984 " -transparent color make this color transparent within the image\n"
985 " -transpose flip image vertically and rotate 90 degrees\n"
986 " -transverse flop image horizontally and rotate 270 degrees\n"
987 " -trim trim image edges\n"
988 " -type type image type\n"
989 " -unique-colors discard all but one of any pixel color\n"
990 " -unsharp geometry sharpen the image\n"
991 " -vignette geometry soften the edges of the image in vignette style\n"
992 " -wave geometry alter an image along a sine wave\n"
993 " -wavelet-denoise threshold\n"
994 " removes noise from the image using a wavelet transform\n"
995 " -white-balance automagically adjust white balance of image\n"
996 " -white-threshold value\n"
997 " force all pixels above the threshold into white",
998 sequence_operators[] =
999 " -append append an image sequence\n"
1000 " -clut apply a color lookup table to the image\n"
1001 " -coalesce merge a sequence of images\n"
1002 " -combine combine a sequence of images\n"
1003 " -compare mathematically and visually annotate the difference between an image and its reconstruction\n"
1004 " -complex operator perform complex mathematics on an image sequence\n"
1005 " -composite composite image\n"
1006 " -copy geometry offset\n"
1007 " copy pixels from one area of an image to another\n"
1008 " -crop geometry cut out a rectangular region of the image\n"
1009 " -deconstruct break down an image sequence into constituent parts\n"
1010 " -evaluate-sequence operator\n"
1011 " evaluate an arithmetic, relational, or logical expression\n"
1012 " -flatten flatten a sequence of images\n"
1013 " -fx expression apply mathematical expression to an image channel(s)\n"
1014 " -hald-clut apply a Hald color lookup table to the image\n"
1015 " -layers method optimize, merge, or compare image layers\n"
1016 " -morph value morph an image sequence\n"
1017 " -mosaic create a mosaic from an image sequence\n"
1018 " -poly terms build a polynomial from the image sequence and the corresponding\n"
1019 " terms (coefficients and degree pairs).\n"
1020 " -print string interpret string and print to console\n"
1021 " -process arguments process the image with a custom image filter\n"
1022 " -smush geometry smush an image sequence together\n"
1023 " -write filename write images to this file",
1024 settings[] =
1025 " -adjoin join images into a single multi-image file\n"
1026 " -affine matrix affine transform matrix\n"
1027 " -alpha option activate, deactivate, reset, or set the alpha channel\n"
1028 " -antialias remove pixel-aliasing\n"
1029 " -authenticate password\n"
1030 " decipher image with this password\n"
1031 " -attenuate value lessen (or intensify) when adding noise to an image\n"
1032 " -background color background color\n"
1033 " -bias value add bias when convolving an image\n"
1034 " -black-point-compensation\n"
1035 " use black point compensation\n"
1036 " -blue-primary point chromaticity blue primary point\n"
1037 " -bordercolor color border color\n"
1038 " -caption string assign a caption to an image\n"
1039 " -clip clip along the first path from the 8BIM profile\n"
1040 " -clip-mask filename associate a clip mask with the image\n"
1041 " -clip-path id clip along a named path from the 8BIM profile\n"
1042 " -colorspace type alternate image colorspace\n"
1043 " -comment string annotate image with comment\n"
1044 " -compose operator set image composite operator\n"
1045 " -compress type type of pixel compression when writing the image\n"
1046 " -define format:option\n"
1047 " define one or more image format options\n"
1048 " -delay value display the next image after pausing\n"
1049 " -density geometry horizontal and vertical density of the image\n"
1050 " -depth value image depth\n"
1051 " -direction type render text right-to-left or left-to-right\n"
1052 " -display server get image or font from this X server\n"
1053 " -dispose method layer disposal method\n"
1054 " -dither method apply error diffusion to image\n"
1055 " -encoding type text encoding type\n"
1056 " -endian type endianness (MSB or LSB) of the image\n"
1057 " -family name render text with this font family\n"
1058 " -features distance analyze image features (e.g. contrast, correlation)\n"
1059 " -fill color color to use when filling a graphic primitive\n"
1060 " -filter type use this filter when resizing an image\n"
1061 " -font name render text with this font\n"
1062 " -format \"string\" output formatted image characteristics\n"
1063 " -fuzz distance colors within this distance are considered equal\n"
1064 " -gravity type horizontal and vertical text placement\n"
1065 " -green-primary point chromaticity green primary point\n"
1066 " -illuminant type reference illuminant\n"
1067 " -intensity method method to generate an intensity value from a pixel\n"
1068 " -intent type type of rendering intent when managing the image color\n"
1069 " -interlace type type of image interlacing scheme\n"
1070 " -interline-spacing value\n"
1071 " set the space between two text lines\n"
1072 " -interpolate method pixel color interpolation method\n"
1073 " -interword-spacing value\n"
1074 " set the space between two words\n"
1075 " -kerning value set the space between two letters\n"
1076 " -label string assign a label to an image\n"
1077 " -limit type value pixel cache resource limit\n"
1078 " -loop iterations add Netscape loop extension to your GIF animation\n"
1079 " -matte store matte channel if the image has one\n"
1080 " -mattecolor color frame color\n"
1081 " -moments report image moments\n"
1082 " -monitor monitor progress\n"
1083 " -orient type image orientation\n"
1084 " -page geometry size and location of an image canvas (setting)\n"
1085 " -ping efficiently determine image attributes\n"
1086 " -pointsize value font point size\n"
1087 " -precision value maximum number of significant digits to print\n"
1088 " -preview type image preview type\n"
1089 " -quality value JPEG/MIFF/PNG compression level\n"
1090 " -quiet suppress all warning messages\n"
1091 " -read-mask filename associate a read mask with the image\n"
1092 " -red-primary point chromaticity red primary point\n"
1093 " -regard-warnings pay attention to warning messages\n"
1094 " -remap filename transform image colors to match this set of colors\n"
1095 " -repage geometry size and location of an image canvas\n"
1096 " -respect-parentheses settings remain in effect until parenthesis boundary\n"
1097 " -sampling-factor geometry\n"
1098 " horizontal and vertical sampling factor\n"
1099 " -scene value image scene number\n"
1100 " -seed value seed a new sequence of pseudo-random numbers\n"
1101 " -size geometry width and height of image\n"
1102 " -stretch type render text with this font stretch\n"
1103 " -stroke color graphic primitive stroke color\n"
1104 " -strokewidth value graphic primitive stroke width\n"
1105 " -style type render text with this font style\n"
1106 " -support factor resize support: > 1.0 is blurry, < 1.0 is sharp\n"
1107 " -synchronize synchronize image to storage device\n"
1108 " -taint declare the image as modified\n"
1109 " -texture filename name of texture to tile onto the image background\n"
1110 " -tile-offset geometry\n"
1111 " tile offset\n"
1112 " -treedepth value color tree depth\n"
1113 " -transparent-color color\n"
1114 " transparent color\n"
1115 " -undercolor color annotation bounding box color\n"
1116 " -units type the units of image resolution\n"
1117 " -verbose print detailed information about the image\n"
1118 " -view FlashPix viewing transforms\n"
1119 " -virtual-pixel method\n"
1120 " virtual pixel access method\n"
1121 " -weight type render text with this font weight\n"
1122 " -white-point point chromaticity white point\n"
1123 " -write-mask filename associate a write mask with the image"
1124 " -word-break type sets whether line breaks appear wherever the text would otherwise overflow",
1125 stack_operators[] =
1126 " -clone indexes clone an image\n"
1127 " -delete indexes delete the image from the image sequence\n"
1128 " -duplicate count,indexes\n"
1129 " duplicate an image one or more times\n"
1130 " -insert index insert last image into the image sequence\n"
1131 " -reverse reverse image sequence\n"
1132 " -swap indexes swap two images in the image sequence";
1133
1134 ListMagickVersion(stdout);
1135 (void) FormatLocaleFile(stdout,
1136 "Usage: %s tool [ {option} | {image} ... ] {output_image}\n",
1137 GetClientName());
1138 (void) FormatLocaleFile(stdout,
1139 "Usage: %s [ {option} | {image} ... ] {output_image}\n",GetClientName());
1140 (void) FormatLocaleFile(stdout,
1141 " %s [ {option} | {image} ... ] -script {filename} [ {script_args} ...]\n",
1142 GetClientName());
1143 (void) FormatLocaleFile(stdout,"\nImage Settings:\n");
1144 (void) FormatLocaleFile(stdout,"%s\n",settings);
1145 (void) FormatLocaleFile(stdout,"\nImage Operators:\n");
1146 (void) FormatLocaleFile(stdout,"%s\n",operators);
1147 (void) FormatLocaleFile(stdout,"\nImage Channel Operators:\n");
1148 (void) FormatLocaleFile(stdout,"%s\n",channel_operators);
1149 (void) FormatLocaleFile(stdout,"\nImage Sequence Operators:\n");
1150 (void) FormatLocaleFile(stdout,"%s\n",sequence_operators);
1151 (void) FormatLocaleFile(stdout,"\nImage Stack Operators:\n");
1152 (void) FormatLocaleFile(stdout,"%s\n",stack_operators);
1153 (void) FormatLocaleFile(stdout,"\nMiscellaneous Options:\n");
1154 (void) FormatLocaleFile(stdout,"%s\n",miscellaneous);
1155 (void) FormatLocaleFile(stdout,
1156 "\nBy default, the image format of 'file' is determined by its magic\n");
1157 (void) FormatLocaleFile(stdout,
1158 "number. To specify a particular image format, precede the filename\n");
1159 (void) FormatLocaleFile(stdout,
1160 "with an image format name and a colon (i.e. ps:image) or specify the\n");
1161 (void) FormatLocaleFile(stdout,
1162 "image type as the filename suffix (i.e. image.ps). Specify 'file' as\n");
1163 (void) FormatLocaleFile(stdout,"'-' for standard input or output.\n");
1164 return(MagickTrue);
1165}
1166
1167static void MagickUsage(MagickBooleanType verbose)
1168{
1169 const char
1170 *name;
1171
1172 size_t
1173 len;
1174
1175 name=GetClientName();
1176 len=strlen(name);
1177
1178 if (verbose == MagickFalse)
1179 {
1180 MagickCommandUsage();
1181 return;
1182 }
1183
1184 if (len>=7 && LocaleCompare("convert",name+len-7) == 0) {
1185 /* convert usage */
1186 (void) FormatLocaleFile(stdout,
1187 "Usage: %s [ {option} | {image} ... ] {output_image}\n",name);
1188 (void) FormatLocaleFile(stdout,
1189 " %s -help | -version | -usage | -list {option}\n\n",name);
1190 return;
1191 }
1192 else if (len>=6 && LocaleCompare("script",name+len-6) == 0) {
1193 /* magick-script usage */
1194 (void) FormatLocaleFile(stdout,
1195 "Usage: %s {filename} [ {script_args} ... ]\n",name);
1196 }
1197 else {
1198 /* magick usage */
1199 (void) FormatLocaleFile(stdout,
1200 "Usage: %s tool [ {option} | {image} ... ] {output_image}\n",name);
1201 (void) FormatLocaleFile(stdout,
1202 "Usage: %s [ {option} | {image} ... ] {output_image}\n",name);
1203 (void) FormatLocaleFile(stdout,
1204 " %s [ {option} | {image} ... ] -script {filename} [ {script_args} ...]\n",
1205 name);
1206 }
1207 (void) FormatLocaleFile(stdout,
1208 " %s -help | -version | -usage | -list {option}\n\n",name);
1209
1210 (void) FormatLocaleFile(stdout,"%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s\n",
1211 "All options are performed in a strict 'as you see them' order\n",
1212 "You must read-in images before you can operate on them.\n",
1213 "\n",
1214 "Magick Script files can use any of the following forms...\n",
1215 " #!/path/to/magick -script\n",
1216 "or\n",
1217 " #!/bin/sh\n",
1218 " :; exec magick -script \"$0\" \"$@\"; exit 10\n",
1219 " # Magick script from here...\n",
1220 "or\n",
1221 " #!/usr/bin/env magick-script\n",
1222 "The latter two forms do not require the path to the command hard coded.\n",
1223 "Note: \"magick-script\" needs to be linked to the \"magick\" command.\n",
1224 "\n",
1225 "For more information on usage, options, examples, and techniques\n",
1226 "see the ImageMagick website at ", MagickAuthoritativeURL);
1227
1228 return;
1229}
1230
1231/*
1232 Concatenate given file arguments to the given output argument.
1233 Used for a special -concatenate option used for specific 'delegates'.
1234 The option is not formally documented.
1235
1236 magick -concatenate files... output
1237
1238 This is much like the UNIX "cat" command, but for both UNIX and Windows,
1239 however the last argument provides the output filename.
1240*/
1241static MagickBooleanType ConcatenateImages(int argc,char **argv,
1242 ExceptionInfo *exception )
1243{
1244 FILE
1245 *input,
1246 *output;
1247
1248 MagickBooleanType
1249 status;
1250
1251 int
1252 c;
1253
1254 ssize_t
1255 i;
1256
1257 if (ExpandFilenames(&argc,&argv) == MagickFalse)
1258 ThrowFileException(exception,ResourceLimitError,"MemoryAllocationFailed",
1259 GetExceptionMessage(errno));
1260 if (IsPathAuthorized(WritePolicyRights,argv[argc-1]) == MagickFalse)
1261 ThrowPolicyException(argv[argc-1],MagickFalse);
1262 output=fopen_utf8(argv[argc-1],"wb");
1263 if (output == (FILE *) NULL)
1264 {
1265 ThrowFileException(exception,FileOpenError,"UnableToOpenFile",
1266 argv[argc-1]);
1267 return(MagickFalse);
1268 }
1269 status=MagickTrue;
1270 for (i=2; i < (ssize_t) (argc-1); i++)
1271 {
1272 if (IsPathAuthorized(ReadPolicyRights,argv[i]) == MagickFalse)
1273 ThrowPolicyException(argv[i],MagickFalse);
1274 input=fopen_utf8(argv[i],"rb");
1275 if (input == (FILE *) NULL)
1276 {
1277 ThrowFileException(exception,FileOpenError,"UnableToOpenFile",argv[i]);
1278 continue;
1279 }
1280 for (c=fgetc(input); c != EOF; c=fgetc(input))
1281 if (fputc((char) c,output) != c)
1282 status=MagickFalse;
1283 (void) fclose(input);
1284 (void) remove_utf8(argv[i]);
1285 }
1286 (void) fclose(output);
1287 return(status);
1288}
1289
1290WandExport MagickBooleanType MagickImageCommand(ImageInfo *image_info,int argc,
1291 char **argv,char **metadata,ExceptionInfo *exception)
1292{
1293 MagickCLI
1294 *cli_wand;
1295
1296 size_t
1297 len;
1298
1299 assert(image_info != (ImageInfo *) NULL);
1300
1301 /* For specific OS command line requirements */
1302 ReadCommandlLine(argc,&argv);
1303
1304 /* Initialize special "CLI Wand" to hold images and settings (empty) */
1305 cli_wand=AcquireMagickCLI(image_info,exception);
1306 cli_wand->location="Initializing";
1307 cli_wand->filename=argv[0];
1308 cli_wand->line=1;
1309
1310 if (cli_wand->wand.debug != MagickFalse)
1311 (void) CLILogEvent(cli_wand,CommandEvent,GetMagickModule(),
1312 "\"%s\"",argv[0]);
1313
1314
1315 GetPathComponent(argv[0],TailPath,cli_wand->wand.name);
1316 SetClientName(cli_wand->wand.name);
1317 ConcatenateMagickString(cli_wand->wand.name,"-CLI",MagickPathExtent);
1318
1319 len=strlen(argv[0]); /* precaution */
1320
1321 /* "convert" command - give a "deprecated" warning" */
1322 if (len>=7 && LocaleCompare("convert",argv[0]+len-7) == 0) {
1323 cli_wand->process_flags = ConvertCommandOptionFlags;
1324 }
1325
1326 /* Special Case: If command name ends with "script" implied "-script" */
1327 if (len>=6 && LocaleCompare("script",argv[0]+len-6) == 0) {
1328 if (argc >= 2 && ( (*(argv[1]) != '-') || (strlen(argv[1]) == 1) )) {
1329 GetPathComponent(argv[1],TailPath,cli_wand->wand.name);
1330 ProcessScriptOptions(cli_wand,argv[1],argc,argv,2);
1331 goto Magick_Command_Cleanup;
1332 }
1333 }
1334
1335 /* Special Case: Version Information and Abort */
1336 if (argc == 2) {
1337 if ((LocaleCompare("-version",argv[1]) == 0) || /* GNU standard option */
1338 (LocaleCompare("--version",argv[1]) == 0) ) { /* just version */
1339 CLIOption(cli_wand, "-version");
1340 goto Magick_Command_Exit;
1341 }
1342 if ((LocaleCompare("-help",argv[1]) == 0) || /* GNU standard option */
1343 (LocaleCompare("--help",argv[1]) == 0) ) { /* just a brief summary */
1344 if (cli_wand->wand.debug != MagickFalse)
1345 (void) CLILogEvent(cli_wand,CommandEvent,GetMagickModule(),
1346 "- Special Option \"%s\"", argv[1]);
1347 MagickUsage(MagickFalse);
1348 goto Magick_Command_Exit;
1349 }
1350 if (LocaleCompare("-usage",argv[1]) == 0) { /* both version & usage */
1351 if (cli_wand->wand.debug != MagickFalse)
1352 (void) CLILogEvent(cli_wand,CommandEvent,GetMagickModule(),
1353 "- Special Option \"%s\"", argv[1]);
1354 CLIOption(cli_wand, "-version" );
1355 MagickUsage(MagickTrue);
1356 goto Magick_Command_Exit;
1357 }
1358 }
1359
1360 /* not enough arguments -- including -help */
1361 if (argc < 3) {
1362 (void) ThrowMagickException(exception,GetMagickModule(),OptionError,
1363 "InvalidArgument","%s",argc > 1 ? argv[argc-1] : "");
1364 MagickUsage(MagickFalse);
1365 goto Magick_Command_Exit;
1366 }
1367
1368 /* Special "concatenate option (hidden) for delegate usage */
1369 if (LocaleCompare("-concatenate",argv[1]) == 0) {
1370 if (cli_wand->wand.debug != MagickFalse)
1371 (void) CLILogEvent(cli_wand,CommandEvent,GetMagickModule(),
1372 "- Special Option \"%s\"", argv[1]);
1373 ConcatenateImages(argc,argv,exception);
1374 goto Magick_Command_Exit;
1375 }
1376
1377 /* List Information and Abort */
1378 if (argc == 3 && LocaleCompare("-list",argv[1]) == 0) {
1379 CLIOption(cli_wand, argv[1], argv[2]);
1380 goto Magick_Command_Exit;
1381 }
1382
1383 /* ------------- */
1384 /* The Main Call */
1385
1386 if (LocaleCompare("-script",argv[1]) == 0) {
1387 /* Start processing directly from script, no pre-script options
1388 Replace wand command name with script name
1389 First argument in the argv array is the script name to read.
1390 */
1391 GetPathComponent(argv[2],TailPath,cli_wand->wand.name);
1392 ProcessScriptOptions(cli_wand,argv[2],argc,argv,3);
1393 }
1394 else {
1395 /* Normal Command Line, assumes output file as last option */
1396 ProcessCommandOptions(cli_wand,argc,argv,1);
1397 }
1398 /* ------------- */
1399
1400Magick_Command_Cleanup:
1401 cli_wand->location="Cleanup";
1402 cli_wand->filename=argv[0];
1403 if (cli_wand->wand.debug != MagickFalse)
1404 (void) CLILogEvent(cli_wand,CommandEvent,GetMagickModule(),
1405 "\"%s\"",argv[0]);
1406
1407 /* recover original image_info and clean up stacks
1408 FUTURE: "-reset stacks" option */
1409 while ((cli_wand->image_list_stack != (CLIStack *) NULL) &&
1410 (cli_wand->image_list_stack->next != (CLIStack *) NULL))
1411 CLIOption(cli_wand,")");
1412 while ((cli_wand->image_info_stack != (CLIStack *) NULL) &&
1413 (cli_wand->image_info_stack->next != (CLIStack *) NULL))
1414 CLIOption(cli_wand,"}");
1415
1416 /* assert we have recovered the original structures */
1417 assert(cli_wand->wand.image_info == image_info);
1418 assert(cli_wand->wand.exception == exception);
1419
1420 /* Handle metadata for ImageMagickObject COM object for Windows VBS */
1421 if ((cli_wand->wand.images != (Image *) NULL) &&
1422 (metadata != (char **) NULL))
1423 {
1424 const char
1425 *format;
1426
1427 char
1428 *text;
1429
1430 format="%w,%h,%m"; /* Get this from image_info Option splaytree */
1431 text=InterpretImageProperties(image_info,cli_wand->wand.images,format,
1432 exception);
1433 if (text == (char *) NULL)
1434 ThrowMagickException(exception,GetMagickModule(),ResourceLimitError,
1435 "MemoryAllocationFailed","`%s'", GetExceptionMessage(errno));
1436 else
1437 {
1438 (void) ConcatenateString(&(*metadata),text);
1439 text=DestroyString(text);
1440 }
1441 }
1442
1443Magick_Command_Exit:
1444 cli_wand->location="Exiting";
1445 cli_wand->filename=argv[0];
1446 if (cli_wand->wand.debug != MagickFalse)
1447 (void) CLILogEvent(cli_wand,CommandEvent,GetMagickModule(),
1448 "\"%s\"",argv[0]);
1449
1450 /* Destroy the special CLI Wand */
1451 cli_wand->wand.image_info = (ImageInfo *) NULL; /* not these */
1452 cli_wand->wand.exception = (ExceptionInfo *) NULL;
1453 cli_wand=DestroyMagickCLI(cli_wand);
1454
1455 return(exception->severity < ErrorException ? MagickTrue : MagickFalse);
1456}