cmd.cpp 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  1. /*
  2. * Copyright 2010-2017 Branimir Karadzic. All rights reserved.
  3. * License: https://github.com/bkaradzic/bgfx#license-bsd-2-clause
  4. */
  5. #include <ctype.h> // isspace
  6. #include <stdint.h>
  7. #include <stdlib.h> // size_t
  8. #include <string.h> // strlen
  9. #include <bx/allocator.h>
  10. #include <bx/hash.h>
  11. #include <bx/commandline.h>
  12. #include "dbg.h"
  13. #include "cmd.h"
  14. #include "entry_p.h"
  15. #include <tinystl/allocator.h>
  16. #include <tinystl/string.h>
  17. #include <tinystl/unordered_map.h>
  18. namespace stl = tinystl;
  19. struct CmdContext
  20. {
  21. CmdContext()
  22. {
  23. }
  24. ~CmdContext()
  25. {
  26. }
  27. void add(const char* _name, ConsoleFn _fn, void* _userData)
  28. {
  29. uint32_t cmd = bx::hashMurmur2A(_name, (uint32_t)strlen(_name) );
  30. BX_CHECK(m_lookup.end() == m_lookup.find(cmd), "Command \"%s\" already exist.", _name);
  31. Func fn = { _fn, _userData };
  32. m_lookup.insert(stl::make_pair(cmd, fn) );
  33. }
  34. void exec(const char* _cmd)
  35. {
  36. for (const char* next = _cmd; '\0' != *next; _cmd = next)
  37. {
  38. char commandLine[1024];
  39. uint32_t size = sizeof(commandLine);
  40. int argc;
  41. char* argv[64];
  42. next = bx::tokenizeCommandLine(_cmd, commandLine, size, argc, argv, BX_COUNTOF(argv), '\n');
  43. if (argc > 0)
  44. {
  45. int err = -1;
  46. uint32_t cmd = bx::hashMurmur2A(argv[0], (uint32_t)strlen(argv[0]) );
  47. CmdLookup::iterator it = m_lookup.find(cmd);
  48. if (it != m_lookup.end() )
  49. {
  50. Func& fn = it->second;
  51. err = fn.m_fn(this, fn.m_userData, argc, argv);
  52. }
  53. switch (err)
  54. {
  55. case 0:
  56. break;
  57. case -1:
  58. {
  59. stl::string tmp(_cmd, next-_cmd - (*next == '\0' ? 0 : 1) );
  60. DBG("Command '%s' doesn't exist.", tmp.c_str() );
  61. }
  62. break;
  63. default:
  64. {
  65. stl::string tmp(_cmd, next-_cmd - (*next == '\0' ? 0 : 1) );
  66. DBG("Failed '%s' err: %d.", tmp.c_str(), err);
  67. }
  68. break;
  69. }
  70. }
  71. }
  72. }
  73. struct Func
  74. {
  75. ConsoleFn m_fn;
  76. void* m_userData;
  77. };
  78. typedef stl::unordered_map<uint32_t, Func> CmdLookup;
  79. CmdLookup m_lookup;
  80. };
  81. static CmdContext* s_cmdContext;
  82. void cmdInit()
  83. {
  84. s_cmdContext = BX_NEW(entry::getAllocator(), CmdContext);
  85. }
  86. void cmdShutdown()
  87. {
  88. BX_DELETE(entry::getAllocator(), s_cmdContext);
  89. }
  90. void cmdAdd(const char* _name, ConsoleFn _fn, void* _userData)
  91. {
  92. s_cmdContext->add(_name, _fn, _userData);
  93. }
  94. void cmdExec(const char* _cmd)
  95. {
  96. s_cmdContext->exec(_cmd);
  97. }