CConsoleHandler.h 1.9 KB

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