CConsoleHandler.h 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  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();
  33. ~CConsoleHandler();
  34. void start(); //starts listening thread
  35. template<typename T> void print(const T &data, bool addNewLine = false, EConsoleTextColor::EConsoleTextColor color = EConsoleTextColor::DEFAULT, bool printToStdErr = false)
  36. {
  37. TLockGuard _(smx);
  38. #ifndef VCMI_WINDOWS
  39. // with love from ffmpeg - library is trying to print some warnings from separate thread
  40. // this results in broken console on Linux. Lock stdout to print all our data at once
  41. flockfile(stdout);
  42. #endif
  43. if(color != EConsoleTextColor::DEFAULT) setColor(color);
  44. if(printToStdErr)
  45. {
  46. std::cerr << data;
  47. if(addNewLine)
  48. {
  49. std::cerr << std::endl;
  50. }
  51. else
  52. {
  53. std::cerr << std::flush;
  54. }
  55. }
  56. else
  57. {
  58. std::cout << data;
  59. if(addNewLine)
  60. {
  61. std::cout << std::endl;
  62. }
  63. else
  64. {
  65. std::cout << std::flush;
  66. }
  67. }
  68. if(color != EConsoleTextColor::DEFAULT) setColor(EConsoleTextColor::DEFAULT);
  69. #ifndef VCMI_WINDOWS
  70. funlockfile(stdout);
  71. #endif
  72. }
  73. std::function<void(const std::string &, bool)> *cb; //function to be called when message is received
  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. /// FIXME: Implement CConsoleHandler as singleton, move some logic into CLogConsoleTarget, etc... needs to be disussed:)
  79. /// Without static, application will crash complaining about mutex deleted. In short: CConsoleHandler gets deleted before
  80. /// the logging system.
  81. static boost::mutex smx;
  82. boost::thread * thread;
  83. };
  84. extern DLL_LINKAGE CConsoleHandler * console;
  85. VCMI_LIB_NAMESPACE_END