terminal_onesession.cpp 29.8 KB
Newer Older
victor's avatar
 
victor committed
1 2
#include "terminal_onesession.h"
#include "terminal.h"
3 4 5
#include <kumir2-libs/stdlib/kumirstdlib.hpp>
#include <kumir2-libs/extensionsystem/pluginmanager.h>
#include <kumir2/actorinterface.h>
Victor Yacovlev's avatar
Victor Yacovlev committed
6

7 8 9 10 11
#include <QPainter>
#include <QDebug>
#include <QApplication>
#include <QTimerEvent>
#include <QAction>
Victor Yacovlev's avatar
Victor Yacovlev committed
12

13 14 15

namespace Terminal
{
victor's avatar
 
victor committed
16

17 18 19 20 21 22
static const uint BodyPadding = 4u;
static const uint HeaderPadding = 4u;
static const uint LineWidth = 1u;
static const uint ShadowOffset = 4u;
static const uint SessionMargin = 4u;
static const uint InputCursorThickness = 2u;
23 24

static const unsigned int SelectionMask = 0xFF00;
victor's avatar
 
victor committed
25

26 27 28 29 30 31 32
OneSession::OneSession(int fixedWidth, const QString &fileName, QWidget *parent)
	: QObject(parent)
	, parent_(parent)
	, maxLineLength_(0u)
	, fileName_(fileName)
	, fixedWidth_(fixedWidth)
	, relayoutMutex_(new QMutex)
victor's avatar
 
victor committed
33
{
34 35 36 37
	inputLineStart_ = inputPosStart_ = -1;
	inputCursorPosition_ = -1;
	timerId_ = -1;
	inputCursorVisible_ = false;
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
//    QString defaultFontFamily = "Courier";
//#ifdef Q_WS_X11
//    defaultFontFamily = "DejaVu Sans Mono";
//#endif
//#ifdef Q_OS_WIN32
//    if (QSysInfo::WindowsVersion>=0x0080)
//        defaultFontFamily = "Consolas";
//#endif
//#ifdef Q_OS_MAC
//    defaultFontFamily = "Courier"; // TODO implement me
//#endif
//    int defaultFontSize = 12;
//    QFont fnt = font();
//    fnt.setFamily(defaultFontFamily);
//    fnt.setPointSize(defaultFontSize);
//    setFont(fnt);
54 55
	setFont(parent_->font());
	startTime_ = QDateTime::currentDateTime();
victor's avatar
 
victor committed
56 57 58 59 60
}

QSize OneSession::charSize() const
{

61 62
	QFontMetrics fm(font());
	return QSize(fm.width('m'), fm.height());
victor's avatar
 
victor committed
63 64
}

victor's avatar
 
victor committed
65 66
int OneSession::widthInChars(int realWidth) const
{
67 68
	QSize atom = charSize();
	return (realWidth - 2 * BodyPadding - LineWidth - ShadowOffset) / atom.width();
victor's avatar
 
victor committed
69 70
}

Victor Yacovlev's avatar
Victor Yacovlev committed
71 72
QString OneSession::fileName() const
{
73
	return fileName_.contains(".") ? fileName_ : QString();
Victor Yacovlev's avatar
Victor Yacovlev committed
74 75
}

Victor Yacovlev's avatar
Victor Yacovlev committed
76 77
int OneSession::flexibleWidth() const
{
78 79 80 81 82 83
	// TODO change to std::algorithms after MSVC2010 support drop
	int result = 0;
	Q_FOREACH (const QString &line, lines_) {
		result = qMax(result, line.length());
	}
	return result;
Victor Yacovlev's avatar
Victor Yacovlev committed
84 85
}

86
QSize OneSession::visibleSize() const
victor's avatar
 
victor committed
87
{
88 89 90 91 92 93 94 95
	const QRegion region = QRegion() +
		headerRect_ + mainTextRegion_ + footerRect_;
	QSize result = region.boundingRect().size();
	int visibleCharsInLine =
		-1 == fixedWidth()
		? flexibleWidth() : fixedWidth();
	result.rwidth() = qMax(result.rwidth(), charSize().width() * (visibleCharsInLine));
	return result;
victor's avatar
 
victor committed
96 97
}

victor's avatar
 
victor committed
98
QString OneSession::plainText(bool footer_header) const
victor's avatar
 
victor committed
99
{
100 101 102
	QString body = lines_.join("\n");
	QString header = headerText();
	QString footer = footerText();
103 104 105 106 107
	if (footer_header) {
		return header + "\n" + body + "\n" + footer + "\n";
	} else {
		return body;
	}
victor's avatar
 
victor committed
108

victor's avatar
 
victor committed
109 110
}

111 112
QSize OneSession::minimumSizeHint() const
{
113 114
	QFontMetrics headingFM(utilityFont());
	QFontMetrics mainFM(font());
115 116 117 118 119 120 121 122
	int minH = 2 * (headingFM.height() + BodyPadding + HeaderPadding) +
		mainFM.height();
	int minWidthInChars = fixedWidth_ == -1 ? 10 : fixedWidth_;
	int minW = charSize().width() * minWidthInChars;
	int headerWidth = qMin(400, headingFM.width(visibleHeader_));
	int footerWidth = qMin(400, headingFM.width(visibleFooter_));
	int maxHeadingWidth = qMax(headerWidth, footerWidth);
	return QSize(qMax(minW, maxHeadingWidth), minH);
123 124
}

125 126
void OneSession::updateSelectionFromVisibleToRealLines()
{
127 128 129 130 131 132 133 134 135 136
	QMutexLocker lock(relayoutMutex_.data());
	for (size_t visNum = 0; visNum < visibleLines_.size(); ++visNum) {
		const VisibleLine &visibleLine = visibleLines_.at(visNum);
		const LineProp &visibleProp = visibleLine.prop;
		LineProp &sourceProp = props_.at(visibleLine.sourceLineNumber);
		Q_ASSERT(visibleProp.size() == sourceProp.size());
		for (size_t x = visibleLine.from; x < visibleLine.to; ++x) {
			sourceProp[x] = visibleProp[x];
		}
	}
137 138
}

139
void OneSession::relayout(uint realWidth, size_t fromLine, bool headerAndFooter)
victor's avatar
 
victor committed
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
	QMutexLocker lock(relayoutMutex_.data());
	if (0 == fromLine) {
		maxLineLength_ = 0;
		visibleLines_.clear();
	} else {
		while (visibleLines_.size() > fromLine) {
			visibleLines_.pop_back();
		}
	}
	// 1. Main text
	Q_ASSERT((size_t) lines_.size() == props_.size());
	Q_ASSERT(lines_.size() == selectedLineEnds_.size());
	for (int i = fromLine; i < lines_.size(); i++) {
		QString text = lines_.at(i);
		LineProp prop = props_.at(i);
		bool *selectedEnd = &selectedLineEnds_[i];
		Q_ASSERT(text.length() == prop.size());
		uint charsInLine = text.length();
		uint charsInVisibleLine = fixedWidth_ == -1
			? widthInChars(realWidth)
			: fixedWidth_;
		uint visibleLinesCount = charsInVisibleLine <= charsInLine
			? 1u
			: 1u + charsInLine / charsInVisibleLine;

		uint currentOffset = 0u;

		for (uint visibleLineNo = 0;
			visibleLineNo < visibleLinesCount;
			visibleLineNo++) {
			VisibleLine vline(text,
				prop,
				selectedEnd,
				currentOffset,
				qMin(
					currentOffset + charsInVisibleLine,
					charsInLine
				),
				i
			);
			visibleLines_.push_back(vline);
			maxLineLength_ = qMax(maxLineLength_, charsInVisibleLine);
			currentOffset += charsInVisibleLine;
		}
	}
	uint top =
		QFontMetrics(utilityFont()).height() + HeaderPadding + BodyPadding;
	uint height = charSize().height() * visibleLines_.size();
	uint left = BodyPadding;
	uint width = charSize().width() * maxLineLength_;
	mainTextRegion_ = QRect(left, top, width, height);

	if (headerAndFooter) {

		// 2. Header
		visibleHeader_ = headerText();
		LineProp old = headerProp_;
		headerProp_.clear();
		for (int i = 0; i < visibleHeader_.length(); i++) {
			headerProp_.push_back(CS_Output);
			if (i < old.size()) {
				headerProp_[i] = old[i];
			}
		}
		headerRect_ = QRect(BodyPadding,
				0,
				QFontMetrics(utilityFont()).width(visibleHeader_),
				QFontMetrics(utilityFont()).height() + HeaderPadding);

		// 3. Footer
		visibleFooter_ = footerText();
		old = footerProp_;
		footerProp_.clear();
		for (int i = 0; i < visibleFooter_.length(); i++) {
			footerProp_.push_back(CS_Output);
			if (i < old.size()) {
				footerProp_[i] = old[i];
			}
		}
		footerRect_ = footerText().isEmpty()
			? QRect(BodyPadding,
				mainTextRegion_.bottom() + HeaderPadding + BodyPadding,
				0,
				0)
			: QRect(BodyPadding,
				mainTextRegion_.bottom() + HeaderPadding + BodyPadding,
				QFontMetrics(utilityFont()).width(visibleFooter_),
				QFontMetrics(utilityFont()).height());
	}
230 231
}

232
void OneSession::draw(QPainter &p, const QRect &dirtyRect) const
233
{
234
	QMutexLocker lock(relayoutMutex_.data());
235 236 237 238 239 240 241 242
//    p.save();
//    p.setPen(QColor(Qt::red));
//    p.drawRect(mainTextRegion_);
//    p.setPen(QColor(Qt::blue));
//    p.drawRect(headerRect_);
//    p.setPen(QColor(Qt::green));
//    p.drawRect(footerRect_);
//    p.restore();
243 244 245 246 247 248 249 250 251 252 253 254 255 256
	if (-1 != fixedWidth()) {
		int x = mainTextRegion_.left() + charSize().width() * fixedWidth();
		int y0 = headerRect_.top() - 3;
		int y1 = y0 + visibleSize().height() + 7;
		p.drawLine(x, y0, x, y1);
		p.save();
		p.setPen(QPen(parent_->palette().brush(QPalette::Shadow), 1));
		p.restore();
	}
	drawUtilityText(p, visibleHeader_, headerProp_, headerRect_.topLeft());
//    drawInputRect(p, 0);
	drawMainText(p, mainTextRegion_.topLeft(), dirtyRect);
	drawUtilityText(p, visibleFooter_, footerProp_, footerRect_.topLeft());
	drawCursor(p);
257
}
258

259 260
void OneSession::drawCursor(QPainter &p) const
{
261 262 263 264 265 266 267 268 269 270 271 272 273 274
	if (inputCursorVisible_) {
		const QSize atom = charSize();
		p.save();
		uint top = mainTextRegion_.top() +
			inputLineStart_ * atom.height() +
			InputCursorThickness
			;
		uint left = mainTextRegion_.left() +
			(inputPosStart_ + inputCursorPosition_) * atom.width();
		p.setPen(Qt::NoPen);
		p.setBrush(parent_->palette().brush(QPalette::Text));
		p.drawRect(left, top, InputCursorThickness, atom.height());
		p.restore();
	}
275 276 277
}

uint OneSession::drawUtilityText(
278 279 280 281 282
	QPainter &p,
	const QString &text,
	const LineProp &prop,
	const QPoint &topLeft
) const
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
	Q_ASSERT(text.length() == prop.size());
	p.save();
	p.setFont(utilityFont());
	const QBrush selectionBackroundBrush = parent_->palette().brush(
			parent_->hasFocus() ? QPalette::Active : QPalette::Inactive,
			QPalette::Highlight
		);
	const QColor selectedTextColor = parent_->palette().brush(
			parent_->hasFocus() ? QPalette::Active : QPalette::Inactive,
			QPalette::HighlightedText
		).color();
	const QFontMetrics fm(utilityFont());
	const uint height = fm.height();
	uint xx = topLeft.x();
	for (int i = 0; i < text.length(); i++) {
		const QChar ch = text.at(i);
		const CharSpec cs = prop[i];
		const uint cw = fm.width(ch);
		if (cs & SelectionMask) {
			p.setPen(Qt::NoPen);
			p.setBrush(selectionBackroundBrush);
			p.drawRect(xx, topLeft.y(), cw, height);
			p.setPen(selectedTextColor);
			qDebug() << "UT has selection";
		} else {
			p.setPen(QColor(Qt::darkGray));
		}
		p.drawText(xx, topLeft.y() + height, QString(ch));
		xx += cw;
	}
	p.restore();
	return  height;
316
}
317

318 319
void OneSession::drawInputRect(QPainter &p, const uint mainTextY) const
{
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
	if (inputCursorPosition_ != -1) {
		p.save();
		const QSize atom = charSize();
		const QRect highlightRect(
			BodyPadding + inputPosStart_ * atom.width(),
			mainTextY + inputLineStart_ * atom.height(),
			parent_->width() - (inputPosStart_ * atom.width()) - 2 * BodyPadding,
			atom.height() + 4
		);

		// Prepare a brush gradient based on current highlight color
		QLinearGradient gr(QPointF(0, 0), QPointF(0, 1));
		gr.setCoordinateMode(QGradient::ObjectBoundingMode);
		QColor c1 = QColor("green").lighter();
		c1.setAlpha(32);
		QColor c2 = QColor("green").lighter();
		gr.setColorAt(0, c1);
		gr.setColorAt(1, c2);

		// Draw a rect
		p.setBrush(gr);
		p.setPen(Qt::NoPen);
		p.drawRect(highlightRect);

		// Draw borders
		p.setPen(QColor("green"));
		p.drawLine(highlightRect.topLeft(),
			highlightRect.topRight());
		p.drawLine(highlightRect.bottomLeft(),
			highlightRect.bottomRight());
		p.drawLine(highlightRect.bottomLeft(),
			highlightRect.topLeft());
		p.drawLine(highlightRect.bottomRight(),
			highlightRect.topRight());
		p.restore();
	}
356
}
Victor Yacovlev's avatar
Victor Yacovlev committed
357

358
uint OneSession::drawMainText(QPainter &p, const QPoint &topLeft, const QRect &dirtyRect) const
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 424 425 426 427 428 429 430 431 432 433 434 435 436
	const QSize atom = charSize();
	const QBrush selectionBackroundBrush = parent_->palette().brush(
			parent_->hasFocus() ? QPalette::Active : QPalette::Inactive,
			QPalette::Highlight
		);
	const QColor selectedTextColor = parent_->palette().brush(
			parent_->hasFocus() ? QPalette::Active : QPalette::Inactive,
			QPalette::HighlightedText
		).color();
	QColor mainColor(Qt::black);
	QColor inputColor(Qt::blue);
	QColor errorColor(Qt::red);
	const QColor bgColor = parent_->palette().color(QPalette::Base);
	int darkness = bgColor.red() + bgColor.green() + bgColor.blue();
	if (darkness / 3 <= 127) {
		// Invert color for dark backround
		mainColor = QColor(Qt::white);
		inputColor = QColor("lime");
		errorColor = QColor("orangered");
	}
	p.save();
	p.setFont(font_);
	for (size_t i = 0; i < visibleLines_.size(); i++) {
		uint xx = topLeft.x();
		uint yy = topLeft.y() + i * atom.height() + atom.height();
		const VisibleLine &vline = visibleLines_.at(i);
		const QString &text = vline.text;
		const LineProp &prop = vline.prop;

		QRect thisLineFullWidthRect;
		if (-1 == fixedWidth()) {
			thisLineFullWidthRect = QRect(0, yy - atom.height(),
					text.length() * atom.width(),
					atom.height());
		} else {
			thisLineFullWidthRect = QRect(0, yy - atom.height(),
					dirtyRect.width(),
					atom.height());
		}
		if (!dirtyRect.intersects(thisLineFullWidthRect)) {
			continue;
		}
		size_t from = vline.from;
		size_t to = vline.to;
		if (-1 == fixedWidth()) {
			from = 0;
			to = text.length();
		}
		for (size_t j = from; j < to; j++) {
			const QChar symbol = text.at(j);
			const CharSpec spec = prop.at(j);
			if (spec & SelectionMask) {
				p.setPen(Qt::NoPen);
				p.setBrush(selectionBackroundBrush);
				p.drawRect(xx, yy - atom.height(), atom.width(), atom.height());
				qDebug() << "MT has selection";
			}
			if (spec & SelectionMask) {
				p.setPen(selectedTextColor);
			} else if (spec == CS_Error || spec == CS_InputError) {
				p.setPen(errorColor);
			} else if (spec == CS_Input) {
				p.setPen(inputColor);
			} else {
				p.setPen(mainColor);
			}
			p.drawText(xx, yy, QString(symbol));
			xx += atom.width();
		}
		if (vline.text.length() == 0 && *vline.endSelected) {
			p.setPen(Qt::NoPen);
			p.setBrush(selectionBackroundBrush);
			p.drawRect(xx, yy - atom.height(), atom.width() / 2, atom.height());
		}
	}
	p.restore();
	return atom.height() * visibleLines_.size();
victor's avatar
 
victor committed
437 438
}

439

440 441
void OneSession::clearSelection()
{
442 443 444 445 446 447 448 449 450 451 452 453 454 455
	for (int x = 0; x < headerProp_.size(); x++) {
		headerProp_[x] = Terminal::CharSpec(headerProp_[x] & 0xFF);
	}
	for (int x = 0; x < footerProp_.size(); x++) {
		footerProp_[x] = Terminal::CharSpec(footerProp_[x] & 0xFF);
	}
	for (size_t y = 0; y < props_.size(); y++) {
		LineProp &lineProp = props_[y];
		for (int x = 0; x < lineProp.size(); x++) {
			lineProp[x] = Terminal::CharSpec(lineProp[x] & 0xFF);
		}
		selectedLineEnds_[y] = false;
	}
	relayout(parent_->width() - 2 * SessionMargin, 0, true);
456 457 458 459
}

bool OneSession::hasSelectedText() const
{
460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478
	for (int x = 0; x < headerProp_.size(); x++) {
		if (headerProp_[x] & SelectionMask) {
			return true;
		}
	}
	for (int x = 0; x < footerProp_.size(); x++) {
		if (footerProp_[x] & SelectionMask) {
			return true;
		}
	}
	for (int y = 0; y < lines_.size(); y++) {
		const LineProp &lineProp = props_[y];
		for (int x = 0; x < lineProp.size(); x++) {
			if (lineProp[x] & SelectionMask) {
				return true;
			}
		}
	}
	return false;
479 480
}

481 482
bool OneSession::isEditable() const
{
483
	return inputCursorPosition_ != -1;
484 485
}

486 487
QString OneSession::selectedText() const
{
488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519
	QString result;
	for (int x = 0; x < headerProp_.size(); x++) {
		if (headerProp_[x] & SelectionMask) {
			result += visibleHeader_[x];
		}
	}
	if (result.length() > 0) {
		result += "\n";
	}
	for (int y = 0; y < lines_.size(); y++) {
		QString thisLineText;
		const QString &thisLine = lines_[y];
		const LineProp &thisProp = props_[y];
		for (int x = 0; x < thisLine.length(); x++) {
			if (thisProp[x] & SelectionMask) {
				thisLineText += thisLine[x];
			}
		}
		result += thisLineText;
		if (selectedLineEnds_[y]) {
			result += "\n";
		}
	}
	if (result.length() > 0 && visibleFooter_.length() > 0 && !result.endsWith("\n")) {
		result += "\n";
	}
	for (int x = 0; x < footerProp_.size(); x++) {
		if (footerProp_[x] & SelectionMask) {
			result += visibleFooter_[x];
		}
	}
	return result;
520 521
}

Victor Yacovlev's avatar
Victor Yacovlev committed
522
struct Chunk {
523 524 525 526 527
	QString text;
	bool italic;
	uint color;
	QString data;
	CharSpec spec;
Victor Yacovlev's avatar
Victor Yacovlev committed
528 529
};

530 531 532 533 534
static QString lineToRtf(const QString &text,
	const bool utilText,
	const LineProp &prop,
	size_t from, size_t to
)
535
{
Victor Yacovlev's avatar
Victor Yacovlev committed
536

537

538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593
	QList<Chunk> result;
	QString rtf;

	// Split text into chunks of various formats
	for (size_t i = from; i < to; i++) {
		if (result.isEmpty()) {
			// Create first empty chunk of text
			Chunk chunk;
			chunk.italic = utilText;
			chunk.color = utilText ? 4u : 0u;
			if (prop[i] & CS_Input) {
				chunk.color = 3u;
			} else if (prop[i] & CS_Error || prop[i] & CS_InputError) {
				chunk.color = 2u;
			}
			chunk.text += text.at(i);
			chunk.spec = prop[i];
			result.push_back(chunk);
		} else if (result.last().spec == prop[i]) {
			// Continue the same format chunk of text
			Chunk &chunk = result.last();
			chunk.text += text.at(i);
		} else {
			// Make new format chunk of text
			Chunk chunk;
			chunk.italic = utilText;
			chunk.color = utilText ? 4u : 0u;
			if (prop[i] & CS_Input) {
				chunk.color = 3u;
			} else if (prop[i] & CS_Error || prop[i] & CS_InputError) {
				chunk.color = 2u;
			}
			chunk.text += text.at(i);
			chunk.spec = prop[i];
			result.push_back(chunk);
		}
	}

	// Make RTF data for chunks
	for (int i = 0; i < result.size(); i++) {
		rtf += "{";
		const Chunk &chunk = result[i];
		if (chunk.color) {
			rtf += "\\cf" + QString::number(chunk.color).toLatin1();
		}
		if (chunk.italic) {
			rtf += "\\i";
		}
		if (chunk.italic || chunk.color) {
			rtf += " ";
		}
		rtf += chunk.text;
		rtf += "}";
	}

	return rtf;
594 595 596 597
}

void OneSession::selectAll()
{
598 599 600 601 602 603 604 605 606 607 608 609 610 611 612
	for (int i = 0; i < headerProp_.size(); i++) {
		headerProp_[i] = CharSpec(headerProp_[i] | SelectionMask);
	}
	for (int i = 0; i < footerProp_.size(); i++) {
		footerProp_[i] = CharSpec(footerProp_[i] | SelectionMask);
	}
	for (size_t l = 0; l < props_.size(); l++) {
		LineProp &lp = props_[l];
		for (int i = 0; i < lp.size(); i++) {
			lp[i] = CharSpec(lp[i] | SelectionMask);
		}
		selectedLineEnds_[l] = true;
	}
	relayout(parent_->width() - 2 * SessionMargin, 0, true);
	emit updateRequest();
613 614 615 616
}

QString OneSession::selectedRtf() const
{
617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681
	QString result;
	{
		// Header
		int from = -1;
		int to = -1;
		for (int i = 0; i < headerProp_.size(); i++) {
			if (headerProp_[i] & SelectionMask) {
				if (from == -1) {
					from = i;
				}
				to = i + 1;
			}
		}
		if (from != -1 && to != -1) {
			result += lineToRtf(visibleHeader_, true, headerProp_, from, to);
			result += "\\par\r\n";
		}

	}
	{
		// Main text
		for (int l = 0; l < lines_.size(); l++) {
			const QString &text = lines_.at(l);
			const LineProp &prop = props_.at(l);

			int from = -1;
			int to = -1;

			for (int i = 0; i < prop.size(); i++) {
				if (prop[i] & SelectionMask) {
					if (from == -1) {
						from = i;
					}
					to = i + 1;
				}
			}
			if (from != -1 && to != -1) {
				result += lineToRtf(text, false, prop, from, to);
			}
			if (selectedLineEnds_[l]) {
				result += "\\par\r\n";
			}
		}
	}
	{
		// Footer
		int from = -1;
		int to = -1;
		for (int i = 0; i < footerProp_.size(); i++) {
			if (footerProp_[i] & SelectionMask) {
				if (from == -1) {
					from = i;
				}
				to = i + 1;
			}
		}
		if (from != -1 && to != -1) {
			if (!result.isEmpty() && !result.endsWith("\\par\r\n")) {
				result += "\\par\r\n";
			}
			result += lineToRtf(visibleFooter_, true, footerProp_, from, to);
		}

	}
	return result;
682 683 684 685
}

void OneSession::triggerTextSelection(const QPoint &fromPos, const QPoint &toPos)
{
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
	clearSelection();
	const QFontMetrics mfm(font());
	const QFontMetrics ufm(utilityFont());
	const int fromY = qMin(fromPos.y(), toPos.y());
	const int toY = qMax(fromPos.y(), toPos.y());
	const int fromX = qMin(fromPos.x(), toPos.x());
	const int toX = qMax(fromPos.x(), toPos.x());

	// Header
	if (fromY <= headerRect_.bottom() && toY >= headerRect_.top()) {
		int fromChar = 0;
		int toChar = visibleHeader_.length();
		if (fromY > headerRect_.top()) {
			fromChar = (fromX - headerRect_.left()) / ufm.width('m');
		}
		if (toY <= headerRect_.bottom()) {
			toChar = (toX - headerRect_.left()) / ufm.width('m');
		}
		fromChar = qMax(0, fromChar);
		toChar = qMin(visibleHeader_.length(), toChar);
		for (int i = fromChar; i < toChar; i++) {
			headerProp_[i] = Terminal::CharSpec(headerProp_[i] | SelectionMask);
		}
	}

	// Footer
	if (fromY <= footerRect_.bottom() && toY >= footerRect_.top()) {
		int fromChar = 0;
		int toChar = visibleFooter_.length();
		if (fromY > footerRect_.top()) {
			fromChar = (fromX - footerRect_.left()) / ufm.width('m');
		}
		if (toY <= footerRect_.bottom()) {
			toChar = (toX - footerRect_.left()) / ufm.width('m');
		}
		fromChar = qMax(0, fromChar);
		toChar = qMin(visibleFooter_.length(), toChar);
		for (int i = fromChar; i < toChar; i++) {
			footerProp_[i] = Terminal::CharSpec(footerProp_[i] | SelectionMask);
		}
	}

	// Main text
	for (size_t l = 0; l < visibleLines_.size(); l++) {
		VisibleLine &line = visibleLines_[l];
		const QString thisLineText = line.text.mid(line.from, line.to - line.from);
		const QRect thisLineRect = QRect(
				mainTextRegion_.left(),
				mainTextRegion_.top() + l * mfm.height(),
				mfm.width(thisLineText),
				mfm.height()
			);
		if (fromY <= thisLineRect.bottom() && toY >= thisLineRect.top()) {
			size_t fromChar = line.from;
			size_t toChar = line.to;
			if (fromY > thisLineRect.top()) {
				fromChar = line.from + (fromX - thisLineRect.left()) / mfm.width('m');
			}
			if (toY <= thisLineRect.bottom()) {
				toChar = line.from + (toX - thisLineRect.left()) / mfm.width('m');
			}
			if (toY > thisLineRect.bottom() || toX > thisLineRect.right()) {
				*line.endSelected = true;
			}
			fromChar = qMax(line.from, fromChar);
			toChar = qMin(line.to, toChar);
			for (size_t i = fromChar; i < toChar; i++) {
				line.prop[i] =
					Terminal::CharSpec(line.prop.at(i) | SelectionMask)
					;
			}
		}
	}
	updateSelectionFromVisibleToRealLines();
	emit updateRequest();
761 762
}

763

764 765
QPoint OneSession::cursorPositionByVisiblePosition(const QPoint &pos) const
{
766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782
	const QSize atom = charSize();

	int offsetX = BodyPadding;
	int offsetY = 2 * HeaderPadding + 2 * atom.height() + BodyPadding;

	const QPoint bodyPos = pos - QPoint(offsetX, offsetY);

	QPoint cursor(bodyPos.x() / atom.width(), bodyPos.y() / atom.height());
	cursor.setY(qMin(lines_.size() - 1,
			qMax(0,
				cursor.y()))
	);
	cursor.setX(qMin(lines_.isEmpty() ? 0 : lines_.at(cursor.y()).length(),
			qMax(0,
				cursor.x())
		));
	return cursor;
783 784 785 786
}

QString OneSession::headerText() const
{
787 788 789 790 791
	return tr(">> %1:%2:%3 - %4 - Process started")
		.arg(startTime_.time().hour(), 2, 10, QChar(' '))
		.arg(startTime_.time().minute(), 2, 10, QChar('0'))
		.arg(startTime_.time().second(), 2, 10, QChar('0'))
		.arg(fileName_);
792 793 794 795
}

QString OneSession::footerText() const
{
796
	QString res = endTime_.isValid()
797 798 799 800 801 802
		? tr(">> %1:%2:%3 - %4 - Process finished")
		.arg(endTime_.time().hour(), 2, 10, QChar(' '))
		.arg(endTime_.time().minute(), 2, 10, QChar('0'))
		.arg(endTime_.time().second(), 2, 10, QChar('0'))
		.arg(fileName_)
		: "";
803 804 805 806 807
	if (startTime_.isValid() && endTime_.isValid()) {
		double dt = startTime_.msecsTo(endTime_) * 1e-3;
		res += " " + QString::number(dt, 'f', 3) + " ";
	}
	return res;
808 809 810 811
}

QFont OneSession::utilityFont() const
{
812 813 814 815
	QFont smallFont = font_;
	smallFont.setPointSize(font_.pointSize() - 2);
	smallFont.setItalic(true);
	return smallFont;
816 817
}

818
void OneSession::output(const QString &text, const CharSpec cs)
victor's avatar
 
victor committed
819
{
820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838
	size_t relayoutStartLine = lines_.size() > 0 ? lines_.size() - 1 : 0;
	int curLine = lines_.size() - 1;
	int curCol = lines_.isEmpty() ? 0 : lines_[curLine].length();
	for (int i = 0; i < text.length(); i++) {
		bool newLine = curLine < 0 || text[i] == '\n' || (fixedWidth_ != -1 && curCol >= fixedWidth_);
		if (newLine) {
			lines_.append("");
			props_.push_back(LineProp());
			selectedLineEnds_.append(false);
			curLine ++;
			curCol = 0;
		}
		if (text[i].unicode() >= 32) {
			lines_[curLine] += text[i];
			props_[curLine].push_back(cs);
		}
	}
	relayout(parent_->width() - 2 * SessionMargin, relayoutStartLine, false);
	emit updateRequest();
victor's avatar
 
victor committed
839 840 841 842
}

void OneSession::input(const QString &format)
{
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
	inputFormat_ = format;
	if (lines_.isEmpty()) {
		lines_ << "";
		props_.push_back(LineProp());
		selectedLineEnds_ << false;
	}
	inputLineStart_ = lines_.size() - 1;
	inputPosStart_ = 0;
	if (!lines_.isEmpty()) {
		inputPosStart_ = lines_.last().length();
	}
	inputCursorPosition_ = 0;
	inputCursorVisible_ = true;
	QString msg;
	if (format.length() == 1 && format.at(0) == 'w') {
		msg = tr("INPUT raw data to console stream");
	} else {
		msg += tr("INPUT ");
		QStringList fmts = format.split(";", QString::SkipEmptyParts);
		for (int i = 0; i < fmts.size(); i++) {
			if (i > 0) {
				msg += ", ";
			}
			if (fmts[i][0] == 's') {
				msg += tr("string");
			} else if (fmts[i][0] == 'i') {
				msg += tr("integer");
			} else if (fmts[i][0] == 'r') {
				msg += tr("real");
			} else if (fmts[i][0] == 'c') {
				msg += tr("charect");
			} else if (fmts[i][0] == 'b') {
				msg += tr("boolean");
			} else if (fmts[i].contains("::")) {
				QStringList typeName = fmts[i].split("::", QString::KeepEmptyParts);
				msg += typeName[2];
			}

		}
		msg += ".";
	}
	emit message(msg);
	timerId_ = startTimer(QApplication::cursorFlashTime() / 2);
	emit updateRequest();
victor's avatar
 
victor committed
887 888 889 890
}

void OneSession::timerEvent(QTimerEvent *e)
{
891 892 893
	inputCursorVisible_ = !inputCursorVisible_;
	emit updateRequest();
	e->accept();
victor's avatar
 
victor committed
894 895 896 897
}

void OneSession::changeCursorPosition(quint16 pos)
{
898 899 900
	inputCursorPosition_ = pos;
	inputCursorVisible_ = true;
	emit updateRequest();
victor's avatar
 
victor committed
901 902 903 904
}

void OneSession::changeInputText(const QString &text)
{
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
	lines_ = lines_.mid(0, inputLineStart_ + 1);
	size_t relayoutStartLine = lines_.size() > 0 ? lines_.size() - 1 : 0;
	props_.resize(inputLineStart_ + 1);
	selectedLineEnds_ = selectedLineEnds_.mid(0, inputLineStart_ + 1);
	if (!lines_.isEmpty()) {
		lines_[lines_.size() - 1] = lines_[lines_.size() - 1].mid(0, inputPosStart_);
		props_[props_.size() - 1].resize(inputPosStart_);
	}
	int curCol = inputPosStart_;
	int curLine = lines_.size() - 1;
	for (int i = 0; i < text.length(); i++) {
		bool newLine = curLine < 0 || (fixedWidth_ != -1 && curCol >= fixedWidth_);
		if (newLine) {
			lines_.append("");
			props_.push_back(LineProp());
			selectedLineEnds_.append(false);
			curLine ++;
			curCol = 0;
		}
		if (text[i].unicode() >= 32) {
			lines_[curLine] += text[i];
			props_[curLine].push_back(CS_Input);
		}
	}
	relayout(parent_->width() - 2 * SessionMargin, relayoutStartLine, false);
	emit updateRequest();
victor's avatar
 
victor committed
931 932 933 934
}

void OneSession::tryFinishInput()
{
935 936 937 938 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 1018 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
	QString text;
	for (int i = inputLineStart_; i < lines_.size(); i++) {
		if (i == inputLineStart_) {
			text += lines_[i].mid(inputPosStart_);
		} else {
			text += lines_[i];
		}
	}
	QVector<bool> errmask = QVector<bool>(text.length(), false);
	QVariantList result;
	Kumir::IO::InputStream stream(text.toStdWString());
	bool conversionError = false;
	int conversionErrorStart = -1;
	int conversionErrorLength = 0;
	bool ignoreGarbageError = false;
	QString conversionErrorType = "";
	const QStringList &formats = inputFormat_.split(";", QString::SkipEmptyParts);
	for (int i = 0; i < formats.size(); i++) {
		QString format = formats[i];
		if (format[0] == 'i') {
			int value = Kumir::IO::readInteger(stream);
			result << value;
		} else if (format[0] == 'r') {
			double value = Kumir::IO::readReal(stream);
			result << value;
		} else if (format[0] == 'b') {
			bool value = Kumir::IO::readBool(stream);
			result << value;
		} else if (format[0] == 'c') {
			Kumir::Char value = Kumir::IO::readChar(stream);
			result << QChar(value);
		} else if (format[0] == 's') {
			Kumir::String value = Kumir::IO::readLine(stream);
			result << QString::fromStdWString(value);
		} else if (format[0] == 'n') {
			Kumir::IO::readLine(stream);
			result << QChar('\n');
		} else if (format[0] == 'w') { // raw data
			result << QString(text + "\n");
			ignoreGarbageError = true;
		} else if (format.contains("::")) {
			const QStringList typeName = format.split("::", QString::KeepEmptyParts);
			const QByteArray moduleAsciiName = typeName[0].toLatin1();
			const QByteArray classAsciiName = typeName[1].toLatin1();
			const QString &className  = typeName[2];
			QList<ExtensionSystem::KPlugin *> plugins =
				ExtensionSystem::PluginManager::instance()->loadedPlugins("Actor*");
			Shared::ActorInterface *actor = 0;
			for (int i = 0; i < plugins.size(); i++) {
				actor = qobject_cast<Shared::ActorInterface *>(plugins[i]);
				if (actor) {
					if (actor->asciiModuleName() == moduleAsciiName) {
						break;
					} else {
						actor = 0;
					}
				}
			}
			if (actor) {
				stream.skipDelimiters(Kumir::String());
				conversionErrorStart = stream.currentPosition();
				QString lexem = QString::fromStdWString(Kumir::IO::readString(stream));
				QVariant value;
				if (!stream.hasError()) {
					value = actor->customValueFromString(classAsciiName, lexem);
					if (!value.isValid()) {
						conversionError = true;
						conversionErrorLength = lexem.length();
						conversionErrorType   = className;
						break;
					}
				}
				result << value;
			} else {
				result << QVariant::Invalid;
			}
		}
		if (stream.hasError() || stream.currentPosition() == text.length()) {
			break;
		}
	}
	bool hasError    = false;
	int  errorStart  = -1;
	int  errorLength = 0;
	QString errorMessage;

	if (stream.hasError()) {
		hasError = true;
		Kumir::String errorText;
		stream.getError(errorText, errorStart, errorLength);
		errorMessage = QString::fromStdWString(errorText);
	}

	if (conversionError) {
		hasError = true;
		errorStart = conversionErrorStart;
		errorLength = conversionErrorLength;
		errorMessage = tr("INPUT ERROR: Not a '%1' value").arg(conversionErrorType);
	}

	if (stream.currentPosition() < text.length()) {
		const QString remainder = text.mid(stream.currentPosition());
		if (!ignoreGarbageError && !remainder.trimmed().isEmpty() && !hasError) {
			hasError = true;
			errorStart = stream.currentPosition();
			errorLength = remainder.length();
			errorMessage = tr("INPUT ERROR: Extra input");
		}
	}

	if (hasError) {
		emit message(errorMessage);
		for (int i = 0; i < errorLength; i++) {
			errmask[errorStart + i] = true;
		}
		int curLine = inputLineStart_;
		int curCol = inputPosStart_;
		LineProp &lp = props_[curLine];
		for (int i = 0; i < text.length(); i++) {
			bool newLine = curLine < 0 || (fixedWidth_ != -1 && curCol >= fixedWidth_);
			if (newLine) {
				curLine ++;
				lp = props_[curLine];
				curCol = 0;
			} else {
				if (errmask[i]) {
					lp[curCol] = CS_InputError;
				} else {
					lp[curCol] = CS_Input;
				}
				curCol ++;
			}
		}
		emit updateRequest();
	} else {
		inputLineStart_ = inputPosStart_ = inputCursorPosition_ = -1;
		output("\n", CS_Output);
		emit message("");
		emit inputDone(result);
		emit updateRequest();
	}
victor's avatar
 
victor committed
1076 1077 1078 1079
}

void OneSession::error(const QString &message)
{
1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090
	inputLineStart_ = inputPosStart_ = inputCursorPosition_ = -1;
	size_t relayoutStartLine = lines_.size() > 0 ? lines_.size() - 1 : 0;
	lines_.append(tr("RUNTIME ERROR: %1").arg(message));
	props_.push_back(LineProp());
	selectedLineEnds_.append(false);
	for (int i = 0; i < lines_.last().size(); i++) {
		props_[props_.size() - 1].push_back(CS_Error);
	}
	endTime_ = QDateTime::currentDateTime();
	relayout(parent_->width() - 2 * SessionMargin, relayoutStartLine, true);
	emit updateRequest();
victor's avatar
 
victor committed
1091 1092 1093 1094
}

void OneSession::terminate()
{
1095 1096 1097 1098 1099 1100 1101 1102
	size_t relayoutStartLine = lines_.size();
	endTime_ = QDateTime::currentDateTime();
	if (timerId_ != -1) {
		killTimer(timerId_);
	}
	inputLineStart_ = inputPosStart_ = inputCursorPosition_ = -1;
	relayout(parent_->width() - 2 * SessionMargin, relayoutStartLine, true);
	emit updateRequest();
victor's avatar
 
victor committed
1103 1104 1105 1106
}

void OneSession::finish()
{
1107 1108 1109 1110 1111
	size_t relayoutStartLine = lines_.size();
	endTime_ = QDateTime::currentDateTime();
	inputLineStart_ = inputPosStart_ = inputCursorPosition_ = -1;
	relayout(parent_->width() - 2 * SessionMargin, relayoutStartLine, true);
	emit updateRequest();
victor's avatar
 
victor committed
1112 1113 1114
}

} // namespace Terminal