aboutsummaryrefslogtreecommitdiff
path: root/src/terminal_chat_console.cpp
blob: 9e3d33736190bc6ca2275d43b2ca84f37423c66a (plain)
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
/*
Minetest
Copyright (C) 2015 est31 <MTest31@outlook.com>

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.

This program 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 Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/

#include "config.h"
#if USE_CURSES
#include "version.h"
#include "terminal_chat_console.h"
#include "porting.h"
#include "settings.h"
#include "util/numeric.h"
#include "util/string.h"
#include "chat_interface.h"

TerminalChatConsole g_term_console;

// include this last to avoid any conflicts
// (likes to set macros to common names, conflicting various stuff)
#if CURSES_HAVE_NCURSESW_NCURSES_H
#include <ncursesw/ncurses.h>
#elif CURSES_HAVE_NCURSESW_CURSES_H
#include <ncursesw/curses.h>
#elif CURSES_HAVE_CURSES_H
#include <curses.h>
#elif CURSES_HAVE_NCURSES_H
#include <ncurses.h>
#elif CURSES_HAVE_NCURSES_NCURSES_H
#include <ncurses/ncurses.h>
#elif CURSES_HAVE_NCURSES_CURSES_H
#include <ncurses/curses.h>
#endif

// Some functions to make drawing etc position independent
static bool reformat_backend(ChatBackend *backend, int rows, int cols)
{
	if (rows < 2)
		return false;
	backend->reformat(cols, rows - 2);
	return true;
}

static void move_for_backend(int row, int col)
{
	move(row + 1, col);
}

void TerminalChatConsole::initOfCurses()
{
	initscr();
	cbreak(); //raw();
	noecho();
	keypad(stdscr, TRUE);
	nodelay(stdscr, TRUE);
	timeout(100);

	// To make esc not delay up to one second. According to the internet,
	// this is the value vim uses, too.
	set_escdelay(25);

	getmaxyx(stdscr, m_rows, m_cols);
	m_can_draw_text = reformat_backend(&m_chat_backend, m_rows, m_cols);
}

void TerminalChatConsole::deInitOfCurses()
{
	endwin();
}

void *TerminalChatConsole::run()
{
	BEGIN_DEBUG_EXCEPTION_HANDLER

	std::cout << "========================" << std::endl;
	std::cout << "Begin log output over terminal"
		<< " (no stdout/stderr backlog during that)" << std::endl;
	// Make the loggers to stdout/stderr shut up.
	// Go over our own loggers instead.
	LogLevelMask err_mask = g_logger.removeOutput(&stderr_output);
	LogLevelMask out_mask = g_logger.removeOutput(&stdout_output);

	g_logger.addOutput(&m_log_output);

	// Inform the server of our nick
	m_chat_interface->command_queue.push_back(
		new ChatEventNick(CET_NICK_ADD, m_nick));

	{
		// Ensures that curses is deinitialized even on an exception being thrown
		CursesInitHelper helper(this);

		while (!stopRequested()) {

			int ch = getch();
			if (stopRequested())
				break;

			step(ch);
		}
	}

	if (m_kill_requested)
		*m_kill_requested = true;

	g_logger.removeOutput(&m_log_output);
	g_logger.addOutputMasked(&stderr_output, err_mask);
	g_logger.addOutputMasked(&stdout_output, out_mask);

	std::cout << "End log output over terminal"
		<< " (no stdout/stderr backlog during that)" << std::endl;
	std::cout << "========================" << std::endl;

	END_DEBUG_EXCEPTION_HANDLER

	return NULL;
}

void TerminalChatConsole::typeChatMessage(const std::wstring &msg)
{
	// Discard empty line
	if (msg.empty())
		return;

	// Send to server
	m_chat_interface->command_queue.push_back(
		new ChatEventChat(m_nick, msg));

	// Print if its a command (gets eaten by server otherwise)
	if (msg[0] == L'/') {
		m_chat_backend.addMessage(L"", (std::wstring)L"Issued command: " + msg);
	}
}

void TerminalChatConsole::handleInput(int ch, bool &complete_redraw_needed)
{
	ChatPrompt &prompt = m_chat_backend.getPrompt();
	// Helpful if you want to collect key codes that aren't documented
	/*if (ch != ERR) {
		m_chat_backend.addMessage(L"",
			(std::wstring)L"Pressed key " + utf8_to_wide(
			std::string(keyname(ch)) + " (code " + itos(ch) + ")"));
		complete_redraw_needed = true;
	}//*/

	// All the key codes below are compatible to xterm
	// Only add new ones if you have tried them there,
	// to ensure compatibility with not just xterm but the wide
	// range of terminals that are compatible to xterm.

	switch (ch) {
		case ERR: // no input
			break;
		case 27: // ESC
			// Toggle ESC mode
			m_esc_mode = !m_esc_mode;
			break;
		case KEY_PPAGE:
			m_chat_backend.scrollPageUp();
			complete_redraw_needed = true;
			break;
		case KEY_NPAGE:
			m_chat_backend.scrollPageDown();
			complete_redraw_needed = true;
			break;
		case KEY_ENTER:
		case '\r':
		case '\n': {
			prompt.addToHistory(prompt.getLine());
			typeChatMessage(prompt.replace(L""));
			break;
		}
		case KEY_UP:
			prompt.historyPrev();
			break;
		case KEY_DOWN:
			prompt.historyNext();
			break;
		case KEY_LEFT:
			// Left pressed
			// move character to the left
			prompt.cursorOperation(
				ChatPrompt::CURSOROP_MOVE,
				ChatPrompt::CURSOROP_DIR_LEFT,
				ChatPrompt::CURSOROP_SCOPE_CHARACTER);
			break;
		case 545:
			// Ctrl-Left pressed
			// move word to the left
			prompt.cursorOperation(
				ChatPrompt::CURSOROP_MOVE,
				ChatPrompt::CURSOROP_DIR_LEFT,
				ChatPrompt::CURSOROP_SCOPE_WORD);
			break;
		case KEY_RIGHT:
			// Right pressed
			// move character to the right
			prompt.cursorOperation(
				ChatPrompt::CURSOROP_MOVE,
				ChatPrompt::CURSOROP_DIR_RIGHT,
				ChatPrompt::CURSOROP_SCOPE_CHARACTER);
			break;
		case 560:
			// Ctrl-Right pressed
			// move word to the right
			prompt.cursorOperation(
				ChatPrompt::CURSOROP_MOVE,
				ChatPrompt::CURSOROP_DIR_RIGHT,
				ChatPrompt::CURSOROP_SCOPE_WORD);
			break;
		case KEY_HOME:
			// Home pressed
			// move to beginning of line
			prompt.cursorOperation(
				ChatPrompt::CURSOROP_MOVE,
				ChatPrompt::CURSOROP_DIR_LEFT,
				ChatPrompt::CURSOROP_SCOPE_LINE);
			break;
		case KEY_END:
			// End pressed
			// move to end of line
			prompt.cursorOperation(
				ChatPrompt::CURSOROP_MOVE,
				ChatPrompt::CURSOROP_DIR_RIGHT,
				ChatPrompt::CURSOROP_SCOPE_LINE);
			break;
		case KEY_BACKSPACE:
		case '\b':
		case 127:
			// Backspace pressed
			// delete character to the left
			prompt.cursorOperation(
				ChatPrompt::CURSOROP_DELETE,
				ChatPrompt::CURSOROP_DIR_LEFT,
				ChatPrompt::CURSOROP_SCOPE_CHARACTER);
			break;
		case KEY_DC:
			// Delete pressed
			// delete character to the right
			prompt.cursorOperation(
				ChatPrompt::CURSOROP_DELETE,
				ChatPrompt::CURSOROP_DIR_RIGHT,
				ChatPrompt::CURSOROP_SCOPE_CHARACTER);
			break;
		case 519:
			// Ctrl-Delete pressed
			// delete word to the right
			prompt.cursorOperation(
				ChatPrompt::CURSOROP_DELETE,
				ChatPrompt::CURSOROP_DIR_RIGHT,
				ChatPrompt::CURSOROP_SCOPE_WORD);
			break;
		case 21:
			// Ctrl-U pressed
			// kill line to left end
			prompt.cursorOperation(
				ChatPrompt::CURSOROP_DELETE,
				ChatPrompt::CURSOROP_DIR_LEFT,
				ChatPrompt::CURSOROP_SCOPE_LINE);
			break;
		case 11:
			// Ctrl-K pressed
			// kill line to right end
			prompt.cursorOperation(
				ChatPrompt::CURSOROP_DELETE,
				ChatPrompt::CURSOROP_DIR_RIGHT,
				ChatPrompt::CURSOROP_SCOPE_LINE);
			break;
		case KEY_TAB:
			// Tab pressed
			// Nick completion
			prompt.nickCompletion(m_nicks, false);
			break;
		default:
			// Add character to the prompt,
			// assuming UTF-8.
			if (IS_UTF8_MULTB_START(ch)) {
				m_pending_utf8_bytes.append(1, (char)ch);
				m_utf8_bytes_to_wait += UTF8_MULTB_START_LEN(ch) - 1;
			} else if (m_utf8_bytes_to_wait != 0) {
				m_pending_utf8_bytes.append(1, (char)ch);
				m_utf8_bytes_to_wait--;
				if (m_utf8_bytes_to_wait == 0) {
					std::wstring w = utf8_to_wide(m_pending_utf8_bytes);
					m_pending_utf8_bytes = "";
					// hopefully only one char in the wstring...
					for (size_t i = 0; i < w.size(); i++) {
						prompt.input(w.c_str()[i]);
					}
				}
			} else if (IS_ASCII_PRINTABLE_CHAR(ch)) {
				prompt.input(ch);
			} else {
				// Silently ignore characters we don't handle

				//warningstream << "Pressed invalid character '"
				//	<< keyname(ch) << "' (code " << itos(ch) << ")" << std::endl;
			}
			break;
	}
}

void TerminalChatConsole::step(int ch)
{
	bool complete_redraw_needed = false;

	// empty queues
	while (!m_chat_interface->outgoing_queue.empty()) {
		ChatEvent *evt = m_chat_interface->outgoing_queue.pop_frontNoEx();
		switch (evt->type) {
			case CET_NICK_REMOVE:
				m_nicks.remove(((ChatEventNick *)evt)->nick);
				break;
			case CET_NICK_ADD:
				m_nicks.push_back(((ChatEventNick *)evt)->nick);
				break;
			case CET_CHAT:
				complete_redraw_needed = true;
				// This is only used for direct replies from commands
				// or for lua's print() functionality
				m_chat_backend.addMessage(L"", ((ChatEventChat *)evt)->evt_msg);
				break;
			case CET_TIME_INFO:
				ChatEventTimeInfo *tevt = (ChatEventTimeInfo *)evt;
				m_game_time = tevt->game_time;
				m_time_of_day = tevt->time;
		};
		delete evt;
	}
	while (!m_log_output.queue.empty()) {
		complete_redraw_needed = true;
		std::pair<LogLevel, std::string> p = m_log_output.queue.pop_frontNoEx();
		if (p.first > m_log_level)
			continue;

		std::wstring error_message = utf8_to_wide(Logger::getLevelLabel(p.first));
		if (!g_settings->getBool("disable_escape_sequences")) {
			error_message = std::wstring(L"\x1b(c@red)").append(error_message)
				.append(L"\x1b(c@white)");
		}
		m_chat_backend.addMessage(error_message, utf8_to_wide(p.second));
	}

	// handle input
	if (!m_esc_mode) {
		handleInput(ch, complete_redraw_needed);
	} else {
		switch (ch) {
			case ERR: // no input
				break;
			case 27: // ESC
				// Toggle ESC mode
				m_esc_mode = !m_esc_mode;
				break;
			case 'L':
				m_log_level--;
				m_log_level = MYMAX(m_log_level, LL_NONE + 1); // LL_NONE isn't accessible
				break;
			case 'l':
				m_log_level++;
				m_log_level = MYMIN(m_log_level, LL_MAX - 1);
				break;
		}
	}

	// was there a resize?
	int xn, yn;
	getmaxyx(stdscr, yn, xn);
	if (xn != m_cols || yn != m_rows) {
		m_cols = xn;
		m_rows = yn;
		m_can_draw_text = reformat_backend(&m_chat_backend, m_rows, m_cols);
		complete_redraw_needed = true;
	}

	// draw title
	move(0, 0);
	clrtoeol();
	addstr(PROJECT_NAME_C);
	addstr(" ");
	addstr(g_version_hash);

	u32 minutes = m_time_of_day % 1000;
	u32 hours = m_time_of_day / 1000;
	minutes = (float)minutes / 1000 * 60;

	if (m_game_time)
		printw(" | Game %d Time of day %02d:%02d ",
			m_game_time, hours, minutes);

	// draw text
	if (complete_redraw_needed && m_can_draw_text)
		draw_text();

	// draw prompt
	if (!m_esc_mode) {
		// normal prompt
		ChatPrompt& prompt = m_chat_backend.getPrompt();
		std::string prompt_text = wide_to_utf8(prompt.getVisiblePortion());
		move(m_rows - 1, 0);
		clrtoeol();
		addstr(prompt_text.c_str());
		// Draw cursor
		s32 cursor_pos = prompt.getVisibleCursorPosition();
		if (cursor_pos >= 0) {
			move(m_rows - 1, cursor_pos);
		}
	} else {
		// esc prompt
		move(m_rows - 1, 0);
		clrtoeol();
		printw("[ESC] Toggle ESC mode |"
			" [CTRL+C] Shut down |"
			" (L) in-, (l) decrease loglevel %s",
			Logger::getLevelLabel((LogLevel) m_log_level).c_str());
	}

	refresh();
}

void TerminalChatConsole::draw_text()
{
	ChatBuffer& buf = m_chat_backend.getConsoleBuffer();
	for (u32 row = 0; row < buf.getRows(); row++) {
		move_for_backend(row, 0);
		clrtoeol();
		const ChatFormattedLine& line = buf.getFormattedLine(row);
		if (line.fragments.empty())
			continue;
		for (const ChatFormattedFragment &fragment : line.fragments) {
			addstr(wide_to_utf8(fragment.text.getString()).c_str());
		}
	}
}

void TerminalChatConsole::stopAndWaitforThread()
{
	clearKillStatus();
	stop();
	wait();
}

#endif
"hl opt">*sa = PLAYER_TO_SA(player); int src_can_take_count = 0xffff; if (from_inv.type == InventoryLocation::DETACHED) src_can_take_count = sa->detached_inventory_AllowTake(*this, src_item, player); else if (from_inv.type == InventoryLocation::NODEMETA) src_can_take_count = sa->nodemeta_inventory_AllowTake(*this, src_item, player); else if (from_inv.type == InventoryLocation::PLAYER) src_can_take_count = sa->player_inventory_AllowTake(*this, src_item, player); else assert(false); return src_can_take_count; } int IMoveAction::allowMove(int try_take_count, ServerActiveObject *player) const { ServerScripting *sa = PLAYER_TO_SA(player); int src_can_take_count = 0xffff; if (from_inv.type == InventoryLocation::DETACHED) src_can_take_count = sa->detached_inventory_AllowMove(*this, try_take_count, player); else if (from_inv.type == InventoryLocation::NODEMETA) src_can_take_count = sa->nodemeta_inventory_AllowMove(*this, try_take_count, player); else if (from_inv.type == InventoryLocation::PLAYER) src_can_take_count = sa->player_inventory_AllowMove(*this, try_take_count, player); else assert(false); return src_can_take_count; } void IMoveAction::apply(InventoryManager *mgr, ServerActiveObject *player, IGameDef *gamedef) { Inventory *inv_from = mgr->getInventory(from_inv); Inventory *inv_to = mgr->getInventory(to_inv); if (!inv_from) { infostream << "IMoveAction::apply(): FAIL: source inventory not found: " << "from_inv=\""<<from_inv.dump() << "\"" << ", to_inv=\"" << to_inv.dump() << "\"" << std::endl; return; } if (!inv_to) { infostream << "IMoveAction::apply(): FAIL: destination inventory not found: " << "from_inv=\"" << from_inv.dump() << "\"" << ", to_inv=\"" << to_inv.dump() << "\"" << std::endl; return; } InventoryList *list_from = inv_from->getList(from_list); InventoryList *list_to = inv_to->getList(to_list); /* If a list doesn't exist or the source item doesn't exist */ if (!list_from) { infostream << "IMoveAction::apply(): FAIL: source list not found: " << "from_inv=\"" << from_inv.dump() << "\"" << ", from_list=\"" << from_list << "\"" << std::endl; return; } if (!list_to) { infostream << "IMoveAction::apply(): FAIL: destination list not found: " << "to_inv=\""<<to_inv.dump() << "\"" << ", to_list=\"" << to_list << "\"" << std::endl; return; } if (move_somewhere) { s16 old_to_i = to_i; u16 old_count = count; caused_by_move_somewhere = true; move_somewhere = false; infostream << "IMoveAction::apply(): moving item somewhere" << " msom=" << move_somewhere << " count=" << count << " from inv=\"" << from_inv.dump() << "\"" << " list=\"" << from_list << "\"" << " i=" << from_i << " to inv=\"" << to_inv.dump() << "\"" << " list=\"" << to_list << "\"" << std::endl; // Try to add the item to destination list s16 dest_size = list_to->getSize(); // First try all the non-empty slots for (s16 dest_i = 0; dest_i < dest_size && count > 0; dest_i++) { if (!list_to->getItem(dest_i).empty()) { to_i = dest_i; apply(mgr, player, gamedef); count -= move_count; } } // Then try all the empty ones for (s16 dest_i = 0; dest_i < dest_size && count > 0; dest_i++) { if (list_to->getItem(dest_i).empty()) { to_i = dest_i; apply(mgr, player, gamedef); count -= move_count; } } to_i = old_to_i; count = old_count; caused_by_move_somewhere = false; move_somewhere = true; return; } if ((u16)to_i > list_to->getSize()) { infostream << "IMoveAction::apply(): FAIL: destination index out of bounds: " << "to_i=" << to_i << ", size=" << list_to->getSize() << std::endl; return; } /* Do not handle rollback if both inventories are that of the same player */ bool ignore_rollback = ( from_inv.type == InventoryLocation::PLAYER && from_inv == to_inv); /* Collect information of endpoints */ ItemStack src_item = list_from->getItem(from_i); if (count > 0) src_item.count = count; if (src_item.empty()) return; int src_can_take_count = 0xffff; int dst_can_put_count = 0xffff; // this is needed for swapping items inside one inventory to work ItemStack restitem; bool allow_swap = !list_to->itemFits(to_i, src_item, &restitem) && restitem.count == src_item.count && !caused_by_move_somewhere; // Shift-click: Cannot fill this stack, proceed with next slot if (caused_by_move_somewhere && restitem.count == src_item.count) return; if (allow_swap) { // Swap will affect the entire stack if it can performed. src_item = list_from->getItem(from_i); count = src_item.count; } if (from_inv == to_inv) { // Move action within the same inventory src_can_take_count = allowMove(src_item.count, player); bool swap_expected = allow_swap; allow_swap = allow_swap && (src_can_take_count == -1 || src_can_take_count >= src_item.count); if (allow_swap) { int try_put_count = list_to->getItem(to_i).count; swapDirections(); dst_can_put_count = allowMove(try_put_count, player); allow_swap = allow_swap && (dst_can_put_count == -1 || dst_can_put_count >= try_put_count); swapDirections(); } else { dst_can_put_count = src_can_take_count; } if (swap_expected != allow_swap) src_can_take_count = dst_can_put_count = 0; } else { // Take from one inventory, put into another dst_can_put_count = allowPut(src_item, player); src_can_take_count = allowTake(src_item, player); bool swap_expected = allow_swap; allow_swap = allow_swap && (src_can_take_count == -1 || src_can_take_count >= src_item.count) && (dst_can_put_count == -1 || dst_can_put_count >= src_item.count); // A swap is expected, which means that we have to // run the "allow" callbacks a second time with swapped inventories if (allow_swap) { ItemStack dst_item = list_to->getItem(to_i); swapDirections(); int src_can_take = allowPut(dst_item, player); int dst_can_put = allowTake(dst_item, player); allow_swap = allow_swap && (src_can_take == -1 || src_can_take >= dst_item.count) && (dst_can_put == -1 || dst_can_put >= dst_item.count); swapDirections(); } if (swap_expected != allow_swap) src_can_take_count = dst_can_put_count = 0; } int old_count = count; /* Modify count according to collected data */ count = src_item.count; if (src_can_take_count != -1 && count > src_can_take_count) count = src_can_take_count; if (dst_can_put_count != -1 && count > dst_can_put_count) count = dst_can_put_count; /* Limit according to source item count */ if (count > list_from->getItem(from_i).count) count = list_from->getItem(from_i).count; /* If no items will be moved, don't go further */ if (count == 0) { // Undo client prediction. See 'clientApply' if (from_inv.type == InventoryLocation::PLAYER) list_from->setModified(); if (to_inv.type == InventoryLocation::PLAYER) list_to->setModified(); infostream<<"IMoveAction::apply(): move was completely disallowed:" <<" count="<<old_count <<" from inv=\""<<from_inv.dump()<<"\"" <<" list=\""<<from_list<<"\"" <<" i="<<from_i <<" to inv=\""<<to_inv.dump()<<"\"" <<" list=\""<<to_list<<"\"" <<" i="<<to_i <<std::endl; return; } src_item = list_from->getItem(from_i); src_item.count = count; ItemStack from_stack_was = list_from->getItem(from_i); ItemStack to_stack_was = list_to->getItem(to_i); /* Perform actual move If something is wrong (source item is empty, destination is the same as source), nothing happens */ bool did_swap = false; move_count = list_from->moveItem(from_i, list_to, to_i, count, allow_swap, &did_swap); assert(allow_swap == did_swap); // If source is infinite, reset it's stack if (src_can_take_count == -1) { // For the caused_by_move_somewhere == true case we didn't force-put the item, // which guarantees there is no leftover, and code below would duplicate the // (not replaced) to_stack_was item. if (!caused_by_move_somewhere) { // If destination stack is of different type and there are leftover // items, attempt to put the leftover items to a different place in the // destination inventory. // The client-side GUI will try to guess if this happens. if (from_stack_was.name != to_stack_was.name) { for (u32 i = 0; i < list_to->getSize(); i++) { if (list_to->getItem(i).empty()) { list_to->changeItem(i, to_stack_was); break; } } } } if (move_count > 0 || did_swap) { list_from->deleteItem(from_i); list_from->addItem(from_i, from_stack_was); } } // If destination is infinite, reset it's stack and take count from source if (dst_can_put_count == -1) { list_to->deleteItem(to_i); list_to->addItem(to_i, to_stack_was); list_from->deleteItem(from_i); list_from->addItem(from_i, from_stack_was); list_from->takeItem(from_i, count); } infostream << "IMoveAction::apply(): moved" << " msom=" << move_somewhere << " caused=" << caused_by_move_somewhere << " count=" << count << " from inv=\"" << from_inv.dump() << "\"" << " list=\"" << from_list << "\"" << " i=" << from_i << " to inv=\"" << to_inv.dump() << "\"" << " list=\"" << to_list << "\"" << " i=" << to_i << std::endl; // If we are inside the move somewhere loop, we don't need to report // anything if nothing happened (perhaps we don't need to report // anything for caused_by_move_somewhere == true, but this way its safer) if (caused_by_move_somewhere && move_count == 0) return; /* Record rollback information */ if (!ignore_rollback && gamedef->rollback()) { IRollbackManager *rollback = gamedef->rollback(); // If source is not infinite, record item take if (src_can_take_count != -1) { RollbackAction action; std::string loc; { std::ostringstream os(std::ios::binary); from_inv.serialize(os); loc = os.str(); } action.setModifyInventoryStack(loc, from_list, from_i, false, src_item); rollback->reportAction(action); } // If destination is not infinite, record item put if (dst_can_put_count != -1) { RollbackAction action; std::string loc; { std::ostringstream os(std::ios::binary); to_inv.serialize(os); loc = os.str(); } action.setModifyInventoryStack(loc, to_list, to_i, true, src_item); rollback->reportAction(action); } } /* Report move to endpoints */ // Source = destination => move if (from_inv == to_inv) { onMove(count, player); if (did_swap) { // Item is now placed in source list src_item = list_from->getItem(from_i); swapDirections(); onMove(src_item.count, player); swapDirections(); } mgr->setInventoryModified(from_inv); } else { onPutAndOnTake(src_item, player); if (did_swap) { // Item is now placed in source list src_item = list_from->getItem(from_i); swapDirections(); onPutAndOnTake(src_item, player); swapDirections(); } mgr->setInventoryModified(to_inv); mgr->setInventoryModified(from_inv); } } void IMoveAction::clientApply(InventoryManager *mgr, IGameDef *gamedef) { // Optional InventoryAction operation that is run on the client // to make lag less apparent. Inventory *inv_from = mgr->getInventory(from_inv); Inventory *inv_to = mgr->getInventory(to_inv); if (!inv_from || !inv_to) return; InventoryLocation current_player; current_player.setCurrentPlayer(); Inventory *inv_player = mgr->getInventory(current_player); if (inv_from != inv_player || inv_to != inv_player) return; InventoryList *list_from = inv_from->getList(from_list); InventoryList *list_to = inv_to->getList(to_list); if (!list_from || !list_to) return; if (!move_somewhere) list_from->moveItem(from_i, list_to, to_i, count); else list_from->moveItemSomewhere(from_i, list_to, count); mgr->setInventoryModified(from_inv); if (inv_from != inv_to) mgr->setInventoryModified(to_inv); } /* IDropAction */ IDropAction::IDropAction(std::istream &is) { std::string ts; std::getline(is, ts, ' '); count = stoi(ts); std::getline(is, ts, ' '); from_inv.deSerialize(ts); std::getline(is, from_list, ' '); std::getline(is, ts, ' '); from_i = stoi(ts); } void IDropAction::apply(InventoryManager *mgr, ServerActiveObject *player, IGameDef *gamedef) { Inventory *inv_from = mgr->getInventory(from_inv); if (!inv_from) { infostream<<"IDropAction::apply(): FAIL: source inventory not found: " <<"from_inv=\""<<from_inv.dump()<<"\""<<std::endl; return; } InventoryList *list_from = inv_from->getList(from_list); /* If a list doesn't exist or the source item doesn't exist */ if (!list_from) { infostream<<"IDropAction::apply(): FAIL: source list not found: " <<"from_inv=\""<<from_inv.dump()<<"\""<<std::endl; return; } if (list_from->getItem(from_i).empty()) { infostream<<"IDropAction::apply(): FAIL: source item not found: " <<"from_inv=\""<<from_inv.dump()<<"\"" <<", from_list=\""<<from_list<<"\"" <<" from_i="<<from_i<<std::endl; return; } /* Do not handle rollback if inventory is player's */ bool ignore_src_rollback = (from_inv.type == InventoryLocation::PLAYER); /* Collect information of endpoints */ int take_count = list_from->getItem(from_i).count; if (count != 0 && count < take_count) take_count = count;