This repository has been archived by the owner on Dec 13, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 21
/
RunController.cpp
423 lines (360 loc) · 10.2 KB
/
RunController.cpp
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
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
/*
Copyright (C) 2010 Casey Link <[email protected]>
This library is free software; you can redistribute it and/or modify it
under the terms of the GNU Library General Public License as published by
the Free Software Foundation; either version 3 of the License, or (at your
option) any later version.
This library is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public
License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301, USA.
*/
#include "RunController.h"
#include "NPietObserver.h"
#include <QSocketNotifier>
#include <QDebug>
#include <QTemporaryFile>
#include <QThread>
#include <stdio.h>
#include <iostream>
#ifndef Q_WS_WIN
#include <unistd.h>
#include <fcntl.h>
#endif
extern "C"
{
#include "npiet/npiet.h"
#include "npiet/npiet_utils.h"
}
RunController::RunController(): QObject( 0 ), mPrepared( false ), mStdOut( 0 ), mObserver( 0 ), mAbort( false ), mExecuting( false ), mDebugging( false ), mTimer( 0 )
{
#ifndef Q_WS_WIN
mNotifier = 0;
#else
mOutputTimer = 0;
#endif
}
RunController::~RunController()
{
qDebug() << "~RunController";
mMutex.lock();
mAbort = true;
qDebug() << "waking";
mWaitCond.wakeOne();
mMutex.unlock();
thread()->wait();
}
void RunController::slotThreadStarted()
{
mObserver = new NPietObserver( this );
connect( mObserver, SIGNAL( stepped( trace_step* ) ), this, SLOT( slotStepped( trace_step* ) ) );
connect( mObserver, SIGNAL( actionChanged( trace_action* ) ), this, SLOT( slotAction( trace_action* ) ) );
}
bool RunController::initialize( const QImage &source )
{
if ( !mTimer )
mTimer = new QTimer( this );
connect( mTimer, SIGNAL( timeout() ), this, SLOT( tick() ) );
#ifdef Q_WS_WIN
if ( !mOutputTimer )
mOutputTimer = new QTimer( this );
connect( mOutputTimer, SIGNAL( timeout() ), this, SLOT( win32OutputTimeout() ) );
#endif
mSource = source;
captureStdout();
if ( prepare() ) {
piet_init();
return true;
}
return false;
}
void RunController::execute()
{
mExecuting = true;
if ( !mPrepared )
return;
mTimer->start( 0 );
}
void RunController::tick()
{
QMutexLocker locker( &mMutex );
// if( mAbort ) {
// abort = true;
// }
if ( !mAbort && piet_step() < 0 )
mAbort = true;
if ( mAbort ) {
mTimer->stop();
finish();
mAbort = false;
emit stopped();
return;
}
}
void RunController::step()
{
if ( !mPrepared )
return;
int res = piet_step();
}
void RunController::abort()
{
qDebug() << "abort!";
QMutexLocker locker( &mMutex );
stop();
}
void RunController::stop()
{
qDebug() << "stop!";
if ( mExecuting ) {
mAbort = true;
mPrepared = false;
mWaitCond.wakeOne();
} else if ( mDebugging ) {
// TODO reset npiets internal state?
finish();
emit stopped();
}
}
bool RunController::runSource( const QImage& source )
{
mMutex.lock();
stop();
mExecuting = true;
mMutex.unlock();
if ( initialize( source ) ) {
execute();
return true;
}
abort();
mMutex.lock();
finish();
mMutex.unlock();
return false;
}
void RunController::debugSource( const QImage& source )
{
mMutex.lock();
stop();
mDebugging = true;
mMutex.unlock();
if ( !initialize( source ) )
abort();
emit debugStarted();
}
void RunController::pixelChanged( int x, int y, QRgb color )
{
if ( mPrepared ) {
mSource.setPixel( x, y, color );
int col = (( qRed( color ) * 256 + qGreen( color ) ) * 256 ) + qBlue( color );
int col_idx = get_color_idx( col );
if ( col_idx < 0 ) {
/* set to black or white: */
col_idx = ( /*unknown_color*/1 == 0 ? c_black : c_white );
}
set_cell( x, y, col_idx );
}
}
void RunController::finish()
{
mTimer->stop();
mExecuting = false;
mDebugging = false;
mPrepared = false;
#ifndef Q_WS_WIN
if ( mNotifier == 0 ) return;
std::cout.flush(); // flush standard output cout file descriptor
::fflush( NULL ); // flush all file buffers
::fsync( 1 ); // syncronize standard output buffers -- may be unnessessery
stdoutReadyRead(); // process whatever data is left there
// Restore original state
delete mNotifier;
delete mStdOut;
mNotifier = 0;
mStdOut = 0;
::dup2( mOrigFdCopy, mOrigFd ); // restore the output descriptor
::close( mOrigFdCopy ); // close the copy as it's redundant now
::close( mPipeFd[0] ); // close the reading end of the pipe
#else
win32OutputTimeout();
mOutputTimer->stop();
::SetStdHandle( STD_OUTPUT_HANDLE, mOldStdoutHandle );
::CloseHandle( mPipeRead );
::CloseHandle( mPipeWrite );
::CloseHandle( mOldStdoutHandle );
#endif
}
bool RunController::prepare()
{
// image = mSource.convertToFormat( QImage::Format_RGB32 );
QRgb* cells = ( QRgb* ) mSource.bits();
set_image( mSource.width(), mSource.height() );
for ( int i = 0; i < mSource.height(); ++i ) {
QRgb* lineptr = ( QRgb* ) mSource.scanLine( i );
for ( int j = 0; j < mSource.width(); ++j ) {
int r = qRed( lineptr[j] );
int g = qGreen( lineptr[j] );
int b = qBlue( lineptr[j] );
int col = (( r * 256 + g ) * 256 ) + b;
int col_idx = get_color_idx( col );
if ( col_idx < 0 ) {
/* set to black or white: */
col_idx = ( /*unknown_color*/1 == 0 ? c_black : c_white );
}
set_cell( j, i, col_idx );
}
}
mPrepared = true;
return mPrepared;
}
void RunController::stdoutReadyRead()
{
emit newOutput( mStdOut->readAll() );
}
void RunController::slotAction( trace_action* act )
{
if ( mDebugging )
emit actionChanged( act );
}
void RunController::slotStepped( trace_step* step )
{
if ( mDebugging )
emit stepped( step );
}
char RunController::getChar()
{
// QMutexLocker locker( &mMutex );
emit waitingForChar();
mWaitCond.wait( &mMutex );
return mChar;
}
int RunController::getInt()
{
// qDebug() << "getInt()" << "getting lock";
// QMutexLocker locker( &mMutex );
// qDebug() << "getInt()" << "got lock";
emit waitingForInt();
// qDebug() << "getInt()" << "waiting";
bool timer_running = mTimer->isActive();
if ( timer_running )
mTimer->stop();
mWaitCond.wait( &mMutex );
qDebug() << "getInt()" << "woke up!" << mInt;
if ( timer_running )
mTimer->start();
return mInt;
}
void RunController::putChar( const QChar & c )
{
qDebug() << "putChar";
QMutexLocker locker( &mMutex );
mChar = c.toAscii();
mWaitCond.wakeOne();
}
void RunController::putInt( int i )
{
QMutexLocker locker( &mMutex );
qDebug() << "putInt" << i;
mInt = i;
mWaitCond.wakeOne();
}
void RunController::win32OutputTimeout()
{
#ifdef Q_WS_WIN
//qDebug() << "win32OutputTimeout ";
DWORD dwAvail = 0;
if ( !::PeekNamedPipe( mPipeRead, NULL, 0, NULL, &dwAvail, NULL ) ) {
//qDebug() << "error";
return; // error
}
if ( !dwAvail ) {
//qDebug() << "no data avail";
return; // no data available
}
char szOutput[256];
DWORD dwRead = 0;
if ( !::ReadFile( mPipeRead, szOutput, min( 255, dwAvail ), &dwRead, NULL ) || !dwRead ) {
//qDebug() << "child dead?";
return; // error, the child might ended
}
szOutput[dwRead] = 0;
QString out( szOutput );
if ( out.length() > 0 ) {
emit newOutput( out );
qDebug() << out;
}
#endif
}
//
// Downloaded from: http://www.ibib.waw.pl/~winnie
//
// License: Public domain
//
void RunController::captureStdout()
{
/**
Capture stdout in a cross platform way (I hope).
1. Initialize pipe.
2. Dup STDOUT so we can restore it later.
3. Make the stdout descriptor a copy of pipe's write end.
4. Close write end.
5. Set flags to ensure non blocking on pipe's read end
6. Associate pipe read end with a FILE*
7. Pass the FILE* to qtextstream
8. Create a QSocketNotifier on the pipe's read end to monitor for new data
*/
#ifndef Q_WS_WIN
int rc = ::pipe( mPipeFd );
Q_ASSERT( rc >= 0 );
mOrigFd = STDOUT_FILENO;
mOrigFdCopy = ::dup( mOrigFd );
Q_ASSERT( mOrigFdCopy >= 0 );
rc = ::dup2( mPipeFd[1], mOrigFd );
Q_ASSERT( rc >= 0 );
::close( mPipeFd[1] );
rc = ::fcntl( mPipeFd[0], F_GETFL );
Q_ASSERT( rc != -1 );
rc = ::fcntl( mPipeFd[0], F_SETFL, rc | O_NONBLOCK );
Q_ASSERT( rc != -1 );
FILE * f = fdopen( mPipeFd[0], "r" );
Q_ASSERT( f != 0 );
if ( mStdOut != 0 )
delete mStdOut;
if ( mNotifier != 0 )
delete mNotifier;
mStdOut = new QTextStream( f );
mNotifier = new QSocketNotifier( mPipeFd[0], QSocketNotifier::Read );
QObject::connect( mNotifier, SIGNAL( activated( int ) ), SLOT( stdoutReadyRead() ) );
#else
// save stdout
mOldStdoutHandle = ::GetStdHandle( STD_OUTPUT_HANDLE );
if ( INVALID_HANDLE_VALUE == mOldStdoutHandle )
return;
if ( 0 == ::CreatePipe( &mPipeRead, &mPipeWrite, NULL, 0 ) )
return;
// redirect stdout, stdout now writes into the pipe
if ( 0 == ::SetStdHandle( STD_OUTPUT_HANDLE, mPipeWrite ) )
return;
// new stdout handle
HANDLE lStdHandle = ::GetStdHandle( STD_OUTPUT_HANDLE );
if ( INVALID_HANDLE_VALUE == lStdHandle )
return;
int hConHandle = ::_open_osfhandle(( intptr_t )lStdHandle, _O_TEXT );
FILE *fp = ::_fdopen( hConHandle, "w" );
if ( !fp )
return;
// replace stdout with pipe file handle
*stdout = *fp;
// unbuffered stdout
::setvbuf( stdout, NULL, _IONBF, 0 );
hConHandle = ::_open_osfhandle(( intptr_t )mPipeRead, _O_TEXT );
if ( -1 == hConHandle )
return;
mOutputTimer->start( 50 );
#endif
}
#include "RunController.moc"