robotmodule.cpp 35.5 KB
Newer Older
1 2 3 4
/*
This file is generated, but you can safely change it
until you run "gen_actor_source.py" with "--project" flag.

5
Generated file is just a skeleton for module contents.
6 7 8
You should change it corresponding to functionality.
*/

9 10 11
#include "rfield.h"
#include "cfield.h"
#include "srobot.h"
12
#include "robotmodule.h"
13 14 15 16
#include "robotview.h"
#include "pult.h"
#include "kumir2-libs/widgets/pultlogger.h"

Alexander A. Maly's avatar
Alexander A. Maly committed
17 18 19 20 21 22 23 24 25 26 27 28
#include <QMenu>
#include <QClipboard>
#include <QLayout>
#include <QMessageBox>
#include <QFileDialog>
#include <QLabel>
#include <QSpinBox>
#include <QDialogButtonBox>
#include <QDebug>
#include <QTimer>
#include <QProcessEnvironment>

29 30 31 32 33
static const int AnimTime = 70;
#define MAX_COLUMNS 255
#define MAX_ROWS 128

namespace ActorRobot
34
{
35
const RobotModule *RobotModule::self = 0;
Denis Khachko's avatar
Denis Khachko committed
36

37 38 39 40 41 42 43 44 45
RobotModule::RobotModule(ExtensionSystem::KPlugin *parent) :
	RobotModuleBase(parent)
{
	self = this;
	inDock = false;
	animation = true;
	pressed = false;
	m_mainWidget = 0;
	m_pultWidget = 0;
46 47 48 49 50
}


void RobotModule::createGui()
{
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
	field = new RoboField(0, this);
	field->createField(7, 7);

	field->setRoboPos(0, 0);
	field->createRobot();
	view = new RobotView(field);
	view-> setViewportUpdateMode(QGraphicsView::FullViewportUpdate);
	view->setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform | QPainter::TextAntialiasing);
	m_mainWidget = view;
	m_pultWidget = new RoboPult();

	connect(m_pultWidget, SIGNAL(goUp()), this, SLOT(runGoUp()));
	connect(m_pultWidget, SIGNAL(goDown()), this, SLOT(runGoDown()));
	connect(m_pultWidget, SIGNAL(goLeft()), this, SLOT(runGoLeft()));
	connect(m_pultWidget, SIGNAL(goRight()), this, SLOT(runGoRight()));
	connect(m_pultWidget, SIGNAL(doPaint()), this, SLOT(runDoPaint()));
	connect(m_pultWidget, SIGNAL(hasLeftWall()), this, SLOT(runIsWallAtLeft()));
	connect(m_pultWidget, SIGNAL(hasRightWall()), this, SLOT(runIsWallAtRight()));
	connect(m_pultWidget, SIGNAL(hasUpWall()), this, SLOT(runIsWallAtTop()));
	connect(m_pultWidget, SIGNAL(hasDownWall()), this, SLOT(runIsWallAtBottom()));
	connect(m_pultWidget, SIGNAL(noLeftWall()), this, SLOT(runIsFreeAtLeft()));
	connect(m_pultWidget, SIGNAL(noRightWall()), this, SLOT(runIsFreeAtRight()));
	connect(m_pultWidget, SIGNAL(noUpWall()), this, SLOT(runIsFreeAtTop()));
	connect(m_pultWidget, SIGNAL(noDownWall()), this, SLOT(runIsFreeAtBottom()));
	connect(m_pultWidget, SIGNAL(Rad()), this, SLOT(runRadiation()));
	connect(m_pultWidget, SIGNAL(Temp()), this, SLOT(runTemperature()));
	connect(m_pultWidget, SIGNAL(Colored()), this, SLOT(runIsColor()));
	connect(m_pultWidget, SIGNAL(Clean()), this, SLOT(runIsClear()));
	connect(m_pultWidget, SIGNAL(Color()), this, SLOT(runDoPaint()));
	connect(m_pultWidget, SIGNAL(robReset()), this, SLOT(reset()));


	connect(m_pultWidget, SIGNAL(copyTextToKumir(QString)), this, SLOT(copyFromPult(QString)));
	connect(this, SIGNAL(sendToPultLog(QVariant)), m_pultWidget, SLOT(addToResultLog(QVariant)));
	startField = field->Clone();
	field->drawField(FIELD_SIZE_SMALL);
	field->dropWasEdit();
	m_actionRobotEditEnvironment->setCheckable(true);
	connect(m_actionRobotLoadEnvironment, SIGNAL(triggered()), this, SLOT(loadEnv()));
	connect(m_actionRobotRevertEnvironment, SIGNAL(triggered()), this, SLOT(resetEnv()));
	connect(m_actionRobotSaveEnvironment, SIGNAL(triggered()), this, SLOT(saveEnv()));
	connect(m_actionRobotEditEnvironment, SIGNAL(triggered()), this, SLOT(editEnv()));
	connect(m_actionRobotNewEnvironment, SIGNAL(triggered()), this, SLOT(newEnv()));
	connect(m_actionRobotAutoWindowSize, SIGNAL(triggered()), this, SLOT(setWindowSize()));
	connect(m_actionRobotSave2Png, SIGNAL(triggered()), this, SLOT(save2png()));

	prepareNewWindow();
	rescentMenu = new QMenu();
	m_actionRobotLoadRescent->setMenu(rescentMenu);
	view->setWindowTitle(trUtf8("Робот - нет файла"));
101 102
}

Denis Khachko's avatar
Denis Khachko committed
103
void RobotModule::copyFromPult(QString log)
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
	QClipboard *clipboard = QApplication::clipboard();
	QString originalText = clipboard->text();

	clipboard->setText(log);
};

/* public slot */ void RobotModule::loadActorData(QIODevice *source)
{
	// Set actor specific data (like environment)
	// The source should be ready-to-read QIODevice like QBuffer or QFile
	if (!DISPLAY) { //console mode
		curConsoleField = new ConsoleField(10, 15);
		if (curConsoleField->loadFromDataStream(source) != 0) {
			qDebug() << "ERROR LOADING FIELD FROM STREAM ";
		}
		return;
	}
	qDebug() << "Load env";
	if (field->loadFromDataStream(source) != 0) {
		return ;
	}
	m_pultWidget->Logger->ClearLog();
	m_mainWidget->setWindowTitle(trUtf8("Робот - ") + source->objectName());
	startField = field->Clone();
	field->dropWasEdit();

	reset();
132 133
}

134

135 136 137 138 139
void RobotModule::reset()
{
	/* TODO
	This method is called when actor resets its state before program starts.
	*/
140 141
	//delete field;
	if (!DISPLAY) { //console mode
142
		qDebug() << "Robot::Reset::console mode";
143
		return;
144 145
	} else {
		qDebug() << "Robot::Reset::gui mode";
146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163
	}

	field->destroyRobot();
	field->deleteLater();
	if (field->isEditMode()) {
		field->setMode(NORMAL_MODE);
		view->showButtons(false);
		view->repaint();
		m_actionRobotEditEnvironment->setChecked(false);
		startField = field->Clone();
	}
	field = startField->Clone();
	field->setRoboPos(startField->robotX(), startField->robotY());
	field->createRobot();
	field->drawField(FIELD_SIZE_SMALL);
	view->setScene(field);
	field->drawField(FIELD_SIZE_SMALL);
	view->setField(field);
164 165
}

166 167 168 169 170 171
void RobotModule::changeGlobalState(
	ExtensionSystem::GlobalState old,
	ExtensionSystem::GlobalState current
) {
	Q_UNUSED(old);
	using namespace Shared;
172 173 174 175 176 177 178 179 180 181 182
	qDebug() << "RobotModuleBase::changeGlobalState from " << (int) old << " to " << (int) current;

	if (!DISPLAY) {
		if (current == PluginInterface::GS_Observe && !oName.isEmpty()) {
			int res = curConsoleField->saveToFile(oName);
			qDebug() << "Dumped state to" << oName << ", res = " << res;
		}

		return;
	}

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
	view->setViewportUpdateMode(QGraphicsView::SmartViewportUpdate);
	if (current == PluginInterface::GS_Running) {
		view->setViewportUpdateMode(QGraphicsView::NoViewportUpdate);
		m_actionRobotRevertEnvironment->setEnabled(false);
		m_actionRobotLoadEnvironment->setEnabled(false);
		m_actionRobotLoadRescent->setEnabled(false);
		m_actionRobotRevertEnvironment->setEnabled(false);
		m_actionRobotSaveEnvironment->setEnabled(false);
		m_actionRobotEditEnvironment->setEnabled(false);
		m_actionRobotNewEnvironment->setEnabled(false);
	}
	if (current == PluginInterface::GS_Unlocked || current == PluginInterface::GS_Observe) {
		m_actionRobotRevertEnvironment->setEnabled(true);
		m_actionRobotLoadEnvironment->setEnabled(true);
		m_actionRobotLoadRescent->setEnabled(true);
		m_actionRobotRevertEnvironment->setEnabled(true);
		m_actionRobotSaveEnvironment->setEnabled(true);
		m_actionRobotEditEnvironment->setEnabled(true);
		m_actionRobotNewEnvironment->setEnabled(true);
		view->FindRobot();
	}
	field->destroyNet();
	field->drawNet();
	view->update();
	field->update();
	msleep(2 * AnimTime);
	view->update();
	field->update();
Alexander A. Maly's avatar
Alexander A. Maly committed
211 212
	qApp->processEvents(QEventLoop::ExcludeUserInputEvents);//Redraw event fix
}
213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230

void RobotModule::reloadSettings(
	ExtensionSystem::SettingsPtr settings,
	const QStringList &keys
) {
	Q_UNUSED(keys);
	qDebug() << "reload settings";
	field->reloadSettings();
	CurCellSize = settings->value("Robot/CellSize", FIELD_SIZE_SMALL).toInt();
	view->reloadSett(settings);
	if (RobotModule::robotSettings()->value("Robot/SFF").isValid()) {
		if (LoadFromFile(RobotModule::robotSettings()->value("Robot/SFF").toString()) != 0) {
			createEmptyField(7, 7);

		}
		setWindowSize();
	}
	createRescentMenu();
Victor Yacovlev's avatar
Victor Yacovlev committed
231 232
}

233 234
void RobotModule::setAnimationEnabled(bool enabled)
{
235
	animation = enabled;
236 237 238
}


239
QWidget *RobotModule::mainWidget() const
240
{
241
	return m_mainWidget;
242 243
}

244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263
class AAA : public QWidget
{
public:
	explicit AAA(QWidget *pult): QWidget(), pult_(pult)
	{
		setLayout(new QVBoxLayout);
		layout()->setContentsMargins(0, 0, 0, 0);
		layout()->addWidget(pult);
	}

	QSize minimumSizeHint() const
	{
		return pult_->minimumSizeHint();
	}
private:
	QWidget *pult_;
};


QWidget *RobotModule::pultWidget() const
Denis Khachko's avatar
Denis Khachko committed
264
{
265 266 267
	static QWidget *dummy = new AAA(m_pultWidget);
	return dummy;
	return m_pultWidget;
Denis Khachko's avatar
Denis Khachko committed
268
}
269 270 271

QList<ExtensionSystem::CommandLineParameter>
RobotModule::acceptableCommandLineParameters()
272
{
273 274 275 276 277 278 279
	QList<ExtensionSystem::CommandLineParameter> params;
	params.append(
		ExtensionSystem::CommandLineParameter(
			true, 'f', "field", tr("Robot field file name"),
			QVariant::String, false
		)
	);
280 281 282 283 284 285
	params.append(
		ExtensionSystem::CommandLineParameter(
			true, 'o', "output", tr("Robot field output file name"),
			QVariant::String, false
		)
	);
286 287 288 289 290 291 292 293 294 295 296 297 298
	return params;
}

QString RobotModule::initialize(
	const QStringList &configurationParameters,
	const ExtensionSystem::CommandLine &runtimeParameters
) {
	QString fName = "";
	if (runtimeParameters.value('f').isValid()) {
		fName = runtimeParameters.value('f').toString();
		qDebug() << "FIELD: |" << fName << "| ";
	}

299 300 301 302 303
	if (runtimeParameters.value('o').isValid()) {
		oName = runtimeParameters.value('o').toString();
		qDebug() << "OUTPUT: |" << oName << "| ";
	}

304
	DISPLAY = (qobject_cast<QApplication*>(qApp) != 0);
305

306
#ifdef Q_OS_LINUX
307 308 309
	QProcessEnvironment pe = QProcessEnvironment::systemEnvironment();
	qDebug() << "Display" << pe.value("DISPLAY");
	if (pe.keys().indexOf("DISPLAY") < 0 || pe.value("DISPLAY").isEmpty()) {
310 311 312 313 314
		DISPLAY = false;
	}
#endif

	if (!DISPLAY) {
315 316 317 318 319 320 321 322 323 324 325 326 327 328 329
		qDebug() << "Robot:Console mode";
		curConsoleField = new ConsoleField(10, 15);
		DISPLAY = false;
		if (!fName.isEmpty()) {
			qDebug() << "LOAD FIELD ERR CODE:" << curConsoleField->loadFromFile(fName);
		}
		return "";
	}

	qDebug() << "Robot:GuiMode";

	if (!configurationParameters.contains("tablesOnly")) {
		createGui();
		redrawTimer = new QTimer();
		connect(redrawTimer, SIGNAL(timeout()), this, SLOT(getTimer()));
Alexander A. Maly's avatar
Alexander A. Maly committed
330
		redrawTimer->start(3000);
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
	}

	if (!fName.isEmpty()) {
		int err = LoadFromFile(fName);
		if (err != 0) {
			return "Error loading: '" + fName + "', code=" + err;
		}
	} else if (RobotModule::robotSettings()->value("Robot/SFF").isValid()) {
		QString sName = RobotModule::robotSettings()->
			value("Robot/SFF").toString();
		int err = LoadFromFile(sName);
		if (err != 0) {
			qDebug() << "Error loading: '" + sName + "', code=" + err;
			createEmptyField(7, 7);
		}
	}

	ExtensionSystem::SettingsPtr sett = robotSettings();
	if (sett->value("Robot/Dir").isValid()) {
		curDir = sett->value("Robot/Dir").toString();
		curPDir = curDir;
	}

	if (!configurationParameters.contains("tablesOnly")) {
		field->reloadSettings();
		reloadSettings(robotSettings(), QStringList());
	}

	return "";
360 361
}

362 363
void RobotModule::runGoUp()
{
364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387
	if (!DISPLAY) {
		qDebug() << "Go up";
		if (!curConsoleField->goUp()) {
			setError(trUtf8("Робот разбился: сверху стена!"));
		}
		return;
	}
	mutex.lock();
	qDebug() << "Robot up";
	QString status = "OK";
	if (!field->stepUp()) {
		field->setCrash(UP_CRASH);
		setError(trUtf8("Робот разбился: сверху стена!"));
		status = trUtf8("Отказ");
	}
	if (sender() == m_pultWidget) {
		m_pultWidget->Logger->appendText(trUtf8("вверх"), QString::fromUtf8("вверх     "), status);
	}
	if (animation) {
		msleep(AnimTime);
	}
	msleep(qrand() % 10);
	mutex.unlock();
	// view->update();
388 389 390 391 392 393
	return;
}


void RobotModule::runGoDown()
{
394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416
	if (!DISPLAY) {
		qDebug() << "Go down";
		if (!curConsoleField->goDown()) {
			setError(trUtf8("Робот разбился: снизу стена!"));
		}
		return;
	}
	mutex.lock();
	qDebug() << "Robot down";
	QString status = "OK";
	if (!field->stepDown()) {
		setError(trUtf8("Робот разбился: снизу стена!"));
		field->setCrash(DOWN_CRASH);
		status = trUtf8("Отказ");
	}
	if (sender() == m_pultWidget) {
		m_pultWidget->Logger->appendText(trUtf8("вниз"), QString::fromUtf8("вниз     "), status);
	}
	if (animation) {
		msleep(AnimTime);
	}
	msleep(qrand() % 10);
	mutex.unlock();
417 418 419 420 421 422
	return;
}


void RobotModule::runGoLeft()
{
Denis Khachko's avatar
Denis Khachko committed
423

424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446
	qDebug() << "Robot left";

	if (!DISPLAY) {
		if (!curConsoleField->goLeft()) {
			setError(trUtf8("Робот разбился: слева стена!"));
		}
		return;
	}
	mutex.lock();
	QString status = "OK";
	if (!field->stepLeft()) {
		field->setCrash(LEFT_CRASH);
		setError(trUtf8("Робот разбился: слева стена!"));
		status = trUtf8("Отказ");
	};
	if (sender() == m_pultWidget) {
		m_pultWidget->Logger->appendText(trUtf8("влево"), QString::fromUtf8("влево     "), status);
	}
	if (animation) {
		msleep(AnimTime);
	}
	msleep(qrand() % 10);
	mutex.unlock();
447 448 449 450 451 452
	return;
}


void RobotModule::runGoRight()
{
453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477
	if (!DISPLAY) {
		if (!curConsoleField->goRight()) {
			setError(trUtf8("Робот разбился: справа стена!"));
		}
		return;
	}
	//  qDebug() << "Robot right";
	mutex.lock();
	QString status = "OK";
	if (!field->stepRight()) {
		field->setCrash(RIGHT_CRASH);
		status = trUtf8("Отказ");

		setError(trUtf8("Робот разбился: справа стена!"));
	}

	if (sender() == m_pultWidget) {
		m_pultWidget->Logger->appendText(trUtf8("вправо"), QString::fromUtf8("вправо     "), status);
	}
	if (animation) {
		msleep(AnimTime);
	}
	msleep(qrand() % 10);
	mutex.unlock();

478 479 480 481 482 483
	return;
}


void RobotModule::runDoPaint()
{
484 485 486 487 488 489 490 491 492 493

	if (!DISPLAY) {
		curConsoleField->getCurItem()->isColored = true;
		return;
	}

	if (!field->currentCell()->IsColored) {
		field->reverseColorCurrent();
	}
	QString status = "OK";
494 495 496
//    if (sender() && qobject_cast<QDeclarativeItem*>(sender())) {
//        emit sendToPultLog(status);
//    }
497 498 499 500 501 502 503 504
	if (sender() == m_pultWidget) {
		m_pultWidget->Logger->appendText(trUtf8("закрасить"), trUtf8("закрасить"), "OK");
	}
	//  if(animation)
//   {
	view->update();
	msleep(AnimTime);
	//  }
505 506 507 508 509 510
	return;
}


bool RobotModule::runIsWallAtTop()
{
511 512 513 514 515 516 517

	if (!DISPLAY) {
		return curConsoleField->isUpWall();
	}

	bool result = !field->currentCell()->canUp();
	QString status = result ? trUtf8("Да") : trUtf8("Нет");
518 519 520
//    if (sender() && qobject_cast<QDeclarativeItem*>(sender())) {
//        emit sendToPultLog(status);
//    }
521 522 523 524
	if (sender() == m_pultWidget)
		m_pultWidget->Logger->appendText(QString::fromUtf8("вывод \'Сверху стена: \',сверху стена,нс"),
			trUtf8("сверху стена"), status);
	return result;
525 526 527 528 529
}


bool RobotModule::runIsWallAtBottom()
{
530 531 532 533 534 535 536

	if (!DISPLAY) {
		return curConsoleField->isDownWall();
	}

	bool result = !field->currentCell()->canDown();
	QString status = result ? trUtf8("Да") : trUtf8("Нет");
537 538 539
//    if (sender() && qobject_cast<QDeclarativeItem*>(sender())) {
//        emit sendToPultLog(status);
//    }
540 541 542 543 544
	if (sender() == m_pultWidget)
		m_pultWidget->Logger->appendText(QString::fromUtf8("вывод \'Снизу стена: \',снизу стена,нс"),
			QString::fromUtf8("снизу стена"), status);

	return result;
545 546 547 548 549
}


bool RobotModule::runIsWallAtLeft()
{
550 551 552 553 554 555
	if (!DISPLAY) {
		return curConsoleField->isLeftWall();
	}

	bool result = !field->currentCell()->canLeft();
	QString status = result ? trUtf8("Да") : trUtf8("Нет");
556 557 558
//    if (sender() && qobject_cast<QDeclarativeItem*>(sender())) {
//        emit sendToPultLog(status);
//    }
559 560 561 562 563
	if (sender() == m_pultWidget)
		m_pultWidget->Logger->appendText(QString::fromUtf8("вывод \'Слева стена: \',слева стена,нс"),
			trUtf8("слева стена"), status);

	return result;
564 565 566 567 568
}


bool RobotModule::runIsWallAtRight()
{
569 570 571 572 573 574

	if (!DISPLAY) {
		return curConsoleField->isRightWall();
	}
	bool result = !field->currentCell()->canRight();
	QString status = result ? trUtf8("Да") : trUtf8("Нет");
575 576 577
//    if (sender() && qobject_cast<QDeclarativeItem*>(sender())) {
//        emit sendToPultLog(status);
//    }
578 579 580 581 582 583 584 585 586
	if (sender() == m_pultWidget) {
		if (result)
			m_pultWidget->Logger->appendText(QString::fromUtf8("вывод \'Справа стена: \',справа стена,нс"),
				trUtf8("справа стена"), trUtf8("Да"));
		else
			m_pultWidget->Logger->appendText(QString::fromUtf8("вывод \'Справа стена: \',справа стена,нс"),
				trUtf8("справа стена"), trUtf8("Нет"));
	}
	return result;
587 588
}

mordol's avatar
Robot  
mordol committed
589
bool RobotModule::runIsFreeAtTop()
Victor Yacovlev's avatar
Victor Yacovlev committed
590
{
591 592 593 594 595 596 597 598 599 600 601
	if (!DISPLAY) {
		qDebug() << "Is free U:" << !curConsoleField->isUpWall();
		return !curConsoleField->isUpWall();
	}

	bool result = field->currentCell()->canUp();
	QString status = result ? trUtf8("Да") : trUtf8("Нет");
	if (sender() == m_pultWidget)
		m_pultWidget->Logger->appendText(QString::fromUtf8("вывод \'Сверху свободно: \',сверху свободно,нс"),
			trUtf8("сверху свободно"), status);
	return result;
Victor Yacovlev's avatar
Victor Yacovlev committed
602
}
603 604


mordol's avatar
Robot  
mordol committed
605
bool RobotModule::runIsFreeAtBottom()
Victor Yacovlev's avatar
Victor Yacovlev committed
606
{
607 608 609 610 611 612 613 614 615 616 617 618

	if (!DISPLAY) {
		qDebug() << "Is free D:" << !curConsoleField->isDownWall();
		return !curConsoleField->isDownWall();
	}

	bool result = field->currentCell()->canDown();
	QString status = result ? trUtf8("Да") : trUtf8("Нет");
	if (sender() == m_pultWidget)
		m_pultWidget->Logger->appendText(QString::fromUtf8("вывод \'Снизу свободно: \',снизу свободно,нс"),
			trUtf8("снизу свободно"), status);
	return result;
Victor Yacovlev's avatar
Victor Yacovlev committed
619
}
620 621


mordol's avatar
Robot  
mordol committed
622
bool RobotModule::runIsFreeAtLeft()
Victor Yacovlev's avatar
Victor Yacovlev committed
623
{
624 625 626 627 628 629 630 631 632 633 634 635 636 637
	if (!DISPLAY) {
		return !curConsoleField->isLeftWall();
	}

	bool result = field->currentCell()->canLeft();
	QString status = result ? trUtf8("Да") : trUtf8("Нет");
	if (sender() == m_pultWidget) {
		m_pultWidget->Logger->appendText(
			QString::fromUtf8("вывод \'Слева свободно: \',слева свободно,нс"),
			trUtf8("слева свободно"),
			status
		);
	}
	return result;
Victor Yacovlev's avatar
Victor Yacovlev committed
638
}
639 640


mordol's avatar
Robot  
mordol committed
641
bool RobotModule::runIsFreeAtRight()
Victor Yacovlev's avatar
Victor Yacovlev committed
642
{
643 644 645 646 647 648 649 650 651 652 653 654 655
	if (!DISPLAY) {
		return !curConsoleField->isRightWall();
	}
	bool result = field->currentCell()->canRight();
	QString status = result ? trUtf8("Да") : trUtf8("Нет");
	if (sender() == m_pultWidget) {
		m_pultWidget->Logger->appendText(
			QString::fromUtf8("вывод \'Справа свободно: \',справа свободно,нс"),
			trUtf8("справа свободно"),
			status
		);
	}
	return result;
Victor Yacovlev's avatar
Victor Yacovlev committed
656
}
mordol's avatar
Robot  
mordol committed
657

Denis Khachko's avatar
Denis Khachko committed
658
bool RobotModule::runIsColor()
659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 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 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890
{
	if (!DISPLAY) {
		return curConsoleField->getCurItem()->isColored;
	}

	bool result = field->currentCell()->isColored();
	QString status = result ? trUtf8("Да") : trUtf8("Нет");

	if (sender() == m_pultWidget) {
		m_pultWidget->Logger->appendText(
			QString::fromUtf8("вывод \'Клетка закрашена: \',клетка закрашена,нс"),
			QString::fromUtf8("клетка закрашена"),
			status
		);
	}
	return result;
}

bool RobotModule::runIsClear()
{
	if (!DISPLAY) {
		return !curConsoleField->getCurItem()->isColored;
	}

	bool result = !field->currentCell()->isColored();
	QString status = result ? trUtf8("да") : trUtf8("нет");
	if (sender() == m_pultWidget) {
		m_pultWidget->Logger->appendText(
			QString::fromUtf8("вывод \'Клетка чистая: \',клетка чистая,нс"),
			QString::fromUtf8("клетка чистая"),
			status
		);
	}
	return result;
}


qreal RobotModule::runRadiation()
{
	if (!DISPLAY) {
		return curConsoleField->getCurItem()->radiation;
	}

	double result = field->currentCell()->radiation;
	QString status = QString::number(result);

	if (sender() == m_pultWidget) {
		m_pultWidget->Logger->appendText(
			QString::fromUtf8("вывод \'Радиация: \',радиация,нс"),
			QString::fromUtf8("радиация"),
			status
		);
	}
	return result;
}

int RobotModule::runTemperature()
{
	if (!DISPLAY) {
		return curConsoleField->getCurItem()->temperature;
	}

	int result = field->currentCell()->temperature;
	QString status = QString::number(result);

	if (sender() == m_pultWidget) {
		m_pultWidget->Logger->appendText(
			QString::fromUtf8("вывод \'Температура: \',температура,нс"),
			QString::fromUtf8("температура"),
			status
		);
	}
	return result;
}


void RobotModule::runFieldSize(int &rows, int &cols)
{
	if (!DISPLAY) {
		rows = curConsoleField->Rows();
		cols = curConsoleField->Cols();
		return;
	}

	rows = field->rows();
	cols = field->columns();
}

bool RobotModule::runMark(int row, int col)
{
	qDebug() << "Get M R:" << row << " C:" << col;
	if (!DISPLAY) {
		uint32_t r = row - 1, c = col - 1;
		if (
			r >= curConsoleField->Rows() ||
			c >= curConsoleField->Cols()
		) {
			setError(trUtf8("Нет какой клетки!"));
			return false;
		}

		return curConsoleField->getItem(r, c)->mark;
	}

	if (
		row - 1 >= field->rows() ||
		col - 1 >= field->columns() ||
		row - 1 < 0 ||
		col - 1 < 0
	) {
		setError(trUtf8("Нет какой клетки!"));
		return false;
	}
	return field->cellAt(row - 1, col - 1)->mark;
}

bool RobotModule::runColored(int row, int col)
{
	qDebug() << "Get Col R:" << row << " C:" << col;
	if (!DISPLAY) {
		uint32_t r = row - 1, c = col - 1;
		if (
			r >= curConsoleField->Rows() ||
			c >= curConsoleField->Cols()
		) {
			setError(trUtf8("Нет какой клетки!"));
			return false;
		}

		return curConsoleField->getItem(r, c)->isColored;
	}

	if (row - 1 >= field->rows() || col - 1 >= field->columns()) {
		setError(trUtf8("Нет какой клетки!"));
		return false;
	}
	return  field->cellAt(row - 1, col - 1)->isColored();
}

void RobotModule::runRobotPos(int &row, int &col)
{
	if (!DISPLAY) {
		row = curConsoleField->robotRow() + 1;
		col = curConsoleField->robotCol() + 1;
		return;
	}

	if (row - 1 >= field->rows() || col - 1 >= field->columns()) {
		setError(trUtf8("Нет какой клетки!"));
		return;
	}
	col = field->robotX() + 1;
	row = field->robotY() + 1;
}

QChar RobotModule::runUpChar(int row, int col)
{
	if (!DISPLAY) {
		uint32_t r = row - 1, c = col - 1;
		if (
			r >= curConsoleField->Rows() ||
			c >= curConsoleField->Cols()
		) {
			setError(trUtf8("Нет какой клетки!"));
			return ' ';
		}

		return curConsoleField->getItem(r, c)->upChar;
	}


	if (row - 1 >= field->rows() || col - 1 >= field->columns()) {

		setError(trUtf8("Нет какой клетки!"));

		return ' ';
	}
	qDebug() << field->cellAt(row - 1, col - 1)->upChar;
	return field->cellAt(row - 1, col - 1)->upChar;
}

int RobotModule::runCellTemp(int row, int col)
{
	if (!DISPLAY) {
		uint32_t r = row - 1, c = col - 1;
		if (r >= curConsoleField->Rows() ||
			c >= curConsoleField->Cols()
		) {
			setError(trUtf8("Нет какой клетки!"));
			return 0;
		}

		return curConsoleField->getItem(r, c)->temperature;
	}


	if (row - 1 >= field->rows() || col - 1 >= field->columns()) {

		setError(trUtf8("Нет какой клетки!"));

		return ' ';
	}
	qDebug() << field->cellAt(row - 1, col - 1)->upChar;
	return field->cellAt(row - 1, col - 1)->temperature;
}

qreal RobotModule::runCellRad(int row, int col)
{
	if (!DISPLAY) {
		uint32_t r = row - 1, c = col - 1;
		if (
			r >= curConsoleField->Rows() ||
			c >= curConsoleField->Cols()
		) {
			setError(trUtf8("Нет какой клетки!"));
			return 0;
		}
		return curConsoleField->getItem(r, c)->radiation;
	}

	if (row - 1 >= field->rows() || col - 1 >= field->columns()) {
		setError(trUtf8("Нет какой клетки!"));
		return ' ';
	}

	qDebug() << field->cellAt(row - 1, col - 1)->upChar;
	return field->cellAt(row - 1, col - 1)->radiation;
}

QChar RobotModule::runDownChar(int row, int col)
{
	if (!DISPLAY) {
891
		qDebug() << "Get DC R:" << row << " C:" << col << " ROWS" << curConsoleField->Rows();
892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937
		uint32_t r = row - 1, c = col - 1;
		if (
			r >= curConsoleField->Rows() ||
			c >= curConsoleField->Cols()
		) {
			setError(trUtf8("Нет какой клетки!"));
			return ' ';
		}

		return curConsoleField->getItem(r, c)->downChar;
	}

	if (row - 1 >= field->rows() || col - 1 >= field->columns()) {

		setError(trUtf8("Нет какой клетки!"));

		return ' ';
	}

	qDebug() << field->cellAt(row - 1, col - 1)->downChar;
	return field->cellAt(row - 1, col - 1)->downChar;
}

int RobotModule::LoadFromFile(QString p_FileName)
{
	qDebug() << "LoadField " << p_FileName;

	if (field->loadFromFile(p_FileName) != 0)
		return 1;

	startField = field->Clone();
	field->dropWasEdit();

	QFileInfo fi(p_FileName);
	QString name = fi.fileName();

	QString Title = trUtf8("Robot") + " - " + name;
	m_mainWidget->setWindowTitle(Title);

	RobotModule::robotSettings()->setValue("Robot/SFF", p_FileName);
	field->drawField(FIELD_SIZE_SMALL);
	qDebug() << "File " << p_FileName ;

	return 0;
}

mordol's avatar
mordol committed
938
void RobotModule::editEnv()
939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017
{
	if (field->isEditMode()) {
		reset(); //reset to normal mode
		setWindowSize();
		return;
	}
	startField->setModeFlag(NEDIT_MODE);

	view->showButtons(true);
	view->repaint();
	reset();
	field->setMode(NEDIT_MODE);
	startField->setModeFlag(NORMAL_MODE);

	setWindowSize();
	reloadSettings(robotSettings(), QStringList());
	field->update();
}

void RobotModule::createEmptyField(int rows, int cols)
{
	Q_UNUSED(cols);
	Q_UNUSED(rows);
	field->createField(7, 7);
	field->setRoboPos(0, 0);
	field->createRobot();
	startField = field->Clone();
	field->drawField(robotSettings()->value("Robot/CellSize", FIELD_SIZE_SMALL).toInt());

	mainWidget()->setWindowTitle(QString::fromUtf8("Робот - нет файла"));
	field->dropWasEdit();
}

bool RobotModule::isSafeToQuit()
{
	if (field->WasEdit()) {
		QMessageBox::StandardButton r;

		QMessageBox messageBox(
			QMessageBox::Question,
			trUtf8("Робот"),
			trUtf8("Сохранить изменения?"),
			QMessageBox::NoButton, mainWidget()
		);

		QPushButton *btnSave = messageBox.addButton(trUtf8("Да"),
			QMessageBox::AcceptRole);
		QPushButton *btnDiscard = messageBox.addButton(trUtf8("Нет"),
			QMessageBox::DestructiveRole);
		QPushButton *btnCancel = messageBox.addButton(trUtf8("Отмена"),
			QMessageBox::RejectRole);

		messageBox.setDefaultButton(btnSave);
		messageBox.exec();

		if (messageBox.clickedButton() == btnSave) {
			r = QMessageBox::Save;
		}

		if (messageBox.clickedButton() == btnDiscard) {
			r = QMessageBox::Discard;
		}

		if (messageBox.clickedButton() == btnCancel) {
			r = QMessageBox::Cancel;
		}

		if (r == QMessageBox::Save) {
			saveEnv();
		}

		if (r == QMessageBox::Cancel) {
			return false;
		}
	}

	return true;
}

mordol's avatar
Robot  
mordol committed
1018
void RobotModule::loadEnv()
1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092
{
	if (field->WasEdit()) {
		if (QMessageBox::question(
					mainWidget(), "",
					QString::fromUtf8("Сохранить изменения?"),
					QMessageBox::Yes, QMessageBox::No, 0
				) == QMessageBox::Yes
		) {
			saveEnv();
		}
	}

	QString RobotFile = QFileDialog::getOpenFileName(
		mainWidget(),
		QString::fromUtf8("Открыть файл"),
		curDir, "(*.fil)"
	);

	qDebug() << "CurDir" << curDir;

	QFileInfo info(RobotFile);
	QDir dir = info.absoluteDir();

	curDir = dir.path();
	robotSettings()->setValue("Robot/Dir", QVariant(curDir));

	if (RobotFile.isEmpty())
		return;

	if (LoadFromFile(RobotFile) != 0) { //Get troubles when loading env.
		QMessageBox::information(
			mainWidget(), "",
			QString::fromUtf8("Ошибка открытия файла! ") + RobotFile,
			0, 0, 0
		);
		return;
	}

	updateLastFiles(RobotFile);

	setWindowSize();
	view->setWindowTitle(trUtf8("Робот  - ") + info.baseName());
	robotSettings()->setValue("Robot/SFF", QVariant(RobotFile));
}

void RobotModule::resetEnv()
{
	reset();
}

void RobotModule::save2png()
{
	QString RobotFile = QFileDialog::getSaveFileName(
		mainWidget(),
		QString::fromUtf8("Сохранить как изображение"),
		curPDir, "(*.png)"
	);

	QFileInfo info(RobotFile);
	QDir dir = info.absoluteDir();
	curPDir = dir.path();

	int cellSize = robotSettings()->value("Robot/CellSize", FIELD_SIZE_SMALL).toInt();
	float multip = robotSettings()->value("ImageSize", FIELD_SIZE_SMALL).toFloat() / cellSize;

	QImage image(field->width()*multip, field->height()*multip, QImage::Format_ARGB32_Premultiplied);
	QPainter painter(&image);
	field->render(&painter);
	image.save(RobotFile);
}

void RobotModule::prepareNewWindow()
{
	NewWindow = new QDialog(mainWidget());
Denis Khachko's avatar
Denis Khachko committed
1093 1094 1095
	QGridLayout *nwl = new QGridLayout;
	NewWindow->setLayout(nwl);
	NewWindow->setWindowModality(Qt::WindowModal);
1096 1097
	NewWindow->setWindowTitle(QString::fromUtf8("Новая обстановка"));
	QLabel *lKol = new QLabel(QString::fromUtf8("Количество:"), NewWindow, 0);
Denis Khachko's avatar
Denis Khachko committed
1098
	nwl->addWidget(lKol, 0, 0, 1, 2, Qt::AlignCenter);
1099 1100

	QLabel *lXSize = new QLabel(QString::fromUtf8("Столбцов"), NewWindow, 0);
Denis Khachko's avatar
Denis Khachko committed
1101
	nwl->addWidget(lXSize, 1, 1, 1, 1, Qt::AlignCenter);
1102 1103

	QLabel *lYSize = new QLabel(QString::fromUtf8("Строк"), NewWindow, 0);
Denis Khachko's avatar
Denis Khachko committed
1104
	nwl->addWidget(lYSize, 1, 0, 1, 1, Qt::AlignCenter);
1105 1106

	NewWindow->setFixedSize(250, 150);
1107

Denis Khachko's avatar
Denis Khachko committed
1108
	eXSizeEdit = new QSpinBox(NewWindow);
1109 1110 1111
	eXSizeEdit->setRange(1, MAX_COLUMNS);
	eXSizeEdit->setValue(9);

Denis Khachko's avatar
Denis Khachko committed
1112
	eYSizeEdit = new QSpinBox(NewWindow);
1113 1114
	eYSizeEdit->setRange(1, MAX_ROWS);
	eYSizeEdit->setValue(9);
1115

Denis Khachko's avatar
Denis Khachko committed
1116 1117
	nwl->addWidget(eYSizeEdit, 2, 0, 1, 1, Qt::AlignCenter);
	nwl->addWidget(eXSizeEdit, 2, 1, 1, 1, Qt::AlignCenter);
1118

Denis Khachko's avatar
Denis Khachko committed
1119
	QDialogButtonBox *buttonBox = new QDialogButtonBox(NewWindow);
1120

Denis Khachko's avatar
Denis Khachko committed
1121
	btnOK1 = buttonBox->addButton(QDialogButtonBox::Ok);
Denis Khachko's avatar
Denis Khachko committed
1122
	btnCancel1 = new QPushButton(trUtf8("Отмена"));
1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199
	buttonBox->addButton(btnCancel1, QDialogButtonBox::RejectRole);

	nwl->addWidget(buttonBox, 3, 0, 1, 2, Qt::AlignRight);
	connect(btnCancel1, SIGNAL(clicked()), NewWindow, SLOT(close()));
	connect(btnOK1, SIGNAL(clicked()), this, SLOT(createNewField()));
}

void RobotModule::createNewField()
{
	field->destroyField();
	field->destroyRobot();
	field->createField(eYSizeEdit->value(), eXSizeEdit->value());
	field->setRoboPos(0, 0);
	field->createRobot();
	startField = field->Clone();
	field->drawField(FIELD_SIZE_SMALL);

	mainWidget()->setWindowTitle(QString::fromUtf8("Робот - нет файла"));

	view->centerOn(field->m_height() / 2, field->m_width() / 2);
	NewWindow->close();

	if (!field->isEditMode())
		editEnv();

	view->update();
}

void RobotModule::newEnv()
{
	if (field->WasEdit()) {
		QMessageBox::StandardButton r;

		QMessageBox messageBox(
			QMessageBox::Question,
			trUtf8("Новая обстановка"),
			trUtf8("Сохранить текущую?"),
			QMessageBox::NoButton, mainWidget()
		);

		QPushButton *btnSave = messageBox.addButton(
			trUtf8("Сохранить"), QMessageBox::AcceptRole
		);
		QPushButton *btnDiscard = messageBox.addButton(
			trUtf8("Не сохранять"), QMessageBox::DestructiveRole
		);
		QPushButton *btnCancel = messageBox.addButton(
			trUtf8("Отмена"), QMessageBox::RejectRole
		);

		messageBox.setDefaultButton(btnSave);
		messageBox.exec();

		if (messageBox.clickedButton() == btnSave) {
			r = QMessageBox::Save;
		}

		if (messageBox.clickedButton() == btnDiscard) {
			r = QMessageBox::Discard;
		}

		if (messageBox.clickedButton() == btnCancel) {
			r = QMessageBox::Cancel;
		}

		if (r == QMessageBox::Save) {
			saveEnv();
		}

		if (r == QMessageBox::Cancel) {
			return;
		}
	}

	NewWindow->show();
}

mordol's avatar
mordol committed
1200
void RobotModule::saveEnv()
1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228
{
	QString RobotFile = QFileDialog::getSaveFileName(
		mainWidget(),
		QString::fromUtf8("Сохранить файл"),
		curDir, "(*.fil)"
	);

	QFileInfo info(RobotFile);
	QDir dir = info.absoluteDir();
	curDir = dir.path();
	robotSettings()->setValue("Robot/Dir", QVariant(curDir));
	if (RobotFile.contains("*") || RobotFile.contains("?")) {
		QMessageBox::information(0, "", trUtf8("Недопустимый символ в имени файла!"), 0, 0, 0);
		return;
	}

	if (RobotFile.right(4) != ".fil") {
		RobotFile += ".fil";
	}

	SaveToFile(RobotFile);

	RobotModule::robotSettings()->setValue("Robot/StartField/File", RobotFile);
	updateLastFiles(RobotFile);

	mainWidget()->setWindowTitle(trUtf8("Робот - ") + info.baseName());
}

mordol's avatar
mordol committed
1229
int RobotModule::SaveToFile(QString p_FileName)
1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241
{
	if (field->saveToFile(p_FileName) != 0) {
		QMessageBox::warning(0, tr("Robot"), QString::fromUtf8("Не удалось сохранить файл"));
		return 1;
	}

	return 0;
}


void RobotModule::createRescentMenu()
{
1242 1243 1244 1245
	QString sFiles = mySettings()->value("Robot/LastFiles").toString();
	QStringList lFiles = sFiles.split(';', QString::SkipEmptyParts);
	qDebug() << lFiles;

1246
	rescentMenu->clear();
1247
	rescentMenu->setEnabled(lFiles.count() > 0);
1248

1249 1250 1251 1252 1253
	for (int i = 0; i < lFiles.count(); i++) {
		rescentMenu->addAction(
			"&" + QString::number(i + 1) + " " + lFiles[i],
			this, SLOT(openRecent())
		);
1254 1255 1256
	}
}

Denis Khachko's avatar
Denis Khachko committed
1257
QSize RobotModule::minimumSize() const
1258 1259 1260 1261 1262 1263 1264
{
	return QSize(
		mySettings()->value("Robot/CellSize").toInt() * 3,
		mySettings()->value("Robot/CellSize", FIELD_SIZE_SMALL).toInt() * 3
	);
}

Denis Khachko's avatar
Denis Khachko committed
1265
void RobotModule::setWindowSize()
1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296
{
	QSize newSize = view->size();
	QRect baseFieldSize; //fieldSize in pixel. Zoom 1:1
	baseFieldSize.setHeight(field->rows()*mySettings()->value("Robot/CellSize", FIELD_SIZE_SMALL).toInt());
	baseFieldSize.setWidth(field->columns()*mySettings()->value("Robot/CellSize", FIELD_SIZE_SMALL).toInt());
	int editEnlarge = 0;

	if (field->isEditMode()) {
		editEnlarge = 1.8 * mySettings()->value("Robot/CellSize", FIELD_SIZE_SMALL).toInt();
	}

	view->setMinimumSize(minimumSize());

	if (baseFieldSize.height() < view->height()) {
		newSize.setHeight(baseFieldSize.height() + mySettings()->value("Robot/CellSize", FIELD_SIZE_SMALL).toInt() + editEnlarge);
	}

	if (baseFieldSize.width() < view->width()) {
		newSize.setWidth(baseFieldSize.width() + mySettings()->value("Robot/CellSize", FIELD_SIZE_SMALL).toInt() + editEnlarge);
	}

	if (baseFieldSize.height() > view->height() && field->rows() < 11) {
		newSize.setHeight(baseFieldSize.height() + mySettings()->value("Robot/CellSize", FIELD_SIZE_SMALL).toInt() + editEnlarge);

	}

	if (baseFieldSize.width() > view->width() && field->columns() < 17) {
		newSize.setWidth(baseFieldSize.width() + mySettings()->value("Robot/CellSize", FIELD_SIZE_SMALL).toInt() + editEnlarge);
	}

	view->setWindowSize(newSize);
1297 1298
}

1299
void RobotModule::openRecent()
1300
{
1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312
	QString RobotFile;
	{
		QAction *s = qobject_cast<QAction *>(sender());
		QString txt = s->text();
		int pos = txt.indexOf(' ', 2);
		if (pos < 0)
			return;
		RobotFile = txt.mid(pos + 1);
	}
	if (RobotFile.isEmpty())
		return;

1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325
	if (field->WasEdit()) {
		QMessageBox::StandardButton r;
		QMessageBox messageBox(
			QMessageBox::Question,
			tr("New field"),
			tr("Save current field?"),
			QMessageBox::NoButton, mainWidget()
		);

		QPushButton *btnSave = messageBox.addButton(tr("Save"),
			QMessageBox::AcceptRole);
		QPushButton *btnDiscard = messageBox.addButton(tr("Don't save"),
			QMessageBox::DestructiveRole);
1326 1327
		QPushButton *btnCancel = messageBox.addButton(tr("Cancel"),
			QMessageBox::RejectRole);
1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353

		messageBox.setDefaultButton(btnSave);
		messageBox.exec();

		if (messageBox.clickedButton() == btnSave) {
			r = QMessageBox::Save;
		}

		if (messageBox.clickedButton() == btnDiscard) {
			r = QMessageBox::Discard;
		}

		if (messageBox.clickedButton() == btnCancel) {
			r = QMessageBox::Cancel;
		}

		if (r == QMessageBox::Save) {
			saveEnv();
		}

		if (r == QMessageBox::Cancel) {
			return;
		}
	}

	if (LoadFromFile(RobotFile) != 0) {
1354 1355 1356 1357
		QMessageBox::warning(
			mainWidget(), "",
			QString::fromUtf8("Ошибка открытия файла '%1'!").arg(RobotFile)
		);
1358 1359 1360 1361
	}
	reset();
	view->setWindowSize(view->size());

1362
}
1363

1364
void RobotModule::updateLastFiles(QString newFile)
1365
{
1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378
	if (newFile.isEmpty())
		return;

	if (newFile.contains(';')) {
		static bool warned = false;
		if (!warned) {
			QMessageBox::information(
				mainWidget(), "",
				QString::fromUtf8("Силам добра противен символ ';' в имени файла!")
			);
			warned = true;
		}
		return;
1379
	}
1380 1381 1382 1383 1384 1385 1386 1387 1388

	QString sFiles = RobotModule::robotSettings()->value("Robot/LastFiles").toString();
	QStringList lFiles = sFiles.split(';', QString::SkipEmptyParts);
	if (!lFiles.contains(newFile)) {
		lFiles.prepend(newFile);
		lFiles = lFiles.mid(0, 11);
		sFiles = lFiles.join(QChar(';'));
		RobotModule::robotSettings()->setValue("Robot/LastFiles", sFiles);
		createRescentMenu();
1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400
	}
}

void RobotModule::updateRobot()
{
}

void RobotModule::getTimer()
{
	mutex.lock();
	field->update();
	view->update();
Alexander A. Maly's avatar
Alexander A. Maly committed
1401
	qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
1402 1403 1404 1405 1406
	mutex.unlock();
}

} // namespace ActorRobot