runplugin.cpp 22.4 KB
Newer Older
1
#include "runplugin.h"
victor's avatar
 
victor committed
2
#include "run.h"
3 4 5 6
#include "util.h"
#include "commonrun.h"
#include "consolerun.h"
#include "guirun.h"
7
#include <kumir2-libs/extensionsystem/pluginmanager.h>
8
#include <kumir2-libs/vm/vm_console_handlers.hpp>
9
#include <kumir2/actorinterface.h>
10

11 12 13 14 15
#include <QWidget>
#include <QCoreApplication>
#include <QDebug>
#include <iostream>
#include <locale.h>
16

17 18 19 20
#ifdef Q_OS_LINUX
#include <unistd.h>
#endif

Alexander A. Maly's avatar
Alexander A. Maly committed
21 22
namespace KumirCodeRun
{
23
using VM::Variable;
victor's avatar
 
victor committed
24

Victor Yacovlev's avatar
Victor Yacovlev committed
25
struct CommonFunctors {
Alexander A. Maly's avatar
Alexander A. Maly committed
26 27 28 29
	Common::ExternalModuleCallFunctor call;
	Common::CustomTypeFromStringFunctor fromString;
	Common::CustomTypeToStringFunctor toString;
	Common::ExternalModuleResetFunctor reset;
30 31 32
};

struct ConsoleFunctors {
Alexander A. Maly's avatar
Alexander A. Maly committed
33 34 35 36 37 38
	Console::ExternalModuleResetFunctor reset;
	Console::ExternalModuleLoadFunctor load;
	VM::Console::InputFunctor input;
	VM::Console::OutputFunctor output;
	VM::Console::GetMainArgumentFunctor getMainArgument;
	VM::Console::ReturnMainValueFunctor returnMainValue;
39 40 41
};

struct GuiFunctors {
Alexander A. Maly's avatar
Alexander A. Maly committed
42 43 44 45 46 47 48 49
	Gui::ExternalModuleResetFunctor reset;
	Gui::ExternalModuleLoadFunctor load;
	Gui::InputFunctor input;
	Gui::OutputFunctor output;
	Gui::GetMainArgumentFunctor getMainArgument;
	Gui::ReturnMainValueFunctor returnMainValue;
	Gui::PauseFunctor pause;
	Gui::DelayFunctor delay;
50 51 52
};


Alexander A. Maly's avatar
Alexander A. Maly committed
53 54 55 56 57 58 59 60
KumirRunPlugin::KumirRunPlugin() :
	ExtensionSystem::KPlugin(),
	pRun_(new Run(this)),
	common_(nullptr),
	console_(nullptr),
	gui_(nullptr),
	simulatedInputBuffer_(nullptr),
	simulatedOutputBuffer_(nullptr)
victor's avatar
 
victor committed
61
{
Alexander A. Maly's avatar
Alexander A. Maly committed
62
	connect(this, SIGNAL(finishInput(QVariantList)), pRun_, SIGNAL(finishInput(QVariantList)));
Victor Yacovlev's avatar
Victor Yacovlev committed
63

Alexander A. Maly's avatar
Alexander A. Maly committed
64 65 66 67
	done_ = true;
	connect(pRun_, SIGNAL(output(QString)), this, SIGNAL(outputRequest(QString)));
	connect(pRun_, SIGNAL(input(QString)), this, SIGNAL(inputRequest(QString)));
	connect(pRun_, SIGNAL(finished()), this, SLOT(handleThreadFinished()));
Victor Yacovlev's avatar
Victor Yacovlev committed
68

Alexander A. Maly's avatar
Alexander A. Maly committed
69 70
	// The signal userTerminated() has the same effect like QThread::finished()
	connect(pRun_, SIGNAL(userTerminated()), this, SLOT(handleThreadFinished()));
Victor Yacovlev's avatar
Victor Yacovlev committed
71

Alexander A. Maly's avatar
Alexander A. Maly committed
72 73 74 75 76 77 78 79
	connect(pRun_, SIGNAL(lineChanged(int, quint32, quint32)), this, SIGNAL(lineChanged(int, quint32, quint32)));
	connect(pRun_, SIGNAL(updateStepsCounter(quint64)), this, SIGNAL(updateStepsCounter(quint64)));
	connect(pRun_, SIGNAL(marginText(int, QString)), this, SIGNAL(marginText(int, QString)));
	connect(pRun_, SIGNAL(clearMarginRequest(int, int)), this, SIGNAL(clearMargin(int, int)));
	connect(pRun_, SIGNAL(marginTextReplace(int, QString, bool)),
		this, SIGNAL(replaceMarginText(int, QString, bool)));
	connect(pRun_, SIGNAL(breakpointHit(QString, int)), this, SLOT(handleBreakpointHit(QString, int)));
	onlyOneTryToInput_ = false;
victor's avatar
 
victor committed
80 81
}

82
unsigned long int KumirRunPlugin::stepsCounted() const
83
{
Alexander A. Maly's avatar
Alexander A. Maly committed
84
	return pRun_->vm->stepsDone();
85 86
}

87
int KumirRunPlugin::currentLineNo() const
victor's avatar
 
victor committed
88
{
Alexander A. Maly's avatar
Alexander A. Maly committed
89
	return pRun_->effectiveLineNo();
victor's avatar
 
victor committed
90 91
}

Alexander A. Maly's avatar
Alexander A. Maly committed
92
QPair<quint32, quint32> KumirRunPlugin::currentColumn() const
93
{
Alexander A. Maly's avatar
Alexander A. Maly committed
94
	return QPair<quint32, quint32>(pRun_->vm->effectiveColumn().first, pRun_->vm->effectiveColumn().second);
95 96
}

97
bool KumirRunPlugin::loadProgram(const RunnableProgram &program)
victor's avatar
 
victor committed
98
{
Alexander A. Maly's avatar
Alexander A. Maly committed
99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114
	const QString programFileName = program.sourceFileName.isEmpty()
		? program.executableFileName : program.sourceFileName;
	bool ok = false;
	std::list<char> buffer;
	for (int i = 0; i < program.executableData.size(); i++) {
		buffer.push_back(program.executableData[i]);
	}
	ok = pRun_->loadProgramFromBinaryBuffer(buffer, programFileName.toStdWString());
	if (!ok) {
		return ok;
	}
	const QString programDirName = program.sourceFileName.isEmpty()
		? "" : QFileInfo(programFileName).absoluteDir().absolutePath();
	pRun_->setProgramDirectory(programDirName);
	pRun_->programLoaded = ok;
	return ok;
victor's avatar
 
victor committed
115 116
}

117
QString KumirRunPlugin::error() const
victor's avatar
 
victor committed
118
{
Alexander A. Maly's avatar
Alexander A. Maly committed
119
	return pRun_->error();
victor's avatar
 
victor committed
120 121
}

Alexander A. Maly's avatar
Alexander A. Maly committed
122
QMap<QString, QVariant> KumirRunPlugin::getScalarLocalValues(int frameNo) const
123
{
Alexander A. Maly's avatar
Alexander A. Maly committed
124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141
	pRun_->lockVMMutex();
	QMap<QString, QVariant> result;
	const std::vector<Variable> &locals = pRun_->vm->getLocals(frameNo);
	for (int i = 0; i < (int)locals.size(); i++) {
		const Variable &var = locals.at(i);
		if (var.dimension() == 0) {
			const QString varName = QString::fromStdWString(var.myName());
			QVariant value;
			if (var.isValid()) {
				value = QString::fromStdWString(var.toString());
			} else {
				value = QVariant::Invalid;
			}
			result.insert(varName, value);
		}
	}
	pRun_->unlockVMMutex();
	return result;
142 143
}

144
QVariant KumirRunPlugin::valueStackTopItem() const
145
{
Alexander A. Maly's avatar
Alexander A. Maly committed
146
	return pRun_->valueStackTopItem();
147 148
}

Alexander A. Maly's avatar
Alexander A. Maly committed
149
QMap<QString, QVariant> KumirRunPlugin::getScalarGlobalValues(const QString &moduleName) const
150
{
Alexander A. Maly's avatar
Alexander A. Maly committed
151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168
	pRun_->lockVMMutex();
	QMap<QString, QVariant> result;
	const std::vector<Variable> &locals = pRun_->vm->getGlobals(moduleName.toStdWString());
	for (int i = 0; i < (int)locals.size(); i++) {
		const Variable &var = locals.at(i);
		if (var.dimension() == 0) {
			const QString varName = QString::fromStdWString(var.myName());
			QVariant value;
			if (var.isValid()) {
				value = QString::fromStdWString(var.toString());
			} else {
				value = QVariant::Invalid;
			}
			result.insert(varName, value);
		}
	}
	pRun_->unlockVMMutex();
	return result;
169 170 171
}

QVariantList getTableValues(
Alexander A. Maly's avatar
Alexander A. Maly committed
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
	const Variable &var,
	int dimension,
	QList< QPair<int, int> > ranges,
	int &counter,
	const int maxCount,
	bool &complete
)
{
	int bounds[7];
	var.getEffectiveBounds(bounds);
	QVariantList result;
	if (ranges.size() < dimension) {
		QPair<int, int> maxRange;
		maxRange.first  = bounds[2 * (3 - dimension)];
		maxRange.second = bounds[2 * (3 - dimension) + 1];
		ranges.push_back(maxRange);
	}
	if (dimension == 1) {
		const QPair<int, int> xrange = ranges[0];
		QVariantList &X = result;
		const int xs = xrange.first;
		const int xe = xrange.second;
		for (int x = xs; x <= xe; x++) {
			const QVariant Xvalue = var.hasValue(x)
				? QVariant(QString::fromStdWString(var.value(x).toString()))
				: QVariant(QVariant::Invalid);
			X.push_back(Xvalue);
			counter += 1;
			if (maxCount != -1 && counter >= maxCount) {
				complete = complete && x == xe;
				break;
			}
		}
	} else if (dimension == 2) {
		const QPair<int, int> yrange = ranges[0];
		const QPair<int, int> xrange = ranges[1];
		QVariantList &Y = result;
		const int ys = yrange.first;
		const int ye = yrange.second;
		for (int y = ys; y <= ye; y++) {
			QVariantList Yvalue;
			QVariantList &X = Yvalue;
			const int xs = xrange.first;
			const int xe = xrange.second;
			for (int x = xs; x <= xe; x++) {
				const QVariant Xvalue = var.hasValue(y, x)
					? QVariant(QString::fromStdWString(var.value(y, x).toString()))
					: QVariant(QVariant::Invalid);
				X.push_back(Xvalue);
				counter += 1;
				if (maxCount != -1 && counter >= maxCount) {
					complete = complete && x == xe;
					break;
				}
			}
			Y.push_back(Yvalue);
			if (maxCount != -1 && counter >= maxCount) {
				complete = complete && y == ye;
				break;
			}
		}
	} else if (dimension == 3) {
		const QPair<int, int> zrange = ranges[0];
		const QPair<int, int> yrange = ranges[1];
		const QPair<int, int> xrange = ranges[2];
		QVariantList &Z = result;
		const int zs = zrange.first;
		const int ze = zrange.second;
		for (int z = zs; z <= ze; z++) {
			QVariantList Zvalue;
			QVariantList &Y = Zvalue;
			const int ys = yrange.first;
			const int ye = yrange.second;
			for (int y = ys; y <= ye; y++) {
				QVariantList Yvalue;
				QVariantList &X = Yvalue;
				const int xs = xrange.first;
				const int xe = xrange.second;
				for (int x = xs; x <= xe; x++) {
					const QVariant Xvalue = var.hasValue(z, y, x)
						? QVariant(QString::fromStdWString(var.value(z, y, x).toString()))
						: QVariant(QVariant::Invalid);
					X.push_back(Xvalue);
					counter += 1;
					if (maxCount != -1 && counter >= maxCount) {
						complete = complete && x == xe;
						break;
					}
				}
				Y.push_back(Yvalue);
				if (maxCount != -1 && counter >= maxCount) {
					complete = complete && y == ye;
					break;
				}
			}
			Z.push_back(Zvalue);
			if (maxCount != -1 && counter >= maxCount) {
				complete = complete && z == ze;
				break;
			}
		}
	}
	return result;
275 276
}

277
QVariantList KumirRunPlugin::getLocalTableValues(
Alexander A. Maly's avatar
Alexander A. Maly committed
278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298
	int frameNo,
	int maxCount,
	const QString &name,
	const QList<QPair<int, int> > &ranges,
	bool &complete
) const
{
	QVariantList result;
	int counter = 0;
	pRun_->lockVMMutex();
	const std::vector<Variable> &locals = pRun_->vm->getLocals(frameNo);
	for (int i = 0; i < (int)locals.size(); i++) {
		const Variable &var = locals.at(i);
		if (var.dimension() > 0 && var.myName() == name.toStdWString()) {
			complete = true;
			result = getTableValues(var, var.dimension(), ranges, counter, maxCount, complete);
			break;
		}
	}
	pRun_->unlockVMMutex();
	return result;
299 300
}

301
QVariant KumirRunPlugin::getLocalTableValue(
Alexander A. Maly's avatar
Alexander A. Maly committed
302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325
	int frameNo,
	const QString &name,
	const QList<int> &indeces
) const
{
	QVariant result;
	int kIndeces[4];
	kIndeces[3] = indeces.size();
	for (int i = 0; i < indeces.size(); i++) {
		kIndeces[i] = indeces[i];
	}
	pRun_->lockVMMutex();
	const std::vector<Variable> &locals = pRun_->vm->getLocals(frameNo);
	for (int i = 0; i < (int)locals.size(); i++) {
		const Variable &var = locals.at(i);
		if (var.dimension() > 0 && var.myName() == name.toStdWString()) {
			if (var.hasValue(kIndeces)) {
				result = QString::fromStdWString(var.toString(kIndeces));
			}
			break;
		}
	}
	pRun_->unlockVMMutex();
	return result;
326 327
}

328
QVariantList KumirRunPlugin::getGlobalTableValues(
Alexander A. Maly's avatar
Alexander A. Maly committed
329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349
	const QString &moduleName,
	int maxCount,
	const QString &name,
	const QList<QPair<int, int> > &ranges,
	bool &complete
) const
{
	QVariantList result;
	int counter = 0;
	pRun_->lockVMMutex();
	const std::vector<Variable> &globals = pRun_->vm->getGlobals(moduleName.toStdWString());
	for (int i = 0; i < (int)globals.size(); i++) {
		const Variable &var = globals.at(i);
		if (var.dimension() > 0 && var.myName() == name.toStdWString()) {
			complete = true;
			result = getTableValues(var, var.dimension(), ranges, counter, maxCount, complete);
			break;
		}
	}
	pRun_->unlockVMMutex();
	return result;
350 351
}

352
QVariant KumirRunPlugin::getGlobalTableValue(
Alexander A. Maly's avatar
Alexander A. Maly committed
353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376
	const QString &moduleName,
	const QString &name,
	const QList<int> &indeces
) const
{
	QVariant result;
	int kIndeces[4];
	kIndeces[3] = indeces.size();
	for (int i = 0; i < indeces.size(); i++) {
		kIndeces[i] = indeces[i];
	}
	pRun_->lockVMMutex();
	const std::vector<Variable> &globals = pRun_->vm->getGlobals(moduleName.toStdWString());
	for (int i = 0; i < (int)globals.size(); i++) {
		const Variable &var = globals.at(i);
		if (var.dimension() > 0 && var.myName() == name.toStdWString()) {
			if (var.hasValue(kIndeces)) {
				result = QString::fromStdWString(var.toString(kIndeces));
			}
			break;
		}
	}
	pRun_->unlockVMMutex();
	return result;
victor's avatar
 
victor committed
377 378
}

379 380


381
void KumirRunPlugin::runContinuous()
victor's avatar
 
victor committed
382
{
Alexander A. Maly's avatar
Alexander A. Maly committed
383 384 385 386 387 388
	if (done_) {
		pRun_->setEntryPointToMain();
		pRun_->reset();
		done_ = false;
	}
	pRun_->runContinuous();
victor's avatar
 
victor committed
389 390
}

391
void KumirRunPlugin::runBlind()
victor's avatar
 
victor committed
392
{
Alexander A. Maly's avatar
Alexander A. Maly committed
393 394 395 396 397 398
	if (done_) {
		pRun_->setEntryPointToMain();
		pRun_->reset();
		done_ = false;
	}
	pRun_->runBlind();
victor's avatar
 
victor committed
399 400
}

401
void KumirRunPlugin::runStepInto()
victor's avatar
 
victor committed
402
{
Alexander A. Maly's avatar
Alexander A. Maly committed
403
	pRun_->runStepIn();
victor's avatar
 
victor committed
404 405
}

Victor Yacovlev's avatar
FS#1287  
Victor Yacovlev committed
406
void KumirRunPlugin::runToEnd()
victor's avatar
 
victor committed
407
{
Alexander A. Maly's avatar
Alexander A. Maly committed
408
	pRun_->runToEnd();
victor's avatar
 
victor committed
409 410
}

411
void KumirRunPlugin::runStepOver()
victor's avatar
 
victor committed
412
{
Alexander A. Maly's avatar
Alexander A. Maly committed
413 414 415 416 417 418
	if (done_) {
		pRun_->setEntryPointToMain();
		pRun_->reset();
		done_ = false;
	}
	pRun_->runStepOver();
victor's avatar
 
victor committed
419 420
}

421
void KumirRunPlugin::runTesting()
victor's avatar
 
victor committed
422
{
Alexander A. Maly's avatar
Alexander A. Maly committed
423 424 425 426 427 428 429 430 431 432 433 434
	if (done_) {
		pRun_->setEntryPointToTest();
		pRun_->reset();
		if (simulatedInputBuffer_) {
			pRun_->vm->setConsoleInputBuffer(simulatedInputBuffer_);
		}
		if (simulatedOutputBuffer_) {
			pRun_->vm->setConsoleOutputBuffer(simulatedOutputBuffer_);
		}
		done_ = false;
	}
	pRun_->runBlind();
victor's avatar
 
victor committed
435 436
}

437
bool KumirRunPlugin::isTestingRun() const
Victor Yacovlev's avatar
Victor Yacovlev committed
438
{
Alexander A. Maly's avatar
Alexander A. Maly committed
439
	return pRun_->isTestingRun();
Victor Yacovlev's avatar
Victor Yacovlev committed
440 441
}

442
void KumirRunPlugin::terminate()
victor's avatar
 
victor committed
443
{
Alexander A. Maly's avatar
Alexander A. Maly committed
444 445 446 447 448
	common_->call.terminate();
	if (gui_) {
		gui_->delay.stop();
	}
	pRun_->stop();
victor's avatar
 
victor committed
449 450
}

451 452
void KumirRunPlugin::removeAllBreakpoints()
{
Alexander A. Maly's avatar
Alexander A. Maly committed
453
	pRun_->removeAllBreakpoints();
454 455 456 457
}

void KumirRunPlugin::insertOrChangeBreakpoint(bool enabled, const QString &fileName, quint32 lineNo, quint32 ignoreCount, const QString &condition)
{
Alexander A. Maly's avatar
Alexander A. Maly committed
458
	pRun_->insertOrChangeBreakpoint(enabled, fileName, lineNo, ignoreCount, condition);
459 460
}

Victor Yacovlev's avatar
Victor Yacovlev committed
461 462
void KumirRunPlugin::insertSingleHitBreakpoint(const QString &fileName, quint32 lineNo)
{
Alexander A. Maly's avatar
Alexander A. Maly committed
463
	pRun_->insertSingleHitBreakpoint(fileName, lineNo);
Victor Yacovlev's avatar
Victor Yacovlev committed
464 465
}

466 467
void KumirRunPlugin::removeBreakpoint(const QString &fileName, quint32 lineNo)
{
Alexander A. Maly's avatar
Alexander A. Maly committed
468
	pRun_->removeBreakpoint(fileName, lineNo);
469 470
}

471 472
void KumirRunPlugin::createPluginSpec()
{
Alexander A. Maly's avatar
Alexander A. Maly committed
473 474 475
	_pluginSpec.name = "KumirCodeRun";
	_pluginSpec.gui = false;
	_pluginSpec.provides.append("Runner");
476 477
}

478 479
void KumirRunPlugin::terminateAndWaitForStopped()
{
Alexander A. Maly's avatar
Alexander A. Maly committed
480 481 482 483
	if (pRun_->isRunning()) {
		terminate();
	}
	pRun_->wait();
484
#ifdef Q_OS_LINUX
Alexander A. Maly's avatar
Alexander A. Maly committed
485 486 487 488
	bool gui = getenv("DISPLAY") != 0;
	if (gui) {
		usleep(50000);
	}
489
#endif
490 491
}

victor's avatar
 
victor committed
492

493
void KumirRunPlugin::handleThreadFinished()
victor's avatar
 
victor committed
494
{
Alexander A. Maly's avatar
Alexander A. Maly committed
495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512
	if (simulatedInputBuffer_) {
		delete simulatedInputBuffer_;
		simulatedInputBuffer_ = 0;
	}
	pRun_->vm->setConsoleInputBuffer(nullptr);
	pRun_->vm->setConsoleOutputBuffer(nullptr);
	if (pRun_->error().length() > 0) {
		done_ = true;
		emit stopped(Shared::RunInterface::SR_Error);
	} else if (pRun_->hasMoreInstructions() && pRun_->stopped()) {
		done_ = true;
		emit stopped(Shared::RunInterface::SR_UserTerminated);
	} else if (pRun_->hasMoreInstructions()) {
		emit stopped(Shared::RunInterface::SR_UserInteraction);
	} else {
		done_ = true;
		emit stopped(Shared::RunInterface::SR_Done);
	}
victor's avatar
 
victor committed
513 514
}

515
void KumirRunPlugin::handleLineChanged(int lineNo, quint32 colStart, quint32 colEnd)
victor's avatar
 
victor committed
516
{
Alexander A. Maly's avatar
Alexander A. Maly committed
517
	emit lineChanged(lineNo, colStart, colEnd);
victor's avatar
 
victor committed
518 519
}

520 521
void KumirRunPlugin::handleBreakpointHit(const QString &fileName, int lineNo)
{
Alexander A. Maly's avatar
Alexander A. Maly committed
522
	emit lineChanged(lineNo, 0, 0);
523 524
}

525 526


527
KumirRunPlugin::~KumirRunPlugin()
528
{
Alexander A. Maly's avatar
Alexander A. Maly committed
529 530 531 532 533 534 535 536 537 538 539 540 541 542
	if (pRun_->isRunning()) {
		pRun_->stop();
		pRun_->wait();
	}
	delete pRun_;
	if (gui_) {
		delete gui_;
	}
	if (console_) {
		delete console_;
	}
	if (common_) {
		delete common_;
	}
543 544
}

545 546
Shared::RunInterface::RunMode KumirRunPlugin::currentRunMode() const
{
Alexander A. Maly's avatar
Alexander A. Maly committed
547
	return pRun_->currentRunMode();
548 549
}

550

551
void KumirRunPlugin::prepareCommonRun()
552
{
Alexander A. Maly's avatar
Alexander A. Maly committed
553 554 555 556
	common_ = new CommonFunctors;
	pRun_->vm->setFunctor(&common_->call);
	pRun_->vm->setFunctor(&common_->toString);
	pRun_->vm->setFunctor(&common_->fromString);
557 558
}

559
void KumirRunPlugin::prepareConsoleRun()
560
{
Alexander A. Maly's avatar
Alexander A. Maly committed
561 562 563
	if (! common_) {
		prepareCommonRun();
	}
564

Alexander A. Maly's avatar
Alexander A. Maly committed
565
	console_ = new ConsoleFunctors;
566

Alexander A. Maly's avatar
Alexander A. Maly committed
567 568 569
	const Kumir::Encoding localeEncoding =
#ifdef Q_OS_WIN32
		Kumir::CP1251;
570
#else
Alexander A. Maly's avatar
Alexander A. Maly committed
571
		Kumir::UTF8;
572
#endif
573

Alexander A. Maly's avatar
Alexander A. Maly committed
574 575 576 577
	std::deque<std::string> arguments;
	foreach (const QString &arg, qApp->arguments()) {
		arguments.push_back(arg.toStdString());
	}
578

Alexander A. Maly's avatar
Alexander A. Maly committed
579 580 581 582
	console_->input.setLocale(localeEncoding);
	console_->output.setLocale(localeEncoding);
	console_->getMainArgument.setLocale(localeEncoding);
	console_->returnMainValue.setLocale(localeEncoding);
583

Alexander A. Maly's avatar
Alexander A. Maly committed
584 585 586 587
	console_->input.setCustomTypeFromStringFunctor(&common_->fromString);
	console_->getMainArgument.setCustomTypeFromStringFunctor(&common_->fromString);
	console_->output.setCustomTypeToStringFunctor(&common_->toString);
	console_->returnMainValue.setCustomTypeToStringFunctor(&common_->toString);
588

Alexander A. Maly's avatar
Alexander A. Maly committed
589
	console_->getMainArgument.init(arguments);
590

Alexander A. Maly's avatar
Alexander A. Maly committed
591
	console_->reset.setCallFunctor(&common_->call);
592

Alexander A. Maly's avatar
Alexander A. Maly committed
593 594 595 596 597 598 599 600
	pRun_->vm->setFunctor(&console_->reset);
	pRun_->vm->setFunctor(&console_->load);
	pRun_->vm->setFunctor(&console_->input);
	pRun_->vm->setFunctor(&console_->output);
	pRun_->vm->setFunctor(&console_->getMainArgument);
	pRun_->vm->setFunctor(&console_->returnMainValue);
	defaultInputBuffer_ = &console_->input;
	defaultOutputBuffer_ = &console_->output;
601 602
}

603
void KumirRunPlugin::prepareGuiRun()
604
{
Alexander A. Maly's avatar
Alexander A. Maly committed
605 606 607 608 609
	if (! common_) {
		prepareCommonRun();
	}
	qDebug() << "Prepare gui run";
	gui_ = new GuiFunctors;
610

Alexander A. Maly's avatar
Alexander A. Maly committed
611 612 613 614
	gui_->input.setRunnerInstance(pRun_);
	gui_->output.setRunnerInstance(pRun_);
	gui_->getMainArgument.setRunnerInstance(pRun_);
	gui_->returnMainValue.setRunnerInstance(pRun_);
615

Alexander A. Maly's avatar
Alexander A. Maly committed
616 617 618 619
	gui_->input.setCustomTypeFromStringFunctor(&common_->fromString);
	gui_->output.setCustomTypeToStringFunctor(&common_->toString);
	gui_->getMainArgument.setCustomTypeFromStringFunctor(&common_->fromString);
	gui_->returnMainValue.setCustomTypeToStringFunctor(&common_->toString);
620

Alexander A. Maly's avatar
Alexander A. Maly committed
621
	gui_->reset.setCallFunctor(&common_->call);
622

Alexander A. Maly's avatar
Alexander A. Maly committed
623 624 625 626
	connect(&gui_->pause, SIGNAL(requestPause()),
		pRun_, SLOT(handlePauseRequest()),
		Qt::DirectConnection
	);
Victor Yacovlev's avatar
Victor Yacovlev committed
627

Alexander A. Maly's avatar
Alexander A. Maly committed
628 629
	connect(&gui_->reset, SIGNAL(showActorWindow(QByteArray)),
		this, SIGNAL(showActorWindowRequest(QByteArray)));
630

Alexander A. Maly's avatar
Alexander A. Maly committed
631 632 633 634 635 636 637 638 639 640
	pRun_->vm->setFunctor(&gui_->reset);
	pRun_->vm->setFunctor(&gui_->load);
	pRun_->vm->setFunctor(&gui_->input);
	pRun_->vm->setFunctor(&gui_->output);
	pRun_->vm->setFunctor(&gui_->getMainArgument);
	pRun_->vm->setFunctor(&gui_->returnMainValue);
	pRun_->vm->setFunctor(&gui_->pause);
	pRun_->vm->setFunctor(&gui_->delay);
	defaultInputBuffer_ = &gui_->input;
	defaultOutputBuffer_ = &gui_->output;
641 642 643 644
}

void KumirRunPlugin::setStdInTextStream(QTextStream *stream)
{
Alexander A. Maly's avatar
Alexander A. Maly committed
645 646 647 648 649 650 651
	if (simulatedInputBuffer_) {
		delete simulatedInputBuffer_;
		simulatedInputBuffer_ = 0;
	}
	if (stream) {
		simulatedInputBuffer_ = new Gui::SimulatedInputBuffer(stream);
	}
652 653 654 655
}

void KumirRunPlugin::setStdOutTextStream(QTextStream *stream)
{
Alexander A. Maly's avatar
Alexander A. Maly committed
656 657 658 659 660 661 662
	if (simulatedOutputBuffer_) {
		delete simulatedOutputBuffer_;
		simulatedOutputBuffer_ = 0;
	}
	if (stream) {
		simulatedOutputBuffer_ = new Gui::SimulatedOutputBuffer(stream);
	}
663 664
}

665 666
void KumirRunPlugin::runProgramInCurrentThread(bool useTestingEntryPoint)
{
Alexander A. Maly's avatar
Alexander A. Maly committed
667 668 669 670 671 672 673 674 675 676
	if (useTestingEntryPoint) {
		pRun_->setEntryPointToTest();
	} else {
		pRun_->setEntryPointToMain();
	}
	pRun_->vm->setConsoleInputBuffer(simulatedInputBuffer_ ? simulatedInputBuffer_ : defaultInputBuffer_);
	pRun_->vm->setConsoleOutputBuffer(simulatedOutputBuffer_ ? simulatedOutputBuffer_ : defaultOutputBuffer_);
	pRun_->reset();
	pRun_->runInCurrentThread();
	checkForErrorInConsole();
677 678
}

679 680 681
QList<ExtensionSystem::CommandLineParameter>
KumirRunPlugin::acceptableCommandLineParameters() const
{
Alexander A. Maly's avatar
Alexander A. Maly committed
682 683
	using ExtensionSystem::CommandLineParameter;
	QList<CommandLineParameter> result;
684

Alexander A. Maly's avatar
Alexander A. Maly committed
685 686 687 688
	result << CommandLineParameter(
			false,
			'p', "pipe",
			tr("Run in pipeline batch mode without user interaction"));
689

Alexander A. Maly's avatar
Alexander A. Maly committed
690 691 692 693
	result << CommandLineParameter(
			false,
			't', "testing",
			tr("Use testing entry point instead of main"));
694

Alexander A. Maly's avatar
Alexander A. Maly committed
695 696 697 698 699 700 701 702
	// Startup parameters
	result << CommandLineParameter(
			false,
			tr("PROGRAM.kod"),
			tr("Executable kumir bytecode"),
			QVariant::String,
			true
		);
703

Alexander A. Maly's avatar
Alexander A. Maly committed
704 705 706 707 708 709 710
	result << CommandLineParameter(
			false,
			tr("PROGRAM_ARG_%1"),
			tr("Program argument"),
			QVariant::String,
			false
		);
711

Alexander A. Maly's avatar
Alexander A. Maly committed
712
	return result;
713 714
}

715 716 717 718
QString KumirRunPlugin::initialize(
	const QStringList &configurationArguments,
	const ExtensionSystem::CommandLine &runtimeArguments
) {
Alexander A. Maly's avatar
Alexander A. Maly committed
719
	pRun_->programLoaded = false;
720
	bool noBreakpoints = configurationArguments.contains("nobreakpoints");
Alexander A. Maly's avatar
Alexander A. Maly committed
721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738
	pRun_->setSupportBreakpoints(!noBreakpoints);
	qRegisterMetaType<QVariant::Type>("QVariant::Type");
	qRegisterMetaType< QList<QVariant::Type> >("QList<QVariant::Type>");
	qRegisterMetaType<Shared::RunInterface::StopReason>("Shared::RunInterface::StopReason");

	if (configurationArguments.contains("console")) {
		prepareConsoleRun();
	} else {
		prepareGuiRun();
	}

	if (ExtensionSystem::PluginManager::instance()->startupModule() == this) {
		if (runtimeArguments.hasFlag(QChar('p'))) {
			console_->returnMainValue.setQuietMode(true);
			console_->getMainArgument.setQuietMode(true);
		}

		onlyOneTryToInput_ = runtimeArguments.hasFlag(QChar('p'));
739

victor's avatar
 
victor committed
740
#ifndef Q_OS_WIN32
Alexander A. Maly's avatar
Alexander A. Maly committed
741
		setlocale(LC_CTYPE, "ru_RU.UTF-8");
victor's avatar
 
victor committed
742
#else
Alexander A. Maly's avatar
Alexander A. Maly committed
743
		setlocale(LC_CTYPE, ".1251");
victor's avatar
 
victor committed
744
#endif
745

Alexander A. Maly's avatar
Alexander A. Maly committed
746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764
		QString fileName;
		QStringList programArguments;
		for (int i = 1; i < qApp->arguments().size(); i++) {
			const QString arg = qApp->arguments()[i];
			if (fileName.isEmpty()) {
				if (!arg.startsWith("-") && !arg.startsWith("[")) {
					fileName = arg;
				}
			} else {
				programArguments << arg;
			}
		}
		if (!fileName.isEmpty()) {
			QFile f(fileName);
			if (f.open(QIODevice::ReadOnly)) {
				RunnableProgram program;
				program.executableData = f.readAll();
				program.executableFileName = fileName;
				loadProgram(program);
765 766 767 768

//                if (localError.length() > 0) {
//                    return QString::fromStdWString(message);
//                }
Alexander A. Maly's avatar
Alexander A. Maly committed
769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803
			}
			if (pRun_->error().length() > 0) {
				return pRun_->error();
			}
		} else {
			qApp->setProperty("returnCode", 127);
			return tr("Error: file name not specified.\nRun with --help parameter for more details");
		}
		if (runtimeArguments.hasFlag('t')) {
			if (!pRun_->hasTestingAlgorithm()) {
				qApp->setProperty("returnCode", 125);
				return QString::fromUtf8("В ПРОГРАММЕ НЕТ ТЕСТОВОГО АЛГОРИТМА");
			} else {
				pRun_->setEntryPointToTest();
			}
		}
	}

	return "";
}

void KumirRunPlugin::timerEvent(QTimerEvent *event)
{
	killTimer(event->timerId());
	event->accept();
	pRun_->reset();
	QList<KPlugin *> actors = ExtensionSystem::PluginManager::instance()
		->loadedPlugins("Actor*");
	foreach (KPlugin *plugin, actors) {
		Shared::ActorInterface *actor =
			qobject_cast<Shared::ActorInterface *>(plugin);
		if (actor) {
			actor->setAnimationEnabled(false);
		}
		if (actor && actor->mainWidget()) {
804
//            actor->mainWidget()->show();
Alexander A. Maly's avatar
Alexander A. Maly committed
805 806 807 808 809 810
			connect(pRun_, SIGNAL(finished()), actor->mainWidget(), SLOT(close()));
		}
	}
	connect(pRun_, SIGNAL(finished()),
		this, SLOT(checkForErrorInConsole()));
	pRun_->start();
Victor Yacovlev's avatar
Victor Yacovlev committed
811 812
}

813 814
void KumirRunPlugin::checkForErrorInConsole()
{
Alexander A. Maly's avatar
Alexander A. Maly committed
815 816 817 818 819 820 821 822 823
	if (pRun_->error().length() > 0) {
		const QString message = pRun_->effectiveLineNo() != -1
			?
			tr("RUNTIME ERROR AT LINE %1: %2")
			.arg(pRun_->effectiveLineNo())
			.arg(pRun_->error())
			: tr("RUNTIME ERROR: %1").arg(pRun_->error());
		std::cerr << message.toLocal8Bit().constData() << std::endl;
	}
824 825
}

826
void KumirRunPlugin::start()
victor's avatar
 
victor committed
827
{
Alexander A. Maly's avatar
Alexander A. Maly committed
828 829 830 831 832 833 834 835 836
	if (pRun_->programLoaded) {
		pRun_->vm->setConsoleInputBuffer(simulatedInputBuffer_ ? simulatedInputBuffer_ : defaultInputBuffer_);
		pRun_->vm->setConsoleOutputBuffer(simulatedOutputBuffer_ ? simulatedOutputBuffer_ : defaultOutputBuffer_);
		if (!ExtensionSystem::PluginManager::instance()->isGuiRequired()) {
			pRun_->reset();
			pRun_->start();
			pRun_->wait();
			checkForErrorInConsole();
			stop();
837
			ExtensionSystem::PluginManager::instance()->switchGlobalState(Shared::PluginInterface::GS_Observe);
Alexander A. Maly's avatar
Alexander A. Maly committed
838 839 840 841
		} else {
			startTimer(0); // start thread after event loop started
		}
	}
victor's avatar
 
victor committed
842 843
}

844 845
void KumirRunPlugin::stop()
{
Alexander A. Maly's avatar
Alexander A. Maly committed
846
	terminateAndWaitForStopped();
847 848
}

849
bool KumirRunPlugin::hasMoreInstructions() const
victor's avatar
 
victor committed
850
{
Alexander A. Maly's avatar
Alexander A. Maly committed
851
	return pRun_->hasMoreInstructions();
victor's avatar
 
victor committed
852 853
}

854
bool KumirRunPlugin::canStepOut() const
victor's avatar
 
victor committed
855
{
Alexander A. Maly's avatar
Alexander A. Maly committed
856
	return pRun_->canStepOut();
victor's avatar
 
victor committed
857 858
}

859
bool KumirRunPlugin::hasTestingEntryPoint() const
860
{
Alexander A. Maly's avatar
Alexander A. Maly committed
861
	return pRun_->vm->hasTestingAlgorithm();
862
}
victor's avatar
 
victor committed
863

864 865
bool KumirRunPlugin::hasBreakpointsSupport() const
{
Alexander A. Maly's avatar
Alexander A. Maly committed
866
	return pRun_->supportBreakpoints();
867 868
}

Alexander A. Maly's avatar
Alexander A. Maly committed
869
QAbstractItemModel *KumirRunPlugin::debuggerVariablesViewModel() const
870
{
Alexander A. Maly's avatar
Alexander A. Maly committed
871
	return pRun_->variablesModel();
872 873
}

victor's avatar
 
victor committed
874 875
} // namespace KumirCodeRun

876

Victor Yacovlev's avatar
Victor Yacovlev committed
877
#if QT_VERSION < 0x050000
878
Q_EXPORT_PLUGIN(KumirCodeRun::KumirRunPlugin)
Victor Yacovlev's avatar
Victor Yacovlev committed
879
#endif