CConsoleHandler.h 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  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, bool addNewLine = false, EConsoleTextColor::EConsoleTextColor color = EConsoleTextColor::DEFAULT, bool printToStdErr = false)
  35. {
  36. TLockGuard _(smx);
  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;
  46. if(addNewLine)
  47. {
  48. std::cerr << std::endl;
  49. }
  50. else
  51. {
  52. std::cerr << std::flush;
  53. }
  54. }
  55. else
  56. {
  57. std::cout << data;
  58. if(addNewLine)
  59. {
  60. std::cout << std::endl;
  61. }
  62. else
  63. {
  64. std::cout << std::flush;
  65. }
  66. }
  67. if(color != EConsoleTextColor::DEFAULT) setColor(EConsoleTextColor::DEFAULT);
  68. #ifndef _WIN32
  69. funlockfile(stdout);
  70. #endif
  71. }
  72. boost::function<void(const std::string &)> *cb; //function to be called when message is received
  73. private:
  74. int run();
  75. void end(); //kills listening thread
  76. void setColor(EConsoleTextColor::EConsoleTextColor color); //sets color of text appropriate for given logging level
  77. /// FIXME: Implement CConsoleHandler as singleton, move some logic into CLogConsoleTarget, etc... needs to be disussed:)
  78. /// Without static, application will crash complaining about mutex deleted. In short: CConsoleHandler gets deleted before
  79. /// the logging system.
  80. static boost::mutex smx;
  81. boost::thread * thread;
  82. };
  83. extern DLL_LINKAGE CConsoleHandler * console;