cmd.cpp 2.2 KB

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