CConsoleHandler.h 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. /*
  2. * CConsoleHandler.h, part of VCMI engine
  3. *
  4. * Authors: listed in file AUTHORS in main folder
  5. *
  6. * License: GNU General Public License v2.0 or later
  7. * Full text of license available in license.txt file, in main folder
  8. *
  9. */
  10. #pragma once
  11. VCMI_LIB_NAMESPACE_BEGIN
  12. namespace EConsoleTextColor
  13. {
  14. /** The color enum is used for colored text console output. */
  15. enum EConsoleTextColor
  16. {
  17. DEFAULT = -1,
  18. GREEN,
  19. RED,
  20. MAGENTA,
  21. YELLOW,
  22. WHITE,
  23. GRAY,
  24. TEAL = -2
  25. };
  26. }
  27. /// Class which wraps the native console. It can print text based on
  28. /// the chosen color
  29. class DLL_LINKAGE CConsoleHandler
  30. {
  31. public:
  32. CConsoleHandler(std::function<void(const std::string &, bool)> callback);
  33. CConsoleHandler();
  34. ~CConsoleHandler();
  35. void start(); //starts listening thread
  36. template<typename T> void print(const T &data, bool addNewLine = false, EConsoleTextColor::EConsoleTextColor color = EConsoleTextColor::DEFAULT, bool printToStdErr = false)
  37. {
  38. TLockGuard _(smx);
  39. #ifndef VCMI_WINDOWS
  40. // with love from ffmpeg - library is trying to print some warnings from separate thread
  41. // this results in broken console on Linux. Lock stdout to print all our data at once
  42. flockfile(stdout);
  43. #endif
  44. if(color != EConsoleTextColor::DEFAULT) setColor(color);
  45. if(printToStdErr)
  46. {
  47. std::cerr << data;
  48. if(addNewLine)
  49. {
  50. std::cerr << std::endl;
  51. }
  52. else
  53. {
  54. std::cerr << std::flush;
  55. }
  56. }
  57. else
  58. {
  59. std::cout << data;
  60. if(addNewLine)
  61. {
  62. std::cout << std::endl;
  63. }
  64. else
  65. {
  66. std::cout << std::flush;
  67. }
  68. }
  69. if(color != EConsoleTextColor::DEFAULT) setColor(EConsoleTextColor::DEFAULT);
  70. #ifndef VCMI_WINDOWS
  71. funlockfile(stdout);
  72. #endif
  73. }
  74. private:
  75. int run();
  76. void end(); //kills listening thread
  77. void setColor(EConsoleTextColor::EConsoleTextColor color); //sets color of text appropriate for given logging level
  78. //function to be called when message is received - string: message, bool: whether call was made from in-game console
  79. std::function<void(const std::string &, bool)> cb;
  80. std::mutex smx;
  81. boost::thread thread;
  82. };
  83. VCMI_LIB_NAMESPACE_END