-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbkemultaperecorder.cpp
More file actions
267 lines (251 loc) · 8.96 KB
/
bkemultaperecorder.cpp
File metadata and controls
267 lines (251 loc) · 8.96 KB
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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
#include "stdafx.h"
#include "bkemultaperecorder.h"
#include "bkemul.h"
#include "resource.h"
#include <fstream>
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
using namespace bkemul;
using namespace std;
// --------------------------------------------------------------
// ---------- BKEmulTapeRecorder
// --------------------------------------------------------------
BKEmulTapeRecorder::BKEmulTapeRecorder():
findFile( NULL ),
last_file( false )
{
}
BKEmulTapeRecorder::~BKEmulTapeRecorder()
{
closeFind();
}
void BKEmulTapeRecorder::reset()
{
}
void BKEmulTapeRecorder::closeFind()
{
if ( findFile ) {
findFile->Close();
delete findFile;
findFile = NULL;
}
}
void BKEmulTapeRecorder::copyToBK( const char* from, WORD to, WORD size ) const
{
for ( WORD i = 0; i < size; i++ ) {
emul.setMemoryByte( to + i, *(from + i) );
}
}
void BKEmulTapeRecorder::copyFromBK( WORD from, char* to, WORD size ) const
{
for ( WORD i = 0; i < size; i++ ) {
*to++ = emul.getMemoryByte( from + i );
}
}
bool BKEmulTapeRecorder::isFileExists( const string& fileName )
{
CFileFind finder;
return finder.FindFile( fileName.c_str() ) ? true : false;
}
void BKEmulTapeRecorder::doEMT36()
{
WORD memory = emul.cpu.R1();
BYTE command = emul.getMemoryByte( memory );
// Инициализируем ответ значением останова по команде оператора
BYTE answer = 4;
WORD address = emul.getMemoryWord( memory+2 );
WORD length = emul.getMemoryWord( memory+4 );
char name[17];
copyFromBK( memory + 6, name, 16 );
name[16] = 0;
string file_name = name;
char* buf = NULL;
try {
switch ( command ) {
// Останов двигателя магнитофона
// Операция завершена без ошибок
case 0: answer = 0; break;
// Пуск двигателя магнитофона
// Операция завершена без ошибок
case 1: answer = 0; break;
// Запись файла
case 2: {
bool canSave = true;
if ( isFileExists( file_name ) ) {
emul.setPause( true );
std::string name = file_name;
trim( name );
canSave = AfxMessageBox( format( IDS_FILEEXISTS, name.c_str() ).c_str(), MB_ICONQUESTION | MB_YESNO ) == IDYES;
emul.setPause( false );
}
if ( canSave ) {
ofstream file( file_name.c_str(), ios_base::out | ios_base::binary );
// Записываем адрес и длину файла в поток
file.write( reinterpret_cast<char*>(&address), 2 );
file.write( reinterpret_cast<char*>(&length), 2 );
// Записываем побайтно файл из памяти БК в выделенную память со всеми проверками
buf = new char[ length ];
copyFromBK( address, buf, length );
// Переписываем файл в поток
file.write( buf, length );
delete buf;
buf = NULL;
// Операция завершена без ошибок
answer = 0;
} else {
// Останов по команде оператора
answer = 4;
}
break;
}
// Фиктивное чтение файла (переходит в раздел чтения файла)
case 4: file_name = "";
// Чтение файла
case 3: {
if ( isFileExists( file_name ) ) {
ifstream file( file_name.c_str(), ios_base::in | ios_base::binary );
WORD load_address;
WORD load_length;
file.read( reinterpret_cast<char*>(&load_address), 2 );
file.read( reinterpret_cast<char*>(&load_length), 2 );
// Адрес текущего массива
emul.setMemoryWord( memory + 22, load_address );
// Длина текущего массива
emul.setMemoryWord( memory + 24, load_length );
// Имя текущего массива
int len = 16 - file_name.length();
for ( int i = 0; i < len; i++ ) {
file_name += ' ';
}
copyToBK( file_name.c_str(), memory + 26, 16 );
// Если задан нулевой адрес назначения, то читаем в адрес, прочитанный из файла
if ( address == 0 ) {
address = load_address;
}
length = load_length;
// Читаем из потока в выделенную память
buf = new char[ length ];
file.read( buf, length );
// Копируем побайтно в память БК со всеми проверками
copyToBK( buf, address, length );
// Выполняем действия стандарного обработчика EMT36, которые он
// выполняет после чтения массива
// Адрес начала массива
emul.setMemoryWord( 0264, load_address );
// Длина массива
emul.setMemoryWord( 0266, load_length );
// Операция завершена без ошибок
answer = 0;
delete buf;
buf = NULL;
} else {
// Не найден файл с таким именем
answer = 1;
// Открываем указатель на первый найденный файл в директории,
// если он уже не открыт (этот механиз похож на callback-функцию, т.к.
// вызов этого обработчика происходит из системного монитора после
// каждого найденного имени)
if ( last_file ) {
last_file = false;
// Все файлы перечислены, необходимо остановить вывод имен
closeFind();
// Останов по команде оператора
answer = 4;
} else {
bool canFind = true;
if ( !findFile ) {
// Настраиваем поиск
findFile = new CFileFind;
char dir[ MAX_PATH + 1 ];
::GetCurrentDirectory( MAX_PATH, dir );
dir[ MAX_PATH ] = 0;
string mask = dir;
string::size_type pos = mask.find_last_of( '\\' );
if ( pos == string::npos ) {
pos = mask.find_last_of( '/' );
}
if ( pos != mask.length() - 1 ) {
mask += '\\';
}
trimRight( file_name );
mask += file_name + "*.*";
canFind = findFile->FindFile( mask.c_str() ) ? true : false;
}
if ( canFind ) {
// Находим первый/следующий файл в директории
if ( findFile->FindNextFile() ) {
bool flag = true;
while ( flag && ( findFile->IsDots() || findFile->IsDirectory() ) ) {
flag = findFile->FindNextFile() ? true : false;
}
if ( !findFile->IsDots() && !findFile->IsDirectory() ) {
file_name = findFile->GetFileName();
} else {
// Все файлы перечислены, необходимо остановить вывод имен
closeFind();
// Останов по команде оператора
answer = 4;
}
} else {
// Находим последний файл в директрии
if ( !findFile->IsDots() && !findFile->IsDirectory() ) {
file_name = findFile->GetFileName();
last_file = true;
} else {
// Все файлы перечислены, необходимо остановить вывод имен
closeFind();
// Останов по команде оператора
answer = 4;
}
}
} else {
// Не можем найти первый файл
closeFind();
// Останов по команде оператора
answer = 4;
}
}
// Передача имени найденного файла
if ( answer == 1 ) {
// Имя текущего массива
int len = 16 - file_name.length();
for ( int i = 0; i < len; i++ ) {
file_name += ' ';
}
copyToBK( file_name.c_str(), memory + 26, 16 );
ifstream file( file_name.c_str(), ios_base::in | ios_base::binary );
WORD load_address;
WORD load_length;
file.read( reinterpret_cast<char*>(&load_address), 2 );
file.read( reinterpret_cast<char*>(&load_length), 2 );
// Адрес текущего массива
emul.setMemoryWord( memory + 22, load_address );
// Длина текущего массива
emul.setMemoryWord( memory + 24, load_length );
}
}
break;
}
}
// Общая часть для всех режимов
// Байт ответа
emul.setMemoryByte( memory + 1, answer );
// Дубль байта ответа
emul.setMemoryByte( 0301, answer );
emul.cpu.BK_doRTI();
} catch ( BKEmul::BKMemoryAccessError& /*e*/ ) {
// Ошибка доступа к памяти БК (грузили в ПЗУ)
answer = 4;
emul.setMemoryByte( memory + 1, answer );
emul.setMemoryByte( 0301, answer );
emul.cpu.BK_doRTI();
if ( buf ) {
delete buf;
buf = NULL;
}
throw;
}
}