fork download
  1. #include <boost/iostreams/categories.hpp>
  2. #include <boost/iostreams/stream.hpp>
  3. #include <boost/coroutine/all.hpp>
  4.  
  5. #include <functional>
  6. #include <istream>
  7. #include <memory>
  8. #include <cwchar>
  9.  
  10. using namespace boost;
  11. using namespace std;
  12.  
  13. #include <windows.h>
  14.  
  15. typedef function<void(wchar_t)> CharHandler;
  16. CharHandler on_char;
  17. HWND main_hwnd;
  18.  
  19. template<typename F>
  20. void async_read(F f)
  21. {
  22. on_char = f;
  23. }
  24.  
  25. typedef coroutines::coroutine<void()> Coro;
  26. typedef std::shared_ptr<Coro> shared_coro;
  27.  
  28. struct DataSource
  29. {
  30. typedef wchar_t char_type;
  31. typedef iostreams::source_tag category;
  32.  
  33. Coro::caller_type &ca;
  34. const shared_coro *coro;
  35.  
  36. std::streamsize read(wchar_t* s, streamsize n)
  37. {
  38. if(n==0) return 0;
  39. auto &&sc = *coro;
  40. async_read([s, sc, this](wchar_t ch)
  41. {
  42. s[0] = ch;
  43. coro = &sc;
  44. (*sc)();
  45. });
  46. ca();
  47. return 1;
  48. }
  49. };
  50. typedef iostreams::stream<DataSource> InputStream;
  51.  
  52. void foo(wistream &client_stream)
  53. {
  54. wstring msg;
  55. do
  56. {
  57. getline(client_stream, msg);
  58. SendMessage(main_hwnd, WM_SETTEXT, 0, reinterpret_cast<LPARAM>(msg.c_str()));
  59. } while(msg != L"exit");
  60. }
  61.  
  62. void task()
  63. {
  64. auto &&coro = make_shared<Coro>();
  65. *coro = Coro([&coro](Coro::caller_type &ca)
  66. {
  67. DataSource source = {ca, &coro};
  68. InputStream client_stream(source);
  69. foo(client_stream);
  70. });
  71. }
  72.  
  73. LRESULT CALLBACK window_procedure(HWND hwnd, UINT msg, WPARAM w_param, LPARAM l_param)
  74. {
  75. switch (msg)
  76. {
  77. case WM_DESTROY:
  78. PostQuitMessage(0);
  79. return 0;
  80. case WM_SIZE:
  81. if(w_param == SIZE_MAXIMIZED)
  82. {
  83. static auto once = []{ return task(), 1; }();
  84. } break;
  85. case WM_CHAR:
  86. if(on_char)
  87. {
  88. wchar_t ch = w_param;
  89. auto handler = on_char;
  90. on_char = CharHandler();
  91. handler(ch == L'\x0D'? L'\n' : ch);
  92. } break;
  93. }
  94. return DefWindowProc(hwnd, msg, w_param, l_param);
  95. }
  96.  
  97. int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE, LPSTR, int nCmdShow)
  98. {
  99. WNDCLASS wincl = {};
  100. wincl.hInstance = hInstance;
  101. wincl.lpszClassName = TEXT("SFC");
  102. wincl.lpfnWndProc = window_procedure;
  103. RegisterClass(&wincl);
  104.  
  105. main_hwnd = CreateWindow(wincl.lpszClassName, TEXT(""), WS_OVERLAPPEDWINDOW, 0, 0, 400, 100, 0, 0, hInstance, 0);
  106. ShowWindow(main_hwnd, nCmdShow);
  107.  
  108. MSG msg;
  109. while(GetMessage(&msg, 0, 0, 0))
  110. {
  111. TranslateMessage(&msg);
  112. DispatchMessage(&msg);
  113. }
  114. }
  115.  
Not running #stdin #stdout 0s 0KB
stdin
Standard input is empty
stdout
Standard output is empty