cmd.cpp 2.2 KB

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