CConsoleHandler.h 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  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. /** The color enum is used for colored text console output. */
  13. enum class EConsoleTextColor : int8_t
  14. {
  15. DEFAULT = -1,
  16. GREEN,
  17. RED,
  18. MAGENTA,
  19. YELLOW,
  20. WHITE,
  21. GRAY,
  22. TEAL = -2
  23. };
  24. /// Class which wraps the native console. It can print text based on
  25. /// the chosen color
  26. class DLL_LINKAGE CConsoleHandler
  27. {
  28. public:
  29. CConsoleHandler(const std::function<void(const std::string &, bool)> & callback);
  30. CConsoleHandler();
  31. ~CConsoleHandler();
  32. void start(); //starts listening thread
  33. template<typename T> void print(const T &data, bool addNewLine = false, EConsoleTextColor color = EConsoleTextColor::DEFAULT, bool printToStdErr = false)
  34. {
  35. TLockGuard _(smx);
  36. #ifndef VCMI_WINDOWS
  37. // with love from ffmpeg - library is trying to print some warnings from separate thread
  38. // this results in broken console on Linux. Lock stdout to print all our data at once
  39. flockfile(stdout);
  40. #endif
  41. if(color != EConsoleTextColor::DEFAULT) setColor(color);
  42. if(printToStdErr)
  43. {
  44. std::cerr << data;
  45. if(addNewLine)
  46. {
  47. std::cerr << std::endl;
  48. }
  49. else
  50. {
  51. std::cerr << std::flush;
  52. }
  53. }
  54. else
  55. {
  56. std::cout << data;
  57. if(addNewLine)
  58. {
  59. std::cout << std::endl;
  60. }
  61. else
  62. {
  63. std::cout << std::flush;
  64. }
  65. }
  66. if(color != EConsoleTextColor::DEFAULT) setColor(EConsoleTextColor::DEFAULT);
  67. #ifndef VCMI_WINDOWS
  68. funlockfile(stdout);
  69. #endif
  70. }
  71. private:
  72. #ifndef VCMI_WINDOWS
  73. using TColor = std::string;
  74. #else
  75. using TColor = int32_t;
  76. #endif
  77. int run();
  78. void end(); //kills listening thread
  79. void setColor(EConsoleTextColor color); //sets color of text appropriate for given logging level
  80. TColor defColor;
  81. TColor defErrColor;
  82. //function to be called when message is received - string: message, bool: whether call was made from in-game console
  83. std::function<void(const std::string &, bool)> cb;
  84. std::condition_variable shutdownVariable;
  85. std::mutex shutdownMutex;
  86. std::atomic<bool> shutdownPending = false;
  87. std::mutex smx;
  88. std::thread thread;
  89. };
  90. VCMI_LIB_NAMESPACE_END