File: CConsole.cpp

package info (click to toggle)
0ad 0.0.23.1-2
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 78,292 kB
  • sloc: cpp: 245,166; ansic: 200,249; python: 13,754; sh: 6,104; perl: 4,620; makefile: 977; xml: 810; java: 533; ruby: 229; erlang: 46; pascal: 30; sql: 21; tcl: 4
file content (695 lines) | stat: -rw-r--r-- 15,988 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
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
478
479
480
481
482
483
484
485
486
487
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
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
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
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
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
682
683
684
685
686
687
688
689
690
691
692
693
694
695
/* Copyright (C) 2016 Wildfire Games.
 * This file is part of 0 A.D.
 *
 * 0 A.D. is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * (at your option) any later version.
 *
 * 0 A.D. is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with 0 A.D.  If not, see <http://www.gnu.org/licenses/>.
 */

/*
 * Implements the in-game console with scripting support.
 */

#include "precompiled.h"
#include <wctype.h>

#include "CConsole.h"

#include "graphics/FontMetrics.h"
#include "graphics/ShaderManager.h"
#include "graphics/TextRenderer.h"
#include "gui/GUIutil.h"
#include "gui/GUIManager.h"
#include "lib/ogl.h"
#include "lib/sysdep/clipboard.h"
#include "lib/timer.h"
#include "lib/utf8.h"
#include "maths/MathUtil.h"
#include "network/NetClient.h"
#include "network/NetServer.h"
#include "ps/CLogger.h"
#include "ps/Filesystem.h"
#include "ps/GameSetup/Config.h"
#include "ps/Globals.h"
#include "ps/Hotkey.h"
#include "ps/Profile.h"
#include "ps/Pyrogenesis.h"
#include "renderer/Renderer.h"
#include "scriptinterface/ScriptInterface.h"

CConsole* g_Console = 0;

CConsole::CConsole()
{
	m_bToggle = false;
	m_bVisible = false;

	m_fVisibleFrac = 0.0f;

	m_szBuffer = new wchar_t[CONSOLE_BUFFER_SIZE];
	FlushBuffer();

	m_iMsgHistPos = 1;
	m_charsPerPage = 0;

	m_prevTime = 0.0;
	m_bCursorVisState = true;
	m_cursorBlinkRate = 0.5;

	InsertMessage("[ 0 A.D. Console v0.14 ]");
	InsertMessage("");
}

CConsole::~CConsole()
{
	delete[] m_szBuffer;
}


void CConsole::SetSize(float X, float Y, float W, float H)
{
	m_fX = X;
	m_fY = Y;
	m_fWidth = W;
	m_fHeight = H;
}

void CConsole::UpdateScreenSize(int w, int h)
{
	float height = h * 0.6f;
	SetSize(0, 0, w / g_GuiScale, height / g_GuiScale);
}


void CConsole::ToggleVisible()
{
	m_bToggle = true;
	m_bVisible = !m_bVisible;

	// TODO: this should be based on input focus, not visibility
	if (m_bVisible)
		SDL_StartTextInput();
	else
		SDL_StopTextInput();
}

void CConsole::SetVisible(bool visible)
{
	if (visible != m_bVisible)
		m_bToggle = true;
	m_bVisible = visible;
	if (visible)
	{
		m_prevTime = 0.0;
		m_bCursorVisState = false;
	}
}

void CConsole::SetCursorBlinkRate(double rate)
{
	m_cursorBlinkRate = rate;
}

void CConsole::FlushBuffer()
{
	// Clear the buffer and set the cursor and length to 0
	memset(m_szBuffer, '\0', sizeof(wchar_t) * CONSOLE_BUFFER_SIZE);
	m_iBufferPos = m_iBufferLength = 0;
}


void CConsole::Update(const float deltaRealTime)
{
	if(m_bToggle)
	{
		const float AnimateTime = .30f;
		const float Delta = deltaRealTime / AnimateTime;
		if(m_bVisible)
		{
			m_fVisibleFrac += Delta;
			if(m_fVisibleFrac > 1.0f)
			{
				m_fVisibleFrac = 1.0f;
				m_bToggle = false;
			}
		}
		else
		{
			m_fVisibleFrac -= Delta;
			if(m_fVisibleFrac < 0.0f)
			{
				m_fVisibleFrac = 0.0f;
				m_bToggle = false;
			}
		}
	}
}

//Render Manager.
void CConsole::Render()
{
	if (! (m_bVisible || m_bToggle) ) return;

	PROFILE3_GPU("console");

	glEnable(GL_BLEND);
	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

	CShaderTechniquePtr solidTech = g_Renderer.GetShaderManager().LoadEffect(str_gui_solid);
	solidTech->BeginPass();
	CShaderProgramPtr solidShader = solidTech->GetShader();

	CMatrix3D transform = GetDefaultGuiMatrix();

	// animation: slide in from top of screen
	const float DeltaY = (1.0f - m_fVisibleFrac) * m_fHeight;
	transform.PostTranslate(m_fX, m_fY - DeltaY, 0.0f); // move to window position
	solidShader->Uniform(str_transform, transform);

	DrawWindow(solidShader);

	solidTech->EndPass();

	CShaderTechniquePtr textTech = g_Renderer.GetShaderManager().LoadEffect(str_gui_text);
	textTech->BeginPass();
	CTextRenderer textRenderer(textTech->GetShader());
	textRenderer.Font(CStrIntern(CONSOLE_FONT));
	textRenderer.SetTransform(transform);

	DrawHistory(textRenderer);
	DrawBuffer(textRenderer);

	textRenderer.Render();

	textTech->EndPass();

	glDisable(GL_BLEND);
}


void CConsole::DrawWindow(CShaderProgramPtr& shader)
{
	float boxVerts[] = {
		m_fWidth, 0.0f,
		1.0f, 0.0f,
		1.0f, m_fHeight-1.0f,
		m_fWidth, m_fHeight-1.0f
	};

	shader->VertexPointer(2, GL_FLOAT, 0, boxVerts);

	// Draw Background
	// Set the color to a translucent blue
	shader->Uniform(str_color, 0.0f, 0.0f, 0.5f, 0.6f);
	shader->AssertPointersBound();
	glDrawArrays(GL_TRIANGLE_FAN, 0, 4);

	// Draw Border
	// Set the color to a translucent yellow
	shader->Uniform(str_color, 0.5f, 0.5f, 0.0f, 0.6f);
	shader->AssertPointersBound();
	glDrawArrays(GL_LINE_LOOP, 0, 4);

	if (m_fHeight > m_iFontHeight + 4)
	{
		float lineVerts[] = {
			0.0f, m_fHeight - (float)m_iFontHeight - 4.0f,
			m_fWidth, m_fHeight - (float)m_iFontHeight - 4.0f
		};
		shader->VertexPointer(2, GL_FLOAT, 0, lineVerts);
		shader->AssertPointersBound();
		glDrawArrays(GL_LINES, 0, 2);
	}
}


void CConsole::DrawHistory(CTextRenderer& textRenderer)
{
	int i = 1;

	std::deque<std::wstring>::iterator Iter; //History iterator

	CScopeLock lock(m_Mutex); // needed for safe access to m_deqMsgHistory

	textRenderer.Color(1.0f, 1.0f, 1.0f);

	for (Iter = m_deqMsgHistory.begin();
			Iter != m_deqMsgHistory.end()
				&& (((i - m_iMsgHistPos + 1) * m_iFontHeight) < m_fHeight);
			++Iter)
	{
		if (i >= m_iMsgHistPos)
			textRenderer.Put(9.0f, m_fHeight - (float)m_iFontOffset - (float)m_iFontHeight * (i - m_iMsgHistPos + 1), Iter->c_str());

		i++;
	}
}

// Renders the buffer to the screen.
void CConsole::DrawBuffer(CTextRenderer& textRenderer)
{
	if (m_fHeight < m_iFontHeight)
		return;

	CMatrix3D savedTransform = textRenderer.GetTransform();

	textRenderer.Translate(2.0f, m_fHeight - (float)m_iFontOffset + 1.0f, 0.0f);

	textRenderer.Color(1.0f, 1.0f, 0.0f);
	textRenderer.PutAdvance(L"]");

	textRenderer.Color(1.0f, 1.0f, 1.0f);

	if (m_iBufferPos == 0)
		DrawCursor(textRenderer);

	for (int i = 0; i < m_iBufferLength; i++)
	{
		textRenderer.PrintfAdvance(L"%lc", m_szBuffer[i]);
		if (m_iBufferPos-1 == i)
			DrawCursor(textRenderer);
	}

	textRenderer.SetTransform(savedTransform);
}

void CConsole::DrawCursor(CTextRenderer& textRenderer)
{
	if (m_cursorBlinkRate > 0.0)
	{
		// check if the cursor visibility state needs to be changed
		double currTime = timer_Time();
		if ((currTime - m_prevTime) >= m_cursorBlinkRate)
		{
			m_bCursorVisState = !m_bCursorVisState;
			m_prevTime = currTime;
		}
	}
	else
	{
		// Should always be visible
		m_bCursorVisState = true;
	}

	if(m_bCursorVisState)
	{
		// Slightly translucent yellow
		textRenderer.Color(1.0f, 1.0f, 0.0f, 0.8f);

		// Cursor character is chosen to be an underscore
		textRenderer.Put(0.0f, 0.0f, L"_");

		// Revert to the standard text color
		textRenderer.Color(1.0f, 1.0f, 1.0f);
	}
}


//Inserts a character into the buffer.
void CConsole::InsertChar(const int szChar, const wchar_t cooked)
{
	static int iHistoryPos = -1;

	if (!m_bVisible) return;

	switch (szChar)
	{
	case SDLK_RETURN:
		iHistoryPos = -1;
		m_iMsgHistPos = 1;
		ProcessBuffer(m_szBuffer);
		FlushBuffer();
		return;

	case SDLK_TAB:
		// Auto Complete
		return;

	case SDLK_BACKSPACE:
		if (IsEmpty() || IsBOB()) return;

		if (m_iBufferPos == m_iBufferLength)
			m_szBuffer[m_iBufferPos - 1] = '\0';
		else
		{
			for (int j = m_iBufferPos-1; j < m_iBufferLength-1; j++)
				m_szBuffer[j] = m_szBuffer[j+1]; // move chars to left
			m_szBuffer[m_iBufferLength-1] = '\0';
		}

		m_iBufferPos--;
		m_iBufferLength--;
		return;

	case SDLK_DELETE:
		if (IsEmpty() || IsEOB()) return;

		if (m_iBufferPos == m_iBufferLength-1)
		{
			m_szBuffer[m_iBufferPos] = '\0';
			m_iBufferLength--;
		}
		else
		{
			if (g_keys[SDLK_RCTRL] || g_keys[SDLK_LCTRL])
			{
				// Make Ctrl-Delete delete up to end of line
				m_szBuffer[m_iBufferPos] = '\0';
				m_iBufferLength = m_iBufferPos;
			}
			else
			{
				// Delete just one char and move the others left
				for(int j=m_iBufferPos; j<m_iBufferLength-1; j++)
					m_szBuffer[j] = m_szBuffer[j+1];
				m_szBuffer[m_iBufferLength-1] = '\0';
				m_iBufferLength--;
			}
		}

		return;

	case SDLK_HOME:
		if (g_keys[SDLK_RCTRL] || g_keys[SDLK_LCTRL])
		{
			CScopeLock lock(m_Mutex); // needed for safe access to m_deqMsgHistory

			int linesShown = (int)m_fHeight/m_iFontHeight - 4;
			m_iMsgHistPos = clamp((int)m_deqMsgHistory.size() - linesShown, 1, (int)m_deqMsgHistory.size());
		}
		else
		{
			m_iBufferPos = 0;
		}
		return;

	case SDLK_END:
		if (g_keys[SDLK_RCTRL] || g_keys[SDLK_LCTRL])
		{
			m_iMsgHistPos = 1;
		}
		else
		{
			m_iBufferPos = m_iBufferLength;
		}
		return;

	case SDLK_LEFT:
		if (m_iBufferPos) m_iBufferPos--;
		return;

	case SDLK_RIGHT:
		if (m_iBufferPos != m_iBufferLength) m_iBufferPos++;
		return;

	// BEGIN: Buffer History Lookup
	case SDLK_UP:
		if (m_deqBufHistory.size() && iHistoryPos != (int)m_deqBufHistory.size() - 1)
		{
			iHistoryPos++;
			SetBuffer(m_deqBufHistory.at(iHistoryPos).c_str());
			m_iBufferPos = m_iBufferLength;
		}
		return;

	case SDLK_DOWN:
		if (m_deqBufHistory.size())
		{
			if (iHistoryPos > 0)
			{
				iHistoryPos--;
				SetBuffer(m_deqBufHistory.at(iHistoryPos).c_str());
				m_iBufferPos = m_iBufferLength;
			}
			else if (iHistoryPos == 0)
			{
				iHistoryPos--;
				FlushBuffer();
			}
		}
		return;
	// END: Buffer History Lookup

	// BEGIN: Message History Lookup
	case SDLK_PAGEUP:
	{
		CScopeLock lock(m_Mutex); // needed for safe access to m_deqMsgHistory

		if (m_iMsgHistPos != (int)m_deqMsgHistory.size()) m_iMsgHistPos++;
		return;
	}

	case SDLK_PAGEDOWN:
		if (m_iMsgHistPos != 1) m_iMsgHistPos--;
		return;
	// END: Message History Lookup

	default: //Insert a character
		if (IsFull()) return;
		if (cooked == 0) return;

		if (IsEOB()) //are we at the end of the buffer?
			m_szBuffer[m_iBufferPos] = cooked; //cat char onto end
		else
		{ //we need to insert
			int i;
			for(i=m_iBufferLength; i>m_iBufferPos; i--)
				m_szBuffer[i] = m_szBuffer[i-1]; // move chars to right
			m_szBuffer[i] = cooked;
		}

		m_iBufferPos++;
		m_iBufferLength++;

		return;
	}
}


void CConsole::InsertMessage(const std::string& message)
{
	// (TODO: this text-wrapping is rubbish since we now use variable-width fonts)

	//Insert newlines to wraparound text where needed
	std::wstring wrapAround = wstring_from_utf8(message.c_str());
	std::wstring newline(L"\n");
	size_t oldNewline=0;
	size_t distance;

	//make sure everything has been initialized
	if ( m_charsPerPage != 0 )
	{
		while ( oldNewline+m_charsPerPage < wrapAround.length() )
		{
			distance = wrapAround.find(newline, oldNewline) - oldNewline;
			if ( distance > m_charsPerPage )
			{
				oldNewline += m_charsPerPage;
				wrapAround.insert( oldNewline++, newline );
			}
			else
				oldNewline += distance+1;
		}
	}
	// Split into lines and add each one individually
	oldNewline = 0;

	{
		CScopeLock lock(m_Mutex); // needed for safe access to m_deqMsgHistory

		while ( (distance = wrapAround.find(newline, oldNewline)) != wrapAround.npos)
		{
			distance -= oldNewline;
			m_deqMsgHistory.push_front(wrapAround.substr(oldNewline, distance));
			oldNewline += distance+1;
		}
		m_deqMsgHistory.push_front(wrapAround.substr(oldNewline));
	}
}

const wchar_t* CConsole::GetBuffer()
{
	m_szBuffer[m_iBufferLength] = 0;
	return( m_szBuffer );
}

void CConsole::SetBuffer(const wchar_t* szMessage)
{
	int oldBufferPos = m_iBufferPos;	// remember since FlushBuffer will set it to 0

	FlushBuffer();

	wcsncpy(m_szBuffer, szMessage, CONSOLE_BUFFER_SIZE);
	m_szBuffer[CONSOLE_BUFFER_SIZE-1] = 0;
	m_iBufferLength = (int)wcslen(m_szBuffer);
	m_iBufferPos = std::min(oldBufferPos, m_iBufferLength);
}

void CConsole::UseHistoryFile(const VfsPath& filename, int max_history_lines)
{
	m_MaxHistoryLines = max_history_lines;

	m_sHistoryFile = filename;
	LoadHistory();
}

void CConsole::ProcessBuffer(const wchar_t* szLine)
{
	shared_ptr<ScriptInterface> pScriptInterface = g_GUI->GetActiveGUI()->GetScriptInterface();
	JSContext* cx = pScriptInterface->GetContext();
	JSAutoRequest rq(cx);

	if (szLine == NULL) return;
	if (wcslen(szLine) <= 0) return;

	ENSURE(wcslen(szLine) < CONSOLE_BUFFER_SIZE);

	m_deqBufHistory.push_front(szLine);
	SaveHistory(); // Do this each line for the moment; if a script causes
	               // a crash it's a useful record.

	// Process it as JavaScript

	JS::RootedValue rval(cx);
	pScriptInterface->Eval(szLine, &rval);
	if (!rval.isUndefined())
		InsertMessage(pScriptInterface->ToString(&rval));
}

void CConsole::LoadHistory()
{
	// note: we don't care if this file doesn't exist or can't be read;
	// just don't load anything in that case.

	// do this before LoadFile to avoid an error message if file not found.
	if (!VfsFileExists(m_sHistoryFile))
		return;

	shared_ptr<u8> buf; size_t buflen;
	if (g_VFS->LoadFile(m_sHistoryFile, buf, buflen) < 0)
		return;

	CStr bytes ((char*)buf.get(), buflen);

	CStrW str (bytes.FromUTF8());
	size_t pos = 0;
	while (pos != CStrW::npos)
	{
		pos = str.find('\n');
		if (pos != CStrW::npos)
		{
			if (pos > 0)
				m_deqBufHistory.push_front(str.Left(str[pos-1] == '\r' ? pos - 1 : pos));
			str = str.substr(pos + 1);
		}
		else if (str.length() > 0)
			m_deqBufHistory.push_front(str);
	}
}

void CConsole::SaveHistory()
{
	WriteBuffer buffer;
	const int linesToSkip = (int)m_deqBufHistory.size() - m_MaxHistoryLines;
	std::deque<std::wstring>::reverse_iterator it = m_deqBufHistory.rbegin();
	if(linesToSkip > 0)
		std::advance(it, linesToSkip);
	for (; it != m_deqBufHistory.rend(); ++it)
	{
		CStr8 line = CStrW(*it).ToUTF8();
		buffer.Append(line.data(), line.length());
		static const char newline = '\n';
		buffer.Append(&newline, 1);
	}
	g_VFS->CreateFile(m_sHistoryFile, buffer.Data(), buffer.Size());
}

static bool isUnprintableChar(SDL_Keysym key)
{
	switch (key.sym)
	{
	// We want to allow some, which are handled specially
	case SDLK_RETURN: case SDLK_TAB:
	case SDLK_BACKSPACE: case SDLK_DELETE:
	case SDLK_HOME: case SDLK_END:
	case SDLK_LEFT: case SDLK_RIGHT:
	case SDLK_UP: case SDLK_DOWN:
	case SDLK_PAGEUP: case SDLK_PAGEDOWN:
		return false;

	// Ignore the others
	default:
		return true;
	}
}

InReaction conInputHandler(const SDL_Event_* ev)
{
	if ((int)ev->ev.type == SDL_HOTKEYDOWN)
	{
		std::string hotkey = static_cast<const char*>(ev->ev.user.data1);

		if (hotkey == "console.toggle")
		{
			g_Console->ToggleVisible();
			return IN_HANDLED;
		}
		else if (g_Console->IsActive() && hotkey == "copy")
		{
			sys_clipboard_set(g_Console->GetBuffer());
			return IN_HANDLED;
		}
		else if (g_Console->IsActive() && hotkey == "paste")
		{
			wchar_t* text = sys_clipboard_get();
			if (text)
			{
				for (wchar_t* c = text; *c; c++)
					g_Console->InsertChar(0, *c);

				sys_clipboard_free(text);
			}
			return IN_HANDLED;
		}
	}

	if (!g_Console->IsActive())
		return IN_PASS;

	// In SDL2, we no longer get Unicode wchars via SDL_Keysym
	// we use text input events instead and they provide UTF-8 chars
	if (ev->ev.type == SDL_TEXTINPUT && !HotkeyIsPressed("console.toggle"))
	{
		// TODO: this could be more efficient with an interface to insert UTF-8 strings directly
		std::wstring wstr = wstring_from_utf8(ev->ev.text.text);
		for (size_t i = 0; i < wstr.length(); ++i)
			g_Console->InsertChar(0, wstr[i]);
		return IN_HANDLED;
	}
	// TODO: text editing events for IME support

	if (ev->ev.type != SDL_KEYDOWN)
		return IN_PASS;

	int sym = ev->ev.key.keysym.sym;

	// Stop unprintable characters (ctrl+, alt+ and escape),
	// also prevent ` and/or ~ appearing in console every time it's toggled.
	if (!isUnprintableChar(ev->ev.key.keysym) &&
		!HotkeyIsPressed("console.toggle"))
	{
		g_Console->InsertChar(sym, 0);
		return IN_HANDLED;
	}

	return IN_PASS;
}