1 /* 2 * Copyright 2013, Haiku, Inc. All Rights Reserved. 3 * Distributed under the terms of the MIT License. 4 * 5 * Authors: 6 * Ingo Weinhold <ingo_weinhold@gmx.de> 7 */ 8 #ifndef COMMAND_H 9 #define COMMAND_H 10 11 12 #include <ObjectList.h> 13 #include <String.h> 14 15 #include "CommonOptions.h" 16 17 18 class Command { 19 public: 20 Command(const BString& name, 21 const BString& shortUsage, 22 const BString& longUsage, 23 const BString& category); 24 virtual ~Command(); 25 26 void Init(const char* programName); 27 Name()28 const BString& Name() const { return fName; } ShortUsage()29 const BString& ShortUsage() const { return fShortUsage; } LongUsage()30 const BString& LongUsage() const { return fLongUsage; } Category()31 const BString& Category() const { return fCategory; } 32 33 void PrintUsage(bool error) const; 34 void PrintUsageAndExit(bool error) const; 35 36 virtual int Execute(int argc, const char* const* argv) = 0; 37 38 protected: 39 CommonOptions fCommonOptions; 40 41 private: 42 BString fName; 43 BString fShortUsage; 44 BString fLongUsage; 45 BString fCategory; 46 }; 47 48 49 typedef BObjectList<Command> CommandList; 50 51 52 class CommandManager { 53 public: 54 static CommandManager* Default(); 55 56 void RegisterCommand(Command* command); 57 void InitCommands(const char* programName); 58 Commands()59 const CommandList& Commands() const 60 { return fCommands; } 61 void GetCommands(const char* prefix, 62 CommandList& _commands); 63 void GetCommandsForCategory(const char* category, 64 CommandList& _commands); 65 66 private: 67 CommandManager(); 68 69 private: 70 CommandList fCommands; 71 }; 72 73 74 template<typename CommandType> 75 struct CommandRegistrar { CommandRegistrarCommandRegistrar76 CommandRegistrar() 77 { 78 CommandManager::Default()->RegisterCommand(new CommandType); 79 } 80 }; 81 82 83 #define DEFINE_COMMAND(className, name, shortUsage, longUsage, category) \ 84 struct className : Command { \ 85 className() \ 86 : \ 87 Command(name, shortUsage, longUsage, category) \ 88 { \ 89 } \ 90 \ 91 virtual int Execute(int argc, const char* const* argv); \ 92 }; \ 93 static CommandRegistrar<className> sRegister##className; 94 95 96 #endif // COMMAND_H 97