1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
|
// Copyright (c) 2020 Egor Tensin <Egor.Tensin@gmail.com>
// This file is part of the "winapi-common" project.
// For details, see https://github.com/egor-tensin/winapi-common.
// Distributed under the MIT License.
#pragma once
#include "command.hpp"
#include <winapi/process.hpp>
#include <boost/config.hpp>
#include <windows.h>
#include <exception>
#include <string>
#include <utility>
#include <vector>
namespace worker {
class Worker {
public:
Worker(winapi::Process&& process) : m_cmd(Command::create()), m_process(std::move(process)) {}
Worker(Worker&& other) BOOST_NOEXCEPT_OR_NOTHROW : m_cmd(std::move(other.m_cmd)),
m_process(std::move(other.m_process)) {}
Worker& operator=(Worker other) BOOST_NOEXCEPT_OR_NOTHROW {
swap(other);
return *this;
}
void swap(Worker& other) BOOST_NOEXCEPT_OR_NOTHROW {
using std::swap;
swap(m_cmd, other.m_cmd);
swap(m_process, other.m_process);
}
Worker(const Worker&) = delete;
~Worker() {
try {
if (m_process.is_running()) {
exit();
}
} catch (const std::exception&) {
}
}
HWND get_console_window() {
HWND ret = NULL;
m_cmd->get_result(Command::GET_CONSOLE_WINDOW,
[&ret](const Command::Result& result) { ret = result.console_window; });
return ret;
}
bool is_window_visible() {
bool ret = false;
m_cmd->get_result(Command::IS_WINDOW_VISIBLE, [&ret](const Command::Result& result) {
ret = result.is_window_visible;
});
return ret;
}
StdHandles get_std_handles() {
StdHandles ret;
m_cmd->get_result(Command::GET_STD_HANDLES,
[&ret](const Command::Result& result) { ret = result.std_handles; });
return ret;
}
StdHandles test_write() {
StdHandles ret;
m_cmd->get_result(Command::TEST_WRITE,
[&ret](const Command::Result& result) { ret = result.std_handles; });
return ret;
}
std::vector<std::string> read_last_lines(std::size_t numof_lines) {
std::vector<std::string> ret;
const auto set_args = [numof_lines](Command::Args& args) {
args.numof_lines = numof_lines;
};
const auto read_result = [&ret](const Command::Result& result) {
ret = result.console_buffer.extract();
};
m_cmd->get_result(Command::GET_CONSOLE_BUFFER, set_args, read_result);
return ret;
}
int exit() {
m_cmd->get_result(Command::EXIT);
m_process.wait();
return m_process.get_exit_code();
}
private:
Command::Shared m_cmd;
winapi::Process m_process;
};
inline void swap(Worker& a, Worker& b) BOOST_NOEXCEPT_OR_NOTHROW {
a.swap(b);
}
} // namespace worker
namespace std {
template <>
inline void swap(worker::Worker& a, worker::Worker& b) BOOST_NOEXCEPT_OR_NOTHROW {
a.swap(b);
}
} // namespace std
|