1/* This file is part of the KDE project
2 Copyright (C) 1999 Waldo Bastian <bastian@kde.org>
3
4 This library is free software; you can redistribute it and/or
5 modify it under the terms of the GNU Library General Public
6 License version 2 as published by the Free Software Foundation.
7
8 This library is distributed in the hope that it will be useful,
9 but WITHOUT ANY WARRANTY; without even the implied warranty of
10 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 Library General Public License for more details.
12
13 You should have received a copy of the GNU Library General Public License
14 along with this library; see the file COPYING.LIB. If not, write to
15 the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
16 Boston, MA 02110-1301, USA.
17*/
18
19#ifndef KCMDLINEARGS_H
20#define KCMDLINEARGS_H
21
22#include <kdecore_export.h>
23#include <QtCore/QBool>
24
25#include <klocale.h>
26
27template <class T> class QList;
28class QString;
29class QStringList;
30class QByteArray;
31class QDataStream;
32class KUrl;
33
34class KCmdLineArgs;
35class KCmdLineArgsPrivate;
36class KCmdLineArgsStatic;
37class KCmdLineOptionsPrivate;
38
39/**
40 * @short Class that holds command line options.
41 *
42 * This class is intended to be used with the KCmdLineArgs class, which
43 * provides convenient and powerful command line argument parsing and
44 * handling functionality.
45 *
46 * @see KCmdLineArgs for additional usage information
47 */
48class KDECORE_EXPORT KCmdLineOptions
49{
50 friend class KCmdLineArgs;
51 friend class KCmdLineArgsStatic;
52
53 public:
54 /**
55 * Constructor.
56 */
57 KCmdLineOptions ();
58
59 /**
60 * Copy constructor.
61 */
62 KCmdLineOptions (const KCmdLineOptions &options);
63
64 /**
65 * Assignment operator.
66 */
67 KCmdLineOptions& operator= (const KCmdLineOptions &options);
68
69 /**
70 * Destructor.
71 */
72 ~KCmdLineOptions ();
73
74 /**
75 * Add command line option, by providing its name, description, and
76 * possibly a default value. These will print out when <i>myapp --help</i>
77 * is called on the command line.
78 *
79 * Note that a long option can only have one short (single character) alias
80 *
81 * @since 4.6 Note that the following does not apply to options that begin
82 * with "no" and expect a parameter, like "nooption4" in the example below.
83 *
84 * Note that if the option name begin with "no" that you will need to test
85 * for the name without the "no" and the result will be the inverse of what
86 * is specified. i.e. if "nofoo" is the name of the option and
87 * <i>myapp --nofoo</i> is called:
88 *
89 * @code
90 * KCmdLineArgs::parsedArgs()->isSet("foo"); // false
91 * @endcode
92 *
93 * Here are some more examples showing various features:
94 *
95 * @code
96 * KCmdLineOptions options;
97 * options.add("a", ki18n("A short binary option"));
98 * options.add("b \<file>", ki18n("A short option which takes an argument"));
99 * options.add("c \<speed>", ki18n("As above but with a default value"), "9600");
100 * options.add("option1", ki18n("A long binary option, off by default"));
101 * options.add("nooption2", ki18n("A long binary option, on by default"));
102 * options.add(":", ki18n("Extra options:"));
103 * options.add("option3 \<file>", ki18n("A long option which takes an argument"));
104 * options.add("nooption4 \<speed>", ki18n("A long option which takes an argument, defaulting to 9600"), "9600");
105 * options.add("d").add("option5", ki18n("A long option which has a short option as alias"));
106 * options.add("e").add("nooption6", ki18n("Another long option with an alias"));
107 * options.add("f").add("option7 \<speed>", ki18n("'--option7 speed' is the same as '-f speed'"));
108 * options.add("!option8 \<cmd>", ki18n("All options following this one will be treated as arguments"));
109 * options.add("+file", ki18n("A required argument 'file'"));
110 * options.add("+[arg1]", ki18n("An optional argument 'arg1'"));
111 * options.add("!+command", ki18n("A required argument 'command', that can contain multiple words, even starting with '-'"));
112 * options.add("", ki18n("Additional help text not associated with any particular option"));
113 * @endcode
114 *
115 * @param name option name
116 * @param description option description, made available for translation;
117 * can be left off
118 * @param defaultValue default option value, when the value is not specified
119 * on the command line; can be left off
120 */
121 KCmdLineOptions &add (const QByteArray &name,
122 const KLocalizedString &description = KLocalizedString(),
123 const QByteArray &defaultValue = QByteArray());
124
125 /**
126 * Add all options from another KCmdLineOptions object.
127 *
128 * @param options options to add
129 */
130 KCmdLineOptions &add (const KCmdLineOptions &options);
131
132 private:
133
134 KCmdLineOptionsPrivate *d; //krazy:exclude=dpointer (for operator=)
135};
136
137class KCmdLineArgsList;
138class KApplication;
139class KAboutData;
140
141/**
142 * @short A class for command-line argument handling.
143 *
144 * KCmdLineArgs provides simple access to the command-line arguments
145 * for an application. It takes into account Qt-specific options,
146 * KDE-specific options and application specific options.
147 *
148 * This class is used in %main() via the static method
149 * init().
150 *
151 * A typical %KDE application using %KCmdLineArgs should look like this:
152 *
153 * @code
154 * int main(int argc, char *argv[])
155 * {
156 * // Initialize command line args
157 * KCmdLineArgs::init(argc, argv, appName, programName, version, description);
158 *
159 * // Define the command line options using KCmdLineOptions
160 * KCmdLineOptions options;
161 * ....
162 *
163 * // Register the supported options
164 * KCmdLineArgs::addCmdLineOptions( options );
165 *
166 * // Add options from other components
167 * KUniqueApplication::addCmdLineOptions();
168 *
169 * ....
170 *
171 * // Create application object without passing 'argc' and 'argv' again.
172 * KUniqueApplication app;
173 *
174 * ....
175 *
176 * // Handle our own options/arguments
177 * // A KApplication will usually do this in main but this is not
178 * // necessary.
179 * // A KUniqueApplication might want to handle it in newInstance().
180 *
181 * KCmdLineArgs *args = KCmdLineArgs::parsedArgs();
182 *
183 * // A binary option (on / off)
184 * if (args->isSet("some-option"))
185 * ....
186 *
187 * // An option which takes an additional argument
188 * QString anotherOptionArg = args->getOption("another-option");
189 *
190 * // Arguments (e.g. files to open)
191 * for(int i = 0; i < args->count(); i++) // Counting start at 0!
192 * {
193 * openFile( args->arg(i));
194 * // Or more convenient:
195 * // openUrl( args->url(i));
196 *
197 * }
198 *
199 * args->clear(); // Free up some memory.
200 * ....
201 * }
202 * @endcode
203 *
204 * The options that an application supports are configured using the
205 * KCmdLineOptions class. An example is shown below:
206 *
207 * @code
208 * KCmdLineOptions options;
209 * options.add("a", ki18n("A short binary option"));
210 * options.add("b \<file>", ki18n("A short option which takes an argument"));
211 * options.add("c \<speed>", ki18n("As above but with a default value"), "9600");
212 * options.add("option1", ki18n("A long binary option, off by default"));
213 * options.add("nooption2", ki18n("A long binary option, on by default"));
214 * options.add(":", ki18n("Extra options:"));
215 * options.add("option3 \<file>", ki18n("A long option which takes an argument"));
216 * options.add("option4 \<speed>", ki18n("A long option which takes an argument, defaulting to 9600"), "9600");
217 * options.add("d").add("option5", ki18n("A long option which has a short option as alias"));
218 * options.add("e").add("nooption6", ki18n("Another long option with an alias"));
219 * options.add("f").add("option7 \<speed>", ki18n("'--option7 speed' is the same as '-f speed'"));
220 * options.add("!option8 \<cmd>", ki18n("All options following this one will be treated as arguments"));
221 * options.add("+file", ki18n("A required argument 'file'"));
222 * options.add("+[arg1]", ki18n("An optional argument 'arg1'"));
223 * options.add("!+command", ki18n("A required argument 'command', that can contain multiple words, even starting with '-'"));
224 * options.add("", ki18n("Additional help text not associated with any particular option"));
225 * @endcode
226 *
227 * The ki18n calls are used for translation instead of the more usual i18n
228 * calls, because the translation needs to be delayed until after the
229 * message catalogs have been initialized.
230 *
231 * Note that a program should define the options before any arguments.
232 *
233 * When a long option has a short option as an alias, a program should
234 * only test for the long option.
235 *
236 * With the above options a command line could look like:
237 * @code
238 * myapp -a -c 4800 --display localhost:0.0 --nooption5 -d /tmp/file
239 * @endcode
240 *
241 * Long binary options can be in the form 'option' and 'nooption'.
242 * A command line may contain the same binary option multiple times,
243 * the last option determines the outcome:
244 * @code
245 * myapp --nooption4 --option4 --nooption4
246 * @endcode
247 * is the same as:
248 * @code
249 * myapp --nooption4
250 * @endcode
251 *
252 * If an option value is provided multiple times, normally only the last
253 * value is used:
254 * @code
255 * myapp -c 1200 -c 2400 -c 4800
256 * @endcode
257 * is usually the same as:
258 * @code
259 * myapp -c 4800
260 * @endcode
261 *
262 * However, an application can choose to use all values specified as well.
263 * As an example of this, consider that you may wish to specify a
264 * number of directories to use:
265 * @code
266 * myapp -I /usr/include -I /opt/kde/include -I /usr/X11/include
267 * @endcode
268 * When an application does this it should mention this in the description
269 * of the option. To access these options, use getOptionList()
270 *
271 * Tips for end-users:
272 *
273 * @li Single char options like "-a -b -c" may be combined into "-abc"
274 * @li The option "--foo bar" may also be written "--foo=bar"
275 * @li The option "-P lp1" may also be written "-P=lp1" or "-Plp1"
276 * @li The option "--foo bar" may also be written "-foo bar"
277 *
278 * @author Waldo Bastian
279 * @version 0.0.4
280 */
281class KDECORE_EXPORT KCmdLineArgs
282{
283 friend class KApplication;
284 friend class KCmdLineArgsList;
285 friend class KCmdLineArgsStatic;
286public:
287 // Static functions:
288
289 enum StdCmdLineArg {
290 CmdLineArgQt = 0x01,
291 CmdLineArgKDE = 0x02,
292 CmdLineArgsMask=0x03,
293 CmdLineArgNone = 0x00,
294 Reserved = 0xff
295 };
296 Q_DECLARE_FLAGS(StdCmdLineArgs, StdCmdLineArg)
297 /**
298 * Initialize class.
299 *
300 * This function should be called as the very first thing in
301 * your application.
302 * @param argc As passed to @p main(...).
303 * @param argv As passed to @p main(...).
304 * @param appname The untranslated name of your application. This should
305 * match with @p argv[0].
306 * @param catalog Translation catalog name, if empty @p appname will be used.
307 * @param programName A program name string to be used for display
308 * purposes. This string should be marked for translation.
309 * Example: ki18n("KEdit")
310 * @param version A version.
311 * @param description A short description of what your application is about.
312 * Also marked for translation.
313 * @param stdargs KDE/Qt or no default parameters
314 */
315 static void init(int argc, char **argv,
316 const QByteArray &appname,
317 const QByteArray &catalog,
318 const KLocalizedString &programName,
319 const QByteArray &version,
320 const KLocalizedString &description = KLocalizedString(),
321 StdCmdLineArgs stdargs=StdCmdLineArgs(CmdLineArgQt|CmdLineArgKDE));
322
323 /**
324 * Initialize class.
325 *
326 * This function should be called as the very first thing in
327 * your application. It uses KAboutData to replace some of the
328 * arguments that would otherwise be required.
329 *
330 * @param _argc As passed to @p main(...).
331 * @param _argv As passed to @p main(...).
332 * @param about A KAboutData object describing your program.
333 * @param stdargs KDE/Qt or no default parameters
334 */
335 static void init(int _argc,
336 char **_argv,
337 const KAboutData *about,
338 StdCmdLineArgs stdargs=StdCmdLineArgs(CmdLineArgQt|CmdLineArgKDE));
339 /**
340 * Initialize Class
341 *
342 * This function should be called as the very first thing in your
343 * application. This method will rarely be used, since it doesn't
344 * provide any argument parsing. It does provide access to the
345 * KAboutData information.
346 * This method is exactly the same as calling
347 * init(0,0, const KAboutData *about, CmdLineArgNone).
348 *
349 * @param about the about data.
350 * @see KAboutData
351 */
352 static void init(const KAboutData *about);
353
354 /**
355 * add standard Qt/KDE command-line args
356 */
357 static void addStdCmdLineOptions(StdCmdLineArgs stdargs=StdCmdLineArgs(CmdLineArgQt|CmdLineArgKDE));
358
359 /**
360 * Add options to your application.
361 *
362 * You must make sure that all possible options have been added before
363 * any class uses the command line arguments.
364 *
365 * The list of options should look like this:
366 *
367 * @code
368 * KCmdLineOptions options;
369 * options.add("option1 \<argument>", ki18n("Description 1"), "my_extra_arg");
370 * options.add("o");
371 * options.add("option2", ki18n("Description 2"));
372 * options.add("nooption3", ki18n("Description 3"));
373 * options.add("+file", ki18n("A required argument 'file'"));
374 * @endcode
375 *
376 * @li "option1" is an option that requires an additional argument,
377 * but if one is not provided, it uses "my_extra_arg".
378 * @li "option2" is an option that can be turned on. The default is off.
379 * @li "option3" is an option that can be turned off. The default is on.
380 * @li "o" does not have a description. It is an alias for the option
381 * that follows. In this case "option2".
382 * @li "+file" specifies an argument. The '+' is removed. If your program
383 * doesn't specify that it can use arguments your program will abort
384 * when an argument is passed to it. Note that the reverse is not
385 * true. If required, you must check yourself the number of arguments
386 * specified by the user:
387 * @code
388 * KCmdLineArgs *args = KCmdLineArgs::parsedArgs();
389 * if (args->count() == 0) KCmdLineArgs::usage(i18n("No file specified"));
390 * @endcode
391 *
392 * In BNF:
393 * @code
394 * cmd = myapp [options] file
395 * options = (option)*
396 * option = --option1 \<argument> |
397 * (-o | --option2 | --nooption2) |
398 * ( --option3 | --nooption3 )
399 * @endcode
400 *
401 * Instead of "--option3" one may also use "-option3"
402 *
403 * Usage examples:
404 *
405 * @li "myapp --option1 test"
406 * @li "myapp" (same as "myapp --option1 my_extra_arg")
407 * @li "myapp --option2"
408 * @li "myapp --nooption2" (same as "myapp", since it is off by default)
409 * @li "myapp -o" (same as "myapp --option2")
410 * @li "myapp --nooption3"
411 * @li "myapp --option3 (same as "myapp", since it is on by default)
412 * @li "myapp --option2 --nooption2" (same as "myapp", because it
413 * option2 is off by default, and the last usage applies)
414 * @li "myapp /tmp/file"
415 *
416 * @param options A list of options that your code supplies.
417 * @param name the name of the option list, as displayed by
418 * the help output. Can be empty.
419 * @param id A name with which these options can be identified, can be empty.
420 * @param afterId The options are inserted after this set of options, can be empty.
421 */
422 static void addCmdLineOptions(const KCmdLineOptions &options,
423 const KLocalizedString &name = KLocalizedString(),
424 const QByteArray &id = QByteArray(),
425 const QByteArray &afterId = QByteArray());
426
427 /**
428 * Access parsed arguments.
429 *
430 * This function returns all command line arguments that your code
431 * handles. If unknown command-line arguments are encountered the program
432 * is aborted and usage information is shown.
433 *
434 * @param id The name of the options you are interested in, can be empty.
435 */
436 static KCmdLineArgs *parsedArgs(const QByteArray &id = QByteArray());
437
438 /**
439 * Get the CWD (Current Working Directory) associated with the
440 * current command line arguments.
441 *
442 * Typically this is needed in KUniqueApplication::newInstance()
443 * since the CWD of the process may be different from the CWD
444 * where the user started a second instance.
445 * @return the current working directory
446 **/
447 static QString cwd();
448
449 /**
450 * Get the appname according to argv[0].
451 * @return the name of the application
452 **/
453 static QString appName();
454
455 /**
456 * Print the usage help to stdout and exit.
457 *
458 * @param id if empty, print all options. If id is set, only print the
459 * option specified by id. The id is the value set by
460 * addCmdLineOptions().
461 **/
462 static void usage(const QByteArray &id = QByteArray());
463
464 /**
465 * Print an error to stderr and the usage help to stdout and exit.
466 * @param error the error to print
467 **/
468 static void usageError(const QString &error);
469
470 /**
471 * Enable i18n to be able to print a translated error message.
472 *
473 * N.B.: This function leaks memory, therefore you are expected to exit
474 * afterwards (e.g., by calling usage()).
475 **/
476 static void enable_i18n();
477
478 // Member functions:
479
480
481 /**
482 * Read out a string option.
483 *
484 * The option must have a corresponding KCmdLineOptions entry
485 * of the form:
486 * @code
487 * options.add("option \<argument>", ki18n("Description"), "default");
488 * @endcode
489 * You cannot test for the presence of an alias - you must always
490 * test for the full option.
491 *
492 * @param option The name of the option without '-'.
493 *
494 * @return The value of the option. If the option was not
495 * present on the command line the default is returned.
496 * If the option was present more than once, the value of the
497 * last occurrence is used.
498 */
499 QString getOption(const QByteArray &option) const;
500
501 /**
502 * Read out all occurrences of a string option.
503 *
504 * The option must have a corresponding KCmdLineOptions entry
505 * of the form:
506 * @code
507 * options.add("option \<argument>", ki18n("Description"), "default");
508 * @endcode
509 * You cannot test for the presence of an alias - you must always
510 * test for the full option.
511 *
512 * @param option The name of the option, without '-' or '-no'.
513 *
514 * @return A list of all option values. If no option was present
515 * on the command line, an empty list is returned.
516 */
517 QStringList getOptionList(const QByteArray &option) const;
518
519 /**
520 * Read out a boolean option or check for the presence of string option.
521 *
522 * @param option The name of the option without '-' or '-no'.
523 *
524 * @return The value of the option. It will be true if the option
525 * was specifically turned on in the command line, or if the option
526 * is turned on by default (in the KCmdLineOptions list) and was
527 * not specifically turned off in the command line. Equivalently,
528 * it will be false if the option was specifically turned off in
529 * the command line, or if the option is turned off by default (in
530 * the KCmdLineOptions list) and was not specifically turned on in
531 * the command line.
532 */
533 bool isSet(const QByteArray &option) const;
534
535 /**
536 * Read the number of arguments that aren't options (but,
537 * for example, filenames).
538 *
539 * @return The number of arguments that aren't options
540 */
541 int count() const;
542
543 /**
544 * Read out an argument.
545 *
546 * @param n The argument to read. 0 is the first argument.
547 * count()-1 is the last argument.
548 *
549 * @return n-th argument
550 */
551 QString arg(int n) const;
552
553 /**
554 * Read out an argument representing a URL.
555 *
556 * The argument can be
557 * @li an absolute filename
558 * @li a relative filename
559 * @li a URL
560 *
561 * @param n The argument to read. 0 is the first argument.
562 * count()-1 is the last argument.
563 *
564 * @return a URL representing the n'th argument.
565 */
566 KUrl url(int n) const;
567
568 /**
569 * Used by url().
570 * Made public for apps that don't use KCmdLineArgs
571 * @param urlArg the argument
572 * @return the url.
573 */
574 static KUrl makeURL( const QByteArray &urlArg );
575
576 /**
577 * Made public for apps that don't use KCmdLineArgs
578 * To be done before makeURL, to set the current working
579 * directory in case makeURL needs it.
580 * @param cwd the new working directory
581 */
582 static void setCwd( const QByteArray &cwd );
583
584 /**
585 * Clear all options and arguments.
586 */
587 void clear();
588
589 /**
590 * Reset all option definitions, i.e. cancel all addCmdLineOptions calls.
591 * Note that KApplication's options are removed too, you might want to
592 * call KApplication::addCmdLineOptions if you want them back.
593 *
594 * You usually don't want to call this method.
595 */
596 static void reset();
597
598 /**
599 * Load arguments from a stream.
600 */
601 static void loadAppArgs( QDataStream &);
602
603 /**
604 * @internal for KUniqueApplication only:
605 *
606 * Save all but the Qt and KDE arguments to a stream.
607 */
608 static void saveAppArgs( QDataStream &);
609
610 /**
611 * Add standard option --tempfile
612 */
613 static void addTempFileOption();
614
615 // this avoids having to know the "id" used by addTempFileOption
616 // but this approach doesn't scale well, we can't have 50 standard options here...
617 /**
618 * @return true if --tempfile was set
619 */
620 static bool isTempFileSet();
621
622 /**
623 * Returns the number of arguments returned by qtArgv()
624 *
625 * @see qtArgv
626 */
627 static int &qtArgc();
628
629 /**
630 * Returns command line options for consumption by Qt after parsing them in a way that
631 * is consistent with KDE's general command line handling. In particular this ensures
632 * that Qt command line options can be specified as either -option or --option and that
633 * any options specified after '--' will be ignored.
634 *
635 * @see qt_argc
636 */
637 static char **qtArgv();
638
639 /**
640 * Returns the list of command-line arguments.
641 * @since 4.6
642 */
643 static QStringList allArguments();
644
645 /**
646 * Returns the KAboutData for consumption by KComponentData
647 */
648 static const KAboutData *aboutData();
649
650protected:
651 /**
652 * @internal
653 * Constructor.
654 */
655 KCmdLineArgs( const KCmdLineOptions &_options, const KLocalizedString &_name,
656 const QByteArray &_id);
657
658 /**
659 * @internal use only.
660 *
661 * Use clear() if you want to free up some memory.
662 *
663 * Destructor.
664 */
665 ~KCmdLineArgs();
666
667private:
668
669 /**
670 * @internal for KApplication only
671 *
672 * Initialize class.
673 *
674 * This function should be called as the very first thing in
675 * your application.
676 * @param argc As passed to @p main(...).
677 * @param argv As passed to @p main(...).
678 * @param appname The untranslated name of your application. This should
679 * match with @p argv[0].
680 *
681 * This function makes KCmdLineArgs ignore all unknown options as well as
682 * all arguments.
683 */
684 static void initIgnore(int _argc, char **_argv, const QByteArray &_appname);
685
686 KCmdLineArgsPrivate *const d;
687};
688
689Q_DECLARE_OPERATORS_FOR_FLAGS(KCmdLineArgs::StdCmdLineArgs)
690
691#endif
692
693