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 16 class Command { 17 public: 18 Command(const BString& name, 19 const BString& shortUsage, 20 const BString& longUsage, 21 const BString& category); 22 virtual ~Command(); 23 24 void Init(const char* programName); 25 26 const BString& Name() const { return fName; } 27 const BString& ShortUsage() const { return fShortUsage; } 28 const BString& LongUsage() const { return fLongUsage; } 29 const BString& Category() const { return fCategory; } 30 31 void PrintUsage(bool error) const; 32 void PrintUsageAndExit(bool error) const; 33 34 virtual int Execute(int argc, const char* const* argv) = 0; 35 36 private: 37 BString fName; 38 BString fShortUsage; 39 BString fLongUsage; 40 BString fCategory; 41 }; 42 43 44 typedef BObjectList<Command> CommandList; 45 46 47 class CommandManager { 48 public: 49 static CommandManager* Default(); 50 51 void RegisterCommand(Command* command); 52 void InitCommands(const char* programName); 53 54 const CommandList& Commands() const 55 { return fCommands; } 56 void GetCommands(const char* prefix, 57 CommandList& _commands); 58 void GetCommandsForCategory(const char* category, 59 CommandList& _commands); 60 61 private: 62 CommandManager(); 63 64 private: 65 CommandList fCommands; 66 }; 67 68 69 template<typename CommandType> 70 struct CommandRegistrar { 71 CommandRegistrar() 72 { 73 CommandManager::Default()->RegisterCommand(new CommandType); 74 } 75 }; 76 77 78 #define DEFINE_COMMAND(className, name, shortUsage, longUsage, category) \ 79 struct className : Command { \ 80 className() \ 81 : \ 82 Command(name, shortUsage, longUsage, category) \ 83 { \ 84 } \ 85 \ 86 virtual int Execute(int argc, const char* const* argv); \ 87 }; \ 88 static CommandRegistrar<className> sRegister##className; 89 90 91 #endif // COMMAND_H 92