axmol/core/base/CCConsole.cpp

1644 lines
46 KiB
C++
Raw Normal View History

2019-11-23 20:27:39 +08:00
/****************************************************************************
Copyright (c) 2013-2016 Chukong Technologies Inc.
Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
2020-05-18 09:21:52 +08:00
Copyright (c) 2020 c4games.com.
2021-10-09 13:48:56 +08:00
Copyright (c) 2021 Bytedance Inc.
2019-11-23 20:27:39 +08:00
2022-01-04 12:36:20 +08:00
https://adxeproject.github.io/
2019-11-23 20:27:39 +08:00
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#include "base/CCConsole.h"
#include <thread>
#include <algorithm>
#include <functional>
#include <cctype>
#include <locale>
#include <sstream>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <fcntl.h>
#if defined(_MSC_VER) || defined(__MINGW32__)
2021-12-25 10:04:45 +08:00
# include <io.h>
# if defined(__MINGW32__)
# include "platform/win32/inet_pton_mingw.h"
# endif
# define bzero(a, b) memset(a, 0, b)
# include "ntcvt/ntcvt.hpp"
2019-11-23 20:27:39 +08:00
#endif
#include "base/CCDirector.h"
#include "base/CCScheduler.h"
#include "platform/CCPlatformConfig.h"
#include "base/CCConfiguration.h"
#include "2d/CCScene.h"
#include "platform/CCFileUtils.h"
#include "renderer/CCTextureCache.h"
#include "base/base64.h"
#include "base/ccUtils.h"
2020-05-18 09:21:52 +08:00
#include "base/ccUTF8.h"
// !FIXME: the previous version of cocos2d::log not thread safe
2021-07-09 10:42:36 +08:00
// since adxe make it multi-threading safe by default
#if !defined(CC_LOG_MULTITHREAD)
2021-12-25 10:04:45 +08:00
# define CC_LOG_MULTITHREAD 1
#endif
2020-08-07 23:55:25 +08:00
#if !defined(CC_LOG_TO_CONSOLE)
2021-12-25 10:04:45 +08:00
# define CC_LOG_TO_CONSOLE 1
#endif
2019-11-23 20:27:39 +08:00
NS_CC_BEGIN
2021-10-25 20:29:40 +08:00
extern const char* adxeVersion(void);
2019-11-23 20:27:39 +08:00
2021-12-25 10:04:45 +08:00
#define PROMPT "> "
2019-11-23 20:27:39 +08:00
#define DEFAULT_COMMAND_SEPARATOR '|'
static const size_t SEND_BUFSIZ = 512;
/** private functions */
2021-12-25 10:04:45 +08:00
namespace
{
2019-11-23 20:27:39 +08:00
#if defined(__MINGW32__)
2021-12-25 10:04:45 +08:00
// inet
const char* inet_ntop(int af, const void* src, char* dst, int cnt)
{
struct sockaddr_in srcaddr;
memset(&srcaddr, 0, sizeof(struct sockaddr_in));
memcpy(&(srcaddr.sin_addr), src, sizeof(srcaddr.sin_addr));
srcaddr.sin_family = af;
if (WSAAddressToStringA((struct sockaddr*)&srcaddr, sizeof(struct sockaddr_in), 0, dst, (LPDWORD)&cnt) != 0)
2019-11-23 20:27:39 +08:00
{
2021-12-25 10:04:45 +08:00
return nullptr;
2019-11-23 20:27:39 +08:00
}
2021-12-25 10:04:45 +08:00
return dst;
}
2019-11-23 20:27:39 +08:00
#endif
2021-12-25 10:04:45 +08:00
//
// Free functions to log
//
2019-11-23 20:27:39 +08:00
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32)
2021-12-25 10:04:45 +08:00
void SendLogToWindow(const char* log)
{
static const int CCLOG_STRING_TAG = 1;
// Send data as a message
COPYDATASTRUCT myCDS;
myCDS.dwData = CCLOG_STRING_TAG;
myCDS.cbData = (DWORD)strlen(log) + 1;
myCDS.lpData = (PVOID)log;
if (Director::getInstance()->getOpenGLView())
2019-11-23 20:27:39 +08:00
{
2021-12-25 10:04:45 +08:00
HWND hwnd = Director::getInstance()->getOpenGLView()->getWin32Window();
// use non-block version of SendMessage
PostMessage(hwnd, WM_COPYDATA, (WPARAM)(HWND)hwnd, (LPARAM)(LPVOID)&myCDS);
2019-11-23 20:27:39 +08:00
}
}
2021-12-25 10:04:45 +08:00
#endif
} // namespace
2019-11-23 20:27:39 +08:00
2021-12-25 10:04:45 +08:00
void log(const char* format, ...)
2019-11-23 20:27:39 +08:00
{
2020-05-06 16:28:34 +08:00
#define CC_VSNPRINTF_BUFFER_LENGTH 512
2019-11-23 20:27:39 +08:00
va_list args;
2020-05-06 16:28:34 +08:00
va_start(args, format);
auto buf = StringUtils::vformat(format, args);
2020-05-06 16:28:34 +08:00
va_end(args);
#if CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID
2020-05-11 23:00:02 +08:00
__android_log_print(ANDROID_LOG_DEBUG, "cocos2d-x debug info", "%s", buf.c_str());
2019-11-23 20:27:39 +08:00
2021-12-25 10:04:45 +08:00
#elif CC_TARGET_PLATFORM == CC_PLATFORM_WIN32
2020-05-06 16:28:34 +08:00
buf.push_back('\n');
2019-11-23 20:27:39 +08:00
2020-05-06 16:28:34 +08:00
// print to debugger output window
std::wstring wbuf = ntcvt::from_chars(buf);
2019-11-23 20:27:39 +08:00
OutputDebugStringW(wbuf.c_str());
2021-12-25 10:04:45 +08:00
# if CC_LOG_TO_CONSOLE
auto hStdout = ::GetStdHandle(STD_OUTPUT_HANDLE);
2021-12-25 10:04:45 +08:00
if (hStdout)
{
// print to console if possible
// since we use win32 API, the ::fflush call doesn't required.
// see: https://docs.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-flushfilebuffers#return-value
DWORD wcch = static_cast<DWORD>(wbuf.size());
::WriteConsoleW(hStdout, wbuf.c_str(), wcch, nullptr, 0);
}
2021-12-25 10:04:45 +08:00
# endif
2020-05-06 16:28:34 +08:00
2021-12-25 10:04:45 +08:00
# if !CC_LOG_MULTITHREAD
2020-05-06 16:28:34 +08:00
// print to log window
SendLogToWindow(buf.c_str());
2021-12-25 10:04:45 +08:00
# endif
2019-11-23 20:27:39 +08:00
#else
2020-05-18 10:13:57 +08:00
buf.push_back('\n');
2019-11-23 20:27:39 +08:00
// Linux, Mac, iOS, etc
2020-05-06 16:28:34 +08:00
fprintf(stdout, "%s", buf.c_str());
2019-11-23 20:27:39 +08:00
fflush(stdout);
#endif
#if !CC_LOG_MULTITHREAD
2020-05-06 16:28:34 +08:00
Director::getInstance()->getConsole()->log(buf.c_str());
#endif
2019-11-23 20:27:39 +08:00
}
// FIXME: Deprecated
// void CCLog(const char * format, ...);
//
// Utility code
//
std::string Console::Utility::_prompt(PROMPT);
2021-12-25 10:04:45 +08:00
// TODO: these general utils should be in a separate class
2019-11-23 20:27:39 +08:00
//
2021-12-25 10:04:45 +08:00
// Trimming functions were taken from: http://stackoverflow.com/a/217605
// Since c++17, some parts of the standard library were removed, include "ptr_fun".
2019-11-23 20:27:39 +08:00
// trim from start
2021-12-25 10:04:45 +08:00
std::string& Console::Utility::ltrim(std::string& s)
{
s.erase(s.begin(), std::find_if(s.begin(), s.end(), [](int ch) { return !std::isspace(ch); }));
2019-11-23 20:27:39 +08:00
return s;
}
// trim from end
2021-12-25 10:04:45 +08:00
std::string& Console::Utility::rtrim(std::string& s)
{
s.erase(std::find_if(s.rbegin(), s.rend(), [](int ch) { return !std::isspace(ch); }).base(), s.end());
2019-11-23 20:27:39 +08:00
return s;
}
// trim from both ends
2021-12-25 10:04:45 +08:00
std::string& Console::Utility::trim(std::string& s)
{
2019-11-23 20:27:39 +08:00
return Console::Utility::ltrim(Console::Utility::rtrim(s));
}
std::vector<std::string>& Console::Utility::split(std::string_view s, char delim, std::vector<std::string>& elems)
2021-12-25 10:04:45 +08:00
{
std::stringstream ss;
ss << s;
2019-11-23 20:27:39 +08:00
std::string item;
2021-12-25 10:04:45 +08:00
while (std::getline(ss, item, delim))
{
2019-11-23 20:27:39 +08:00
elems.push_back(item);
}
return elems;
}
std::vector<std::string> Console::Utility::split(std::string_view s, char delim)
2021-12-25 10:04:45 +08:00
{
2019-11-23 20:27:39 +08:00
std::vector<std::string> elems;
Console::Utility::split(s, delim, elems);
return elems;
}
2021-12-25 10:04:45 +08:00
// isFloat taken from http://stackoverflow.com/questions/447206/c-isfloat-function
bool Console::Utility::isFloat(std::string_view myString)
2021-12-25 10:04:45 +08:00
{
std::stringstream ss;
ss << myString;
2019-11-23 20:27:39 +08:00
float f;
ss >> std::noskipws >> f; // noskipws considers leading whitespace invalid
2019-11-23 20:27:39 +08:00
// Check the entire string was consumed and if either failbit or badbit is set
return ss.eof() && !ss.fail();
2019-11-23 20:27:39 +08:00
}
ssize_t Console::Utility::sendToConsole(int fd, const void* buffer, size_t length, int flags)
{
2021-12-25 10:04:45 +08:00
if (_prompt.length() == length)
{
if (strncmp(_prompt.c_str(), static_cast<const char*>(buffer), length) == 0)
{
fprintf(stderr, "bad parameter error: a buffer is the prompt string.\n");
2019-11-23 20:27:39 +08:00
return 0;
}
}
2021-12-25 10:04:45 +08:00
2019-11-23 20:27:39 +08:00
const char* buf = static_cast<const char*>(buffer);
2021-12-25 10:04:45 +08:00
ssize_t retLen = 0;
for (size_t i = 0; i < length;)
{
2019-11-23 20:27:39 +08:00
size_t len = length - i;
2021-12-25 10:04:45 +08:00
if (SEND_BUFSIZ < len)
len = SEND_BUFSIZ;
2019-11-23 20:27:39 +08:00
retLen += send(fd, buf + i, len, flags);
i += len;
}
return retLen;
}
// dprintf() is not defined in Android
// so we add our own 'dpritnf'
2021-12-25 10:04:45 +08:00
ssize_t Console::Utility::mydprintf(int sock, const char* format, ...)
2019-11-23 20:27:39 +08:00
{
va_list args;
char buf[16386];
2021-12-25 10:04:45 +08:00
2019-11-23 20:27:39 +08:00
va_start(args, format);
vsnprintf(buf, sizeof(buf), format, args);
va_end(args);
return sendToConsole(sock, buf, strlen(buf));
}
void Console::Utility::sendPrompt(int fd)
{
const char* prompt = _prompt.c_str();
send(fd, prompt, strlen(prompt), 0);
}
void Console::Utility::setPrompt(std::string_view prompt)
2019-11-23 20:27:39 +08:00
{
_prompt = prompt;
}
std::string_view Console::Utility::getPrompt()
2019-11-23 20:27:39 +08:00
{
return _prompt;
}
//
// Command code
//
2021-12-25 10:04:45 +08:00
Console::Command::Command() : _callback(nullptr) {}
2019-11-23 20:27:39 +08:00
Console::Command::Command(std::string_view name, std::string_view help) : _name(name), _help(help), _callback(nullptr)
2021-12-25 10:04:45 +08:00
{}
2019-11-23 20:27:39 +08:00
Console::Command::Command(std::string_view name, std::string_view help, const Callback& callback)
2021-12-25 10:04:45 +08:00
: _name(name), _help(help), _callback(callback)
{}
2019-11-23 20:27:39 +08:00
Console::Command::Command(const Command& o)
{
*this = o;
}
Console::Command::Command(Command&& o)
{
*this = std::move(o);
}
Console::Command::~Command()
{
for (const auto& e : _subCommands)
{
delete e.second;
}
}
Console::Command& Console::Command::operator=(const Command& o)
{
if (this != &o)
{
2021-12-25 10:04:45 +08:00
_name = o._name;
_help = o._help;
2019-11-23 20:27:39 +08:00
_callback = o._callback;
for (const auto& e : _subCommands)
delete e.second;
_subCommands.clear();
for (const auto& e : o._subCommands)
{
2021-12-25 10:04:45 +08:00
Command* subCommand = e.second;
auto newCommand = new Command(*subCommand);
2019-11-23 20:27:39 +08:00
_subCommands[e.first] = newCommand;
}
}
return *this;
}
Console::Command& Console::Command::operator=(Command&& o)
{
if (this != &o)
{
2021-12-25 10:04:45 +08:00
_name = std::move(o._name);
_help = std::move(o._help);
_callback = std::move(o._callback);
2019-11-23 20:27:39 +08:00
o._callback = nullptr;
for (const auto& e : _subCommands)
delete e.second;
_subCommands.clear();
_subCommands = std::move(o._subCommands);
}
return *this;
}
void Console::Command::addCallback(const Callback& callback)
{
_callback = callback;
}
void Console::Command::addSubCommand(const Command& subCmd)
{
auto iter = _subCommands.find(subCmd._name);
if (iter != _subCommands.end())
{
delete iter->second;
_subCommands.erase(iter);
}
2021-12-25 10:04:45 +08:00
Command* cmd = new Command();
*cmd = subCmd;
2019-11-23 20:27:39 +08:00
_subCommands[subCmd._name] = cmd;
}
const Console::Command* Console::Command::getSubCommand(std::string_view subCmdName) const
2019-11-23 20:27:39 +08:00
{
auto it = _subCommands.find(subCmdName);
2021-12-25 10:04:45 +08:00
if (it != _subCommands.end())
{
2019-11-23 20:27:39 +08:00
auto& subCmd = it->second;
return subCmd;
}
return nullptr;
}
void Console::Command::delSubCommand(std::string_view subCmdName)
2019-11-23 20:27:39 +08:00
{
auto iter = _subCommands.find(subCmdName);
2021-12-25 10:04:45 +08:00
if (iter != _subCommands.end())
{
2019-11-23 20:27:39 +08:00
delete iter->second;
_subCommands.erase(iter);
}
}
void Console::Command::commandHelp(int fd, std::string_view /*args*/)
2019-11-23 20:27:39 +08:00
{
2021-12-25 10:04:45 +08:00
if (!_help.empty())
{
2019-11-23 20:27:39 +08:00
Console::Utility::mydprintf(fd, "%s\n", _help.c_str());
}
2021-12-25 10:04:45 +08:00
if (!_subCommands.empty())
{
2019-11-23 20:27:39 +08:00
sendHelp(fd, _subCommands, "");
}
}
void Console::Command::commandGeneric(int fd, std::string_view args)
2019-11-23 20:27:39 +08:00
{
// The first argument (including the empty)
std::string key(args);
auto pos = args.find(' ');
2021-12-25 10:04:45 +08:00
if ((pos != std::string::npos) && (0 < pos))
{
2019-11-23 20:27:39 +08:00
key = args.substr(0, pos);
}
2021-12-25 10:04:45 +08:00
2019-11-23 20:27:39 +08:00
// help
2021-12-25 10:04:45 +08:00
if (key == "help" || key == "-h")
{
2019-11-23 20:27:39 +08:00
commandHelp(fd, args);
return;
}
2021-12-25 10:04:45 +08:00
2019-11-23 20:27:39 +08:00
// find sub command
auto it = _subCommands.find(key);
2021-12-25 10:04:45 +08:00
if (it != _subCommands.end())
{
2019-11-23 20:27:39 +08:00
auto subCmd = it->second;
2021-12-25 10:04:45 +08:00
if (subCmd->_callback)
{
2019-11-23 20:27:39 +08:00
subCmd->_callback(fd, args);
}
return;
}
2021-12-25 10:04:45 +08:00
2019-11-23 20:27:39 +08:00
// can not find
2021-12-25 10:04:45 +08:00
if (_callback)
{
2019-11-23 20:27:39 +08:00
_callback(fd, args);
}
}
//
// Console code
//
Console::Console()
2021-12-25 10:04:45 +08:00
: _commandSeparator(DEFAULT_COMMAND_SEPARATOR)
, _listenfd(-1)
, _running(false)
, _endThread(false)
, _isIpv6Server(false)
, _sendDebugStrings(false)
, _bindAddress("")
2019-11-23 20:27:39 +08:00
{
createCommandAllocator();
createCommandConfig();
createCommandDebugMsg();
createCommandDirector();
createCommandExit();
createCommandFileUtils();
createCommandFps();
createCommandHelp();
createCommandProjection();
createCommandResolution();
createCommandSceneGraph();
createCommandTexture();
createCommandTouch();
createCommandUpload();
createCommandVersion();
}
Console::~Console()
{
stop();
for (auto& e : _commands)
delete e.second;
}
bool Console::listenOnTCP(int port)
{
2021-10-09 13:48:56 +08:00
socket_native_type listenfd = -1;
int n;
2019-11-23 20:27:39 +08:00
const int on = 1;
struct addrinfo hints, *res, *ressave;
char serv[30];
2021-12-25 10:04:45 +08:00
snprintf(serv, sizeof(serv) - 1, "%d", port);
2019-11-23 20:27:39 +08:00
bzero(&hints, sizeof(struct addrinfo));
2021-12-25 10:04:45 +08:00
hints.ai_flags = AI_PASSIVE;
hints.ai_family = AF_UNSPEC;
2019-11-23 20:27:39 +08:00
hints.ai_socktype = SOCK_STREAM;
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32)
WSADATA wsaData;
2021-12-25 10:04:45 +08:00
n = WSAStartup(MAKEWORD(2, 2), &wsaData);
2019-11-23 20:27:39 +08:00
#endif
2021-12-25 10:04:45 +08:00
if ((n = getaddrinfo(nullptr, serv, &hints, &res)) != 0)
{
2019-11-23 20:27:39 +08:00
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32)
fprintf(stderr, "net_listen error for %s: %s", serv, gai_strerrorA(n));
#else
2021-12-25 10:04:45 +08:00
fprintf(stderr, "net_listen error for %s: %s", serv, gai_strerror(n));
2019-11-23 20:27:39 +08:00
#endif
return false;
}
ressave = res;
2021-12-25 10:04:45 +08:00
do
{
2019-11-23 20:27:39 +08:00
listenfd = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
if (listenfd < 0)
2021-12-25 10:04:45 +08:00
continue; /* error, try next one */
2019-11-23 20:27:39 +08:00
setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, (const char*)&on, sizeof(on));
// bind address
if (!_bindAddress.empty())
{
if (res->ai_family == AF_INET)
{
2021-12-25 10:04:45 +08:00
struct sockaddr_in* sin = (struct sockaddr_in*)res->ai_addr;
2019-11-23 20:27:39 +08:00
inet_pton(res->ai_family, _bindAddress.c_str(), (void*)&sin->sin_addr);
}
else if (res->ai_family == AF_INET6)
{
2021-12-25 10:04:45 +08:00
struct sockaddr_in6* sin = (struct sockaddr_in6*)res->ai_addr;
2019-11-23 20:27:39 +08:00
inet_pton(res->ai_family, _bindAddress.c_str(), (void*)&sin->sin6_addr);
}
}
if (bind(listenfd, res->ai_addr, res->ai_addrlen) == 0)
2021-12-25 10:04:45 +08:00
break; /* success */
2019-11-23 20:27:39 +08:00
/* bind error, close and try next one */
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32)
closesocket(listenfd);
#else
close(listenfd);
#endif
2021-12-25 10:04:45 +08:00
} while ((res = res->ai_next) != nullptr);
if (res == nullptr)
{
2019-11-23 20:27:39 +08:00
perror("net_listen:");
freeaddrinfo(ressave);
return false;
}
listen(listenfd, 50);
2021-12-25 10:04:45 +08:00
if (res->ai_family == AF_INET)
{
_isIpv6Server = false;
2019-11-23 20:27:39 +08:00
char buf[INET_ADDRSTRLEN] = {0};
2021-12-25 10:04:45 +08:00
struct sockaddr_in* sin = (struct sockaddr_in*)res->ai_addr;
if (inet_ntop(res->ai_family, &sin->sin_addr, buf, sizeof(buf)) != nullptr)
2019-11-23 20:27:39 +08:00
cocos2d::log("Console: IPV4 server is listening on %s:%d", buf, ntohs(sin->sin_port));
else
perror("inet_ntop");
2021-12-25 10:04:45 +08:00
}
else if (res->ai_family == AF_INET6)
{
_isIpv6Server = true;
2019-11-23 20:27:39 +08:00
char buf[INET6_ADDRSTRLEN] = {0};
2021-12-25 10:04:45 +08:00
struct sockaddr_in6* sin = (struct sockaddr_in6*)res->ai_addr;
if (inet_ntop(res->ai_family, &sin->sin6_addr, buf, sizeof(buf)) != nullptr)
2019-11-23 20:27:39 +08:00
cocos2d::log("Console: IPV6 server is listening on [%s]:%d", buf, ntohs(sin->sin6_port));
else
perror("inet_ntop");
}
freeaddrinfo(ressave);
return listenOnFileDescriptor(listenfd);
}
bool Console::listenOnFileDescriptor(int fd)
{
2021-12-25 10:04:45 +08:00
if (_running)
{
2019-11-23 20:27:39 +08:00
cocos2d::log("Console already started. 'stop' it before calling 'listen' again");
return false;
}
_listenfd = fd;
2021-12-25 10:04:45 +08:00
_thread = std::thread(std::bind(&Console::loop, this));
2019-11-23 20:27:39 +08:00
return true;
}
void Console::stop()
{
2021-12-25 10:04:45 +08:00
if (_running)
{
2019-11-23 20:27:39 +08:00
_endThread = true;
if (_thread.joinable())
{
_thread.join();
}
}
}
void Console::addCommand(const Command& cmd)
{
2021-12-08 00:11:53 +08:00
Command* newCommand = new Command(cmd);
2021-12-25 10:04:45 +08:00
auto iter = _commands.find(cmd.getName());
2019-11-23 20:27:39 +08:00
if (iter != _commands.end())
{
delete iter->second;
_commands.erase(iter);
}
_commands.emplace(cmd.getName(), newCommand); // _commands[cmd.getName()] = newCommand;
2019-11-23 20:27:39 +08:00
}
void Console::addSubCommand(std::string_view cmdName, const Command& subCmd)
2019-11-23 20:27:39 +08:00
{
auto it = _commands.find(cmdName);
if (it != _commands.end())
{
auto& cmd = it->second;
addSubCommand(*cmd, subCmd);
}
}
void Console::addSubCommand(Command& cmd, const Command& subCmd)
{
cmd.addSubCommand(subCmd);
}
const Console::Command* Console::getCommand(std::string_view cmdName)
2019-11-23 20:27:39 +08:00
{
auto it = _commands.find(cmdName);
2021-12-25 10:04:45 +08:00
if (it != _commands.end())
{
2019-11-23 20:27:39 +08:00
auto& cmd = it->second;
return cmd;
}
return nullptr;
}
const Console::Command* Console::getSubCommand(std::string_view cmdName, std::string_view subCmdName)
2019-11-23 20:27:39 +08:00
{
auto it = _commands.find(cmdName);
2021-12-25 10:04:45 +08:00
if (it != _commands.end())
{
2019-11-23 20:27:39 +08:00
auto& cmd = it->second;
return getSubCommand(*cmd, subCmdName);
}
return nullptr;
}
const Console::Command* Console::getSubCommand(const Command& cmd, std::string_view subCmdName)
2019-11-23 20:27:39 +08:00
{
return cmd.getSubCommand(subCmdName);
}
void Console::delCommand(std::string_view cmdName)
2019-11-23 20:27:39 +08:00
{
auto it = _commands.find(cmdName);
2021-12-25 10:04:45 +08:00
if (it != _commands.end())
{
2019-11-23 20:27:39 +08:00
delete it->second;
_commands.erase(it);
}
}
void Console::delSubCommand(std::string_view cmdName, std::string_view subCmdName)
2019-11-23 20:27:39 +08:00
{
auto it = _commands.find(cmdName);
2021-12-25 10:04:45 +08:00
if (it != _commands.end())
{
2019-11-23 20:27:39 +08:00
auto& cmd = it->second;
delSubCommand(*cmd, subCmdName);
}
}
void Console::delSubCommand(Command& cmd, std::string_view subCmdName)
2019-11-23 20:27:39 +08:00
{
cmd.delSubCommand(subCmdName);
}
void Console::log(const char* buf)
{
2021-12-25 10:04:45 +08:00
if (_sendDebugStrings)
{
2019-11-23 20:27:39 +08:00
_DebugStringsMutex.lock();
_DebugStrings.push_back(buf);
_DebugStringsMutex.unlock();
}
}
void Console::setBindAddress(std::string_view address)
2019-11-23 20:27:39 +08:00
{
_bindAddress = address;
}
bool Console::isIpv6Server() const
{
return _isIpv6Server;
}
//
// Main Loop
//
void Console::loop()
{
fd_set copy_set;
struct timeval timeout, timeout_copy;
2021-12-25 10:04:45 +08:00
2019-11-23 20:27:39 +08:00
_running = true;
2021-12-25 10:04:45 +08:00
2019-11-23 20:27:39 +08:00
FD_ZERO(&_read_set);
FD_SET(_listenfd, &_read_set);
_maxfd = _listenfd;
2021-12-25 10:04:45 +08:00
timeout.tv_sec = 1;
2019-11-23 20:27:39 +08:00
timeout.tv_usec = 0;
2021-12-25 10:04:45 +08:00
while (!_endThread)
{
copy_set = _read_set;
2019-11-23 20:27:39 +08:00
timeout_copy = timeout;
2021-12-25 10:04:45 +08:00
int nready = select(_maxfd + 1, &copy_set, nullptr, nullptr, &timeout_copy);
if (nready == -1)
2019-11-23 20:27:39 +08:00
{
/* error */
2021-12-25 10:04:45 +08:00
if (errno != EINTR)
2019-11-23 20:27:39 +08:00
cocos2d::log("Abnormal error in select()\n");
continue;
}
2021-12-25 10:04:45 +08:00
else if (nready == 0)
2019-11-23 20:27:39 +08:00
{
/* timeout. do something ? */
}
else
{
/* new client */
2021-12-25 10:04:45 +08:00
if (FD_ISSET(_listenfd, &copy_set))
{
2019-11-23 20:27:39 +08:00
addClient();
2021-12-25 10:04:45 +08:00
if (--nready <= 0)
2019-11-23 20:27:39 +08:00
continue;
}
2021-12-25 10:04:45 +08:00
2019-11-23 20:27:39 +08:00
/* data from client */
std::vector<int> to_remove;
2021-12-25 10:04:45 +08:00
for (const auto& fd : _fds)
{
if (FD_ISSET(fd, &copy_set))
2019-11-23 20:27:39 +08:00
{
2021-12-25 10:04:45 +08:00
// fix Bug #4302 Test case ConsoleTest--ConsoleUploadFile crashed on Linux
// On linux, if you send data to a closed socket, the sending process will
// receive a SIGPIPE, which will cause linux system shutdown the sending process.
// Add this ioctl code to check if the socket has been closed by peer.
2019-11-23 20:27:39 +08:00
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32)
u_long n = 0;
ioctlsocket(fd, FIONREAD, &n);
#else
int n = 0;
2021-12-25 10:04:45 +08:00
if (ioctl(fd, FIONREAD, &n) < 0)
2019-11-23 20:27:39 +08:00
{
cocos2d::log("Abnormal error in ioctl()\n");
break;
}
#endif
2021-12-25 10:04:45 +08:00
if (n == 0)
2019-11-23 20:27:39 +08:00
{
2021-12-25 10:04:45 +08:00
// no data received, or fd is closed
// fix #18620. readable and no pending data means that the fd is closed.
to_remove.push_back(fd);
2019-11-23 20:27:39 +08:00
continue;
}
2021-12-25 10:04:45 +08:00
if (!parseCommand(fd))
2019-11-23 20:27:39 +08:00
{
to_remove.push_back(fd);
}
2021-12-25 10:04:45 +08:00
if (--nready <= 0)
2019-11-23 20:27:39 +08:00
break;
}
}
2021-12-25 10:04:45 +08:00
2019-11-23 20:27:39 +08:00
/* remove closed connections */
2021-12-25 10:04:45 +08:00
for (int fd : to_remove)
{
2019-11-23 20:27:39 +08:00
FD_CLR(fd, &_read_set);
_fds.erase(std::remove(_fds.begin(), _fds.end(), fd), _fds.end());
}
}
2021-12-25 10:04:45 +08:00
2019-11-23 20:27:39 +08:00
/* Any message for the remote console ? send it! */
2021-12-25 10:04:45 +08:00
if (!_DebugStrings.empty())
{
2019-11-23 20:27:39 +08:00
if (_DebugStringsMutex.try_lock())
{
2021-12-25 10:04:45 +08:00
for (const auto& str : _DebugStrings)
{
for (auto fd : _fds)
{
2019-11-23 20:27:39 +08:00
Console::Utility::sendToConsole(fd, str.c_str(), str.length());
}
}
_DebugStrings.clear();
_DebugStringsMutex.unlock();
}
}
}
2021-12-25 10:04:45 +08:00
2019-11-23 20:27:39 +08:00
// clean up: ignore stdin, stdout and stderr
2021-12-25 10:04:45 +08:00
for (const auto& fd : _fds)
2019-11-23 20:27:39 +08:00
{
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32)
closesocket(fd);
#else
close(fd);
#endif
}
2021-12-25 10:04:45 +08:00
2019-11-23 20:27:39 +08:00
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32)
closesocket(_listenfd);
WSACleanup();
#else
close(_listenfd);
#endif
_running = false;
}
//
// Helpers
//
2021-10-09 13:48:56 +08:00
ssize_t Console::readline(socket_native_type fd, char* ptr, size_t maxlen)
2019-11-23 20:27:39 +08:00
{
size_t n, rc;
char c;
2021-12-25 10:04:45 +08:00
for (n = 0; n < maxlen - 1; n++)
{
if ((rc = recv(fd, &c, 1, 0)) == 1)
{
2019-11-23 20:27:39 +08:00
*ptr++ = c;
2021-12-25 10:04:45 +08:00
if (c == '\n')
{
2019-11-23 20:27:39 +08:00
break;
}
2021-12-25 10:04:45 +08:00
}
else if (rc == 0)
{
2019-11-23 20:27:39 +08:00
return 0;
2021-12-25 10:04:45 +08:00
}
else if (errno == EINTR)
{
2019-11-23 20:27:39 +08:00
continue;
2021-12-25 10:04:45 +08:00
}
else
{
2019-11-23 20:27:39 +08:00
return -1;
}
}
2021-12-25 10:04:45 +08:00
2019-11-23 20:27:39 +08:00
*ptr = 0;
return n;
}
2021-10-09 13:48:56 +08:00
ssize_t Console::readBytes(socket_native_type fd, char* buffer, size_t maxlen, bool* more)
2019-11-23 20:27:39 +08:00
{
size_t n, rc;
char c, *ptr = buffer;
*more = false;
2021-12-25 10:04:45 +08:00
for (n = 0; n < maxlen; n++)
{
if ((rc = recv(fd, &c, 1, 0)) == 1)
{
2019-11-23 20:27:39 +08:00
*ptr++ = c;
2021-12-25 10:04:45 +08:00
if (c == '\n')
{
2019-11-23 20:27:39 +08:00
return n;
}
2021-12-25 10:04:45 +08:00
}
else if (rc == 0)
{
2019-11-23 20:27:39 +08:00
return 0;
2021-12-25 10:04:45 +08:00
}
else if (errno == EINTR)
{
2019-11-23 20:27:39 +08:00
continue;
2021-12-25 10:04:45 +08:00
}
else
{
2019-11-23 20:27:39 +08:00
return -1;
}
}
*more = true;
return n;
}
2021-10-09 13:48:56 +08:00
bool Console::parseCommand(socket_native_type fd)
2019-11-23 20:27:39 +08:00
{
char buf[512];
bool more_data;
auto h = readBytes(fd, buf, 6, &more_data);
2021-12-25 10:04:45 +08:00
if (h < 0)
2019-11-23 20:27:39 +08:00
{
return false;
}
2021-12-25 10:04:45 +08:00
if (strncmp(buf, "upload", 6) == 0)
2019-11-23 20:27:39 +08:00
{
char c = '\0';
recv(fd, &c, 1, 0);
2021-12-25 10:04:45 +08:00
if (c == ' ')
2019-11-23 20:27:39 +08:00
{
commandUpload(fd);
Console::Utility::sendPrompt(fd);
return true;
}
else
{
const char err[] = "upload: invalid args! Type 'help' for options\n";
Console::Utility::sendToConsole(fd, err, strlen(err));
Console::Utility::sendPrompt(fd);
return true;
}
}
2021-12-25 10:04:45 +08:00
if (!more_data)
2019-11-23 20:27:39 +08:00
{
buf[h] = 0;
}
else
{
2021-12-25 10:04:45 +08:00
char* pb = buf + 6;
auto r = readline(fd, pb, sizeof(buf) - 6);
if (r < 0)
2019-11-23 20:27:39 +08:00
{
const char err[] = "Unknown error!\n";
Console::Utility::sendPrompt(fd);
Console::Utility::sendToConsole(fd, err, strlen(err));
return false;
}
}
std::string cmdLine;
2021-12-25 10:04:45 +08:00
cmdLine = std::string(buf);
2019-11-23 20:27:39 +08:00
auto commands = Console::Utility::split(cmdLine, _commandSeparator);
2021-12-25 10:04:45 +08:00
try
{
for (auto command : commands)
{
2019-11-23 20:27:39 +08:00
performCommand(fd, Console::Utility::trim(command));
}
2021-12-25 10:04:45 +08:00
}
catch (const std::runtime_error& e)
{
2019-11-23 20:27:39 +08:00
Console::Utility::sendToConsole(fd, e.what(), strlen(e.what()));
}
2021-12-25 10:04:45 +08:00
2019-11-23 20:27:39 +08:00
Console::Utility::sendPrompt(fd);
2021-12-25 10:04:45 +08:00
2019-11-23 20:27:39 +08:00
return true;
}
void Console::performCommand(socket_native_type fd, std::string_view command)
2021-10-09 13:48:56 +08:00
{
2019-11-23 20:27:39 +08:00
std::vector<std::string> args = Console::Utility::split(command, ' ');
2021-12-25 10:04:45 +08:00
if (args.empty())
{
2019-11-23 20:27:39 +08:00
throw std::runtime_error("Unknown command. Type 'help' for options\n");
}
2021-12-25 10:04:45 +08:00
2019-11-23 20:27:39 +08:00
auto it = _commands.find(Console::Utility::trim(args[0]));
2021-12-25 10:04:45 +08:00
if (it != _commands.end())
2019-11-23 20:27:39 +08:00
{
std::string args2;
2021-12-25 10:04:45 +08:00
for (size_t i = 1; i < args.size(); ++i)
2019-11-23 20:27:39 +08:00
{
2021-12-25 10:04:45 +08:00
if (i > 1)
2019-11-23 20:27:39 +08:00
{
args2 += ' ';
}
args2 += Console::Utility::trim(args[i]);
}
auto cmd = it->second;
cmd->commandGeneric(fd, args2);
2021-12-25 10:04:45 +08:00
}
else
{
throw std::runtime_error(std::string{"Unknown command "}.append(command).append(". Type 'help' for options\n"));
2019-11-23 20:27:39 +08:00
}
}
void Console::addClient()
{
struct sockaddr_in6 ipv6Addr;
struct sockaddr_in ipv4Addr;
struct sockaddr* addr = _isIpv6Server ? (struct sockaddr*)&ipv6Addr : (struct sockaddr*)&ipv4Addr;
2021-12-25 10:04:45 +08:00
socklen_t addrLen = _isIpv6Server ? sizeof(ipv6Addr) : sizeof(ipv4Addr);
2019-11-23 20:27:39 +08:00
/* new client */
2021-10-09 13:48:56 +08:00
socket_native_type fd = accept(_listenfd, addr, &addrLen);
2021-12-25 10:04:45 +08:00
2019-11-23 20:27:39 +08:00
// add fd to list of FD
2021-12-25 10:04:45 +08:00
if (fd != -1)
{
2019-11-23 20:27:39 +08:00
FD_SET(fd, &_read_set);
_fds.push_back(fd);
2021-12-25 10:04:45 +08:00
_maxfd = (std::max)(_maxfd, fd);
2019-11-23 20:27:39 +08:00
Console::Utility::sendPrompt(fd);
2021-12-25 10:04:45 +08:00
2019-11-23 20:27:39 +08:00
/**
* A SIGPIPE is sent to a process if it tried to write to socket that had been shutdown for
* writing or isn't connected (anymore) on iOS.
*
* The default behaviour for this signal is to end the process.So we make the process ignore SIGPIPE.
*/
#if CC_TARGET_PLATFORM == CC_PLATFORM_IOS
int set = 1;
setsockopt(fd, SOL_SOCKET, SO_NOSIGPIPE, (void*)&set, sizeof(int));
#endif
}
}
//
// create commands
//
void Console::createCommandAllocator()
{
addCommand({"allocator", "Display allocator diagnostics for all allocators. Args: [-h | help | ]",
2021-12-25 10:04:45 +08:00
CC_CALLBACK_2(Console::commandAllocator, this)});
2019-11-23 20:27:39 +08:00
}
void Console::createCommandConfig()
{
addCommand({"config", "Print the Configuration object. Args: [-h | help | ]",
2021-12-25 10:04:45 +08:00
CC_CALLBACK_2(Console::commandConfig, this)});
2019-11-23 20:27:39 +08:00
}
void Console::createCommandDebugMsg()
{
2021-12-25 10:04:45 +08:00
addCommand({"debugmsg",
"Whether or not to forward the debug messages on the console. Args: [-h | help | on | off | ]",
CC_CALLBACK_2(Console::commandDebugMsg, this)});
addSubCommand("debugmsg",
{"on", "enable debug logging", CC_CALLBACK_2(Console::commandDebugMsgSubCommandOnOff, this)});
addSubCommand("debugmsg",
{"off", "disable debug logging", CC_CALLBACK_2(Console::commandDebugMsgSubCommandOnOff, this)});
2019-11-23 20:27:39 +08:00
}
void Console::createCommandDirector()
{
addCommand({"director", "director commands, type -h or [director help] to list supported directives"});
2021-12-25 10:04:45 +08:00
addSubCommand("director",
{"pause", "pause all scheduled timers, the draw rate will be 4 FPS to reduce CPU consumption",
CC_CALLBACK_2(Console::commandDirectorSubCommandPause, this)});
2019-11-23 20:27:39 +08:00
addSubCommand("director", {"resume", "resume all scheduled timers",
2021-12-25 10:04:45 +08:00
CC_CALLBACK_2(Console::commandDirectorSubCommandResume, this)});
addSubCommand("director", {"stop", "Stops the animation. Nothing will be drawn.",
CC_CALLBACK_2(Console::commandDirectorSubCommandStop, this)});
addSubCommand(
"director",
{"start", "Restart the animation again, Call this function only if [director stop] was called earlier",
CC_CALLBACK_2(Console::commandDirectorSubCommandStart, this)});
addSubCommand("director", {"end", "exit this app.", CC_CALLBACK_2(Console::commandDirectorSubCommandEnd, this)});
2019-11-23 20:27:39 +08:00
}
void Console::createCommandExit()
{
2021-12-25 10:04:45 +08:00
addCommand(
{"exit", "Close connection to the console. Args: [-h | help | ]", CC_CALLBACK_2(Console::commandExit, this)});
2019-11-23 20:27:39 +08:00
}
void Console::createCommandFileUtils()
{
addCommand({"fileutils", "Flush or print the FileUtils info. Args: [-h | help | flush | ]",
2021-12-25 10:04:45 +08:00
CC_CALLBACK_2(Console::commandFileUtils, this)});
2019-11-23 20:27:39 +08:00
addSubCommand("fileutils", {"flush", "Purges the file searching cache.",
2021-12-25 10:04:45 +08:00
CC_CALLBACK_2(Console::commandFileUtilsSubCommandFlush, this)});
2019-11-23 20:27:39 +08:00
}
void Console::createCommandFps()
{
2021-12-25 10:04:45 +08:00
addCommand(
{"fps", "Turn on / off the FPS. Args: [-h | help | on | off | ]", CC_CALLBACK_2(Console::commandFps, this)});
addSubCommand("fps", {"on", "Display the FPS on the bottom-left corner.",
CC_CALLBACK_2(Console::commandFpsSubCommandOnOff, this)});
addSubCommand("fps", {"off", "Hide the FPS on the bottom-left corner.",
CC_CALLBACK_2(Console::commandFpsSubCommandOnOff, this)});
2019-11-23 20:27:39 +08:00
}
void Console::createCommandHelp()
{
addCommand({"help", "Print this message. Args: [ ]", CC_CALLBACK_2(Console::commandHelp, this)});
}
void Console::createCommandProjection()
{
addCommand({"projection", "Change or print the current projection. Args: [-h | help | 2d | 3d | ]",
2021-12-25 10:04:45 +08:00
CC_CALLBACK_2(Console::commandProjection, this)});
2019-11-23 20:27:39 +08:00
addSubCommand("projection", {"2d", "sets a 2D projection (orthogonal projection).",
2021-12-25 10:04:45 +08:00
CC_CALLBACK_2(Console::commandProjectionSubCommand2d, this)});
2019-11-23 20:27:39 +08:00
addSubCommand("projection", {"3d", "sets a 3D projection with a fovy=60, znear=0.5f and zfar=1500.",
2021-12-25 10:04:45 +08:00
CC_CALLBACK_2(Console::commandProjectionSubCommand3d, this)});
2019-11-23 20:27:39 +08:00
}
void Console::createCommandResolution()
{
2021-12-25 10:04:45 +08:00
addCommand({"resolution",
"Change or print the window resolution. Args: [-h | help | width height resolution_policy | ]",
CC_CALLBACK_2(Console::commandResolution, this)});
2019-11-23 20:27:39 +08:00
addSubCommand("resolution", {"", "", CC_CALLBACK_2(Console::commandResolutionSubCommandEmpty, this)});
}
void Console::createCommandSceneGraph()
{
addCommand({"scenegraph", "Print the scene graph", CC_CALLBACK_2(Console::commandSceneGraph, this)});
}
void Console::createCommandTexture()
{
addCommand({"texture", "Flush or print the TextureCache info. Args: [-h | help | flush | ] ",
2021-12-25 10:04:45 +08:00
CC_CALLBACK_2(Console::commandTextures, this)});
2019-11-23 20:27:39 +08:00
addSubCommand("texture", {"flush", "Purges the dictionary of loaded textures.",
2021-12-25 10:04:45 +08:00
CC_CALLBACK_2(Console::commandTexturesSubCommandFlush, this)});
2019-11-23 20:27:39 +08:00
}
void Console::createCommandTouch()
{
addCommand({"touch", "simulate touch event via console, type -h or [touch help] to list supported directives"});
addSubCommand("touch", {"tap", "touch tap x y: simulate touch tap at (x,y).",
2021-12-25 10:04:45 +08:00
CC_CALLBACK_2(Console::commandTouchSubCommandTap, this)});
2019-11-23 20:27:39 +08:00
addSubCommand("touch", {"swipe", "touch swipe x1 y1 x2 y2: simulate touch swipe from (x1,y1) to (x2,y2).",
2021-12-25 10:04:45 +08:00
CC_CALLBACK_2(Console::commandTouchSubCommandSwipe, this)});
2019-11-23 20:27:39 +08:00
}
void Console::createCommandUpload()
{
2021-12-25 10:04:45 +08:00
addCommand(
{"upload", "upload file. Args: [filename base64_encoded_data]", CC_CALLBACK_1(Console::commandUpload, this)});
2019-11-23 20:27:39 +08:00
}
void Console::createCommandVersion()
{
addCommand({"version", "print version string ", CC_CALLBACK_2(Console::commandVersion, this)});
}
//
// commands
//
void Console::commandAllocator(socket_native_type fd, std::string_view /*args*/)
2019-11-23 20:27:39 +08:00
{
#if CC_ENABLE_ALLOCATOR_DIAGNOSTICS
auto info = allocator::AllocatorDiagnostics::instance()->diagnostics();
Console::Utility::mydprintf(fd, info.c_str());
#else
2021-12-25 10:04:45 +08:00
Console::Utility::mydprintf(
fd, "allocator diagnostics not available. CC_ENABLE_ALLOCATOR_DIAGNOSTICS must be set to 1 in ccConfig.h\n");
2019-11-23 20:27:39 +08:00
#endif
}
void Console::commandConfig(socket_native_type fd, std::string_view /*args*/)
2019-11-23 20:27:39 +08:00
{
2021-12-25 10:04:45 +08:00
Scheduler* sched = Director::getInstance()->getScheduler();
sched->performFunctionInCocosThread([=]() {
2019-11-23 20:27:39 +08:00
Console::Utility::mydprintf(fd, "%s", Configuration::getInstance()->getInfo().c_str());
Console::Utility::sendPrompt(fd);
});
}
void Console::commandDebugMsg(socket_native_type fd, std::string_view /*args*/)
2019-11-23 20:27:39 +08:00
{
Console::Utility::mydprintf(fd, "Debug message is: %s\n", _sendDebugStrings ? "on" : "off");
}
void Console::commandDebugMsgSubCommandOnOff(socket_native_type /*fd*/, std::string_view args)
2019-11-23 20:27:39 +08:00
{
_sendDebugStrings = (args.compare("on") == 0);
}
void Console::commandDirectorSubCommandPause(socket_native_type /*fd*/, std::string_view /*args*/)
2019-11-23 20:27:39 +08:00
{
2021-12-25 10:04:45 +08:00
auto director = Director::getInstance();
Scheduler* sched = director->getScheduler();
sched->performFunctionInCocosThread([]() { Director::getInstance()->pause(); });
2019-11-23 20:27:39 +08:00
}
void Console::commandDirectorSubCommandResume(socket_native_type /*fd*/, std::string_view /*args*/)
2019-11-23 20:27:39 +08:00
{
auto director = Director::getInstance();
director->resume();
}
void Console::commandDirectorSubCommandStop(socket_native_type /*fd*/, std::string_view /*args*/)
2019-11-23 20:27:39 +08:00
{
2021-12-25 10:04:45 +08:00
auto director = Director::getInstance();
Scheduler* sched = director->getScheduler();
sched->performFunctionInCocosThread([]() { Director::getInstance()->stopAnimation(); });
2019-11-23 20:27:39 +08:00
}
void Console::commandDirectorSubCommandStart(socket_native_type /*fd*/, std::string_view /*args*/)
2019-11-23 20:27:39 +08:00
{
auto director = Director::getInstance();
director->startAnimation();
}
void Console::commandDirectorSubCommandEnd(socket_native_type /*fd*/, std::string_view /*args*/)
2019-11-23 20:27:39 +08:00
{
auto director = Director::getInstance();
director->end();
}
void Console::commandExit(socket_native_type fd, std::string_view /*args*/)
2019-11-23 20:27:39 +08:00
{
FD_CLR(fd, &_read_set);
_fds.erase(std::remove(_fds.begin(), _fds.end(), fd), _fds.end());
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32)
closesocket(fd);
#else
close(fd);
#endif
}
void Console::commandFileUtils(socket_native_type fd, std::string_view /*args*/)
2019-11-23 20:27:39 +08:00
{
2021-12-25 10:04:45 +08:00
Scheduler* sched = Director::getInstance()->getScheduler();
sched->performFunctionInCocosThread(std::bind(&Console::printFileUtils, this, fd));
2019-11-23 20:27:39 +08:00
}
void Console::commandFileUtilsSubCommandFlush(socket_native_type /*fd*/, std::string_view /*args*/)
2019-11-23 20:27:39 +08:00
{
FileUtils::getInstance()->purgeCachedEntries();
}
void Console::commandFps(socket_native_type fd, std::string_view /*args*/)
2019-11-23 20:27:39 +08:00
{
Console::Utility::mydprintf(fd, "FPS is: %s\n", Director::getInstance()->isDisplayStats() ? "on" : "off");
}
void Console::commandFpsSubCommandOnOff(socket_native_type /*fd*/, std::string_view args)
2019-11-23 20:27:39 +08:00
{
2021-12-25 10:04:45 +08:00
bool state = (args.compare("on") == 0);
Director* dir = Director::getInstance();
Scheduler* sched = dir->getScheduler();
sched->performFunctionInCocosThread(std::bind(&Director::setDisplayStats, dir, state));
2019-11-23 20:27:39 +08:00
}
void Console::commandHelp(socket_native_type fd, std::string_view /*args*/)
2019-11-23 20:27:39 +08:00
{
sendHelp(fd, _commands, "\nAvailable commands:\n");
}
void Console::commandProjection(socket_native_type fd, std::string_view /*args*/)
2019-11-23 20:27:39 +08:00
{
auto director = Director::getInstance();
char buf[20];
auto proj = director->getProjection();
2021-12-25 10:04:45 +08:00
switch (proj)
{
case cocos2d::Director::Projection::_2D:
sprintf(buf, "2d");
break;
case cocos2d::Director::Projection::_3D:
sprintf(buf, "3d");
break;
case cocos2d::Director::Projection::CUSTOM:
sprintf(buf, "custom");
break;
default:
sprintf(buf, "unknown");
break;
2019-11-23 20:27:39 +08:00
}
Console::Utility::mydprintf(fd, "Current projection: %s\n", buf);
}
void Console::commandProjectionSubCommand2d(socket_native_type /*fd*/, std::string_view /*args*/)
2019-11-23 20:27:39 +08:00
{
2021-12-25 10:04:45 +08:00
auto director = Director::getInstance();
Scheduler* sched = director->getScheduler();
sched->performFunctionInCocosThread([=]() { director->setProjection(Director::Projection::_2D); });
2019-11-23 20:27:39 +08:00
}
void Console::commandProjectionSubCommand3d(socket_native_type /*fd*/, std::string_view /*args*/)
2019-11-23 20:27:39 +08:00
{
2021-12-25 10:04:45 +08:00
auto director = Director::getInstance();
Scheduler* sched = director->getScheduler();
sched->performFunctionInCocosThread([=]() { director->setProjection(Director::Projection::_3D); });
2019-11-23 20:27:39 +08:00
}
void Console::commandResolution(socket_native_type /*fd*/, std::string_view args)
2019-11-23 20:27:39 +08:00
{
int policy;
float width, height;
std::stringstream stream;
stream << args;
2021-12-25 10:04:45 +08:00
stream >> width >> height >> policy;
Scheduler* sched = Director::getInstance()->getScheduler();
sched->performFunctionInCocosThread([=]() {
Director::getInstance()->getOpenGLView()->setDesignResolutionSize(width, height,
static_cast<ResolutionPolicy>(policy));
});
2019-11-23 20:27:39 +08:00
}
void Console::commandResolutionSubCommandEmpty(socket_native_type fd, std::string_view /*args*/)
2019-11-23 20:27:39 +08:00
{
2021-12-25 10:04:45 +08:00
auto director = Director::getInstance();
Vec2 points = director->getWinSize();
Vec2 pixels = director->getWinSizeInPixels();
auto glview = director->getOpenGLView();
Vec2 design = glview->getDesignResolutionSize();
2019-11-23 20:27:39 +08:00
ResolutionPolicy res = glview->getResolutionPolicy();
2021-12-25 10:04:45 +08:00
Rect visibleRect = glview->getVisibleRect();
Console::Utility::mydprintf(fd,
"Window size:\n"
"\t%d x %d (points)\n"
"\t%d x %d (pixels)\n"
"\t%d x %d (design resolution)\n"
"Resolution Policy: %d\n"
"Visible Rect:\n"
"\torigin: %d x %d\n"
"\tsize: %d x %d\n",
(int)points.width, (int)points.height, (int)pixels.width, (int)pixels.height,
(int)design.width, (int)design.height, (int)res, (int)visibleRect.origin.x,
(int)visibleRect.origin.y, (int)visibleRect.size.width, (int)visibleRect.size.height);
2019-11-23 20:27:39 +08:00
}
void Console::commandSceneGraph(socket_native_type fd, std::string_view /*args*/)
2019-11-23 20:27:39 +08:00
{
2021-12-25 10:04:45 +08:00
Scheduler* sched = Director::getInstance()->getScheduler();
sched->performFunctionInCocosThread(std::bind(&Console::printSceneGraphBoot, this, fd));
2019-11-23 20:27:39 +08:00
}
void Console::commandTextures(socket_native_type fd, std::string_view /*args*/)
2019-11-23 20:27:39 +08:00
{
2021-12-25 10:04:45 +08:00
Scheduler* sched = Director::getInstance()->getScheduler();
sched->performFunctionInCocosThread([=]() {
Console::Utility::mydprintf(fd, "%s",
Director::getInstance()->getTextureCache()->getCachedTextureInfo().c_str());
2019-11-23 20:27:39 +08:00
Console::Utility::sendPrompt(fd);
});
}
void Console::commandTexturesSubCommandFlush(socket_native_type /*fd*/, std::string_view /*args*/)
2019-11-23 20:27:39 +08:00
{
2021-12-25 10:04:45 +08:00
Scheduler* sched = Director::getInstance()->getScheduler();
sched->performFunctionInCocosThread([]() { Director::getInstance()->getTextureCache()->removeAllTextures(); });
2019-11-23 20:27:39 +08:00
}
void Console::commandTouchSubCommandTap(socket_native_type fd, std::string_view args)
2019-11-23 20:27:39 +08:00
{
2021-12-25 10:04:45 +08:00
auto argv = Console::Utility::split(args, ' ');
if ((argv.size() == 3) && (Console::Utility::isFloat(argv[1]) && Console::Utility::isFloat(argv[2])))
2019-11-23 20:27:39 +08:00
{
2021-12-25 10:04:45 +08:00
2019-11-23 20:27:39 +08:00
float x = (float)utils::atof(argv[1].c_str());
float y = (float)utils::atof(argv[2].c_str());
2021-12-25 10:04:45 +08:00
std::srand((unsigned)time(nullptr));
_touchId = rand();
Scheduler* sched = Director::getInstance()->getScheduler();
sched->performFunctionInCocosThread([&]() {
2019-11-23 20:27:39 +08:00
Director::getInstance()->getOpenGLView()->handleTouchesBegin(1, &_touchId, &x, &y);
Director::getInstance()->getOpenGLView()->handleTouchesEnd(1, &_touchId, &x, &y);
});
}
else
{
const char msg[] = "touch: invalid arguments.\n";
Console::Utility::sendToConsole(fd, msg, strlen(msg));
}
}
void Console::commandTouchSubCommandSwipe(socket_native_type fd, std::string_view args)
2019-11-23 20:27:39 +08:00
{
2021-12-25 10:04:45 +08:00
auto argv = Console::Utility::split(args, ' ');
if ((argv.size() == 5) && (Console::Utility::isFloat(argv[1])) && (Console::Utility::isFloat(argv[2])) &&
(Console::Utility::isFloat(argv[3])) && (Console::Utility::isFloat(argv[4])))
2019-11-23 20:27:39 +08:00
{
2021-12-25 10:04:45 +08:00
2019-11-23 20:27:39 +08:00
float x1 = (float)utils::atof(argv[1].c_str());
float y1 = (float)utils::atof(argv[2].c_str());
float x2 = (float)utils::atof(argv[3].c_str());
float y2 = (float)utils::atof(argv[4].c_str());
2021-12-25 10:04:45 +08:00
std::srand((unsigned)time(nullptr));
2019-11-23 20:27:39 +08:00
_touchId = rand();
2021-12-25 10:04:45 +08:00
Scheduler* sched = Director::getInstance()->getScheduler();
sched->performFunctionInCocosThread([=]() {
2019-11-23 20:27:39 +08:00
float tempx = x1, tempy = y1;
Director::getInstance()->getOpenGLView()->handleTouchesBegin(1, &_touchId, &tempx, &tempy);
});
2021-12-25 10:04:45 +08:00
float dx = std::abs(x1 - x2);
float dy = std::abs(y1 - y2);
2019-11-23 20:27:39 +08:00
float _x_ = x1, _y_ = y1;
2021-12-25 10:04:45 +08:00
if (dx > dy)
2019-11-23 20:27:39 +08:00
{
2021-12-25 10:04:45 +08:00
while (dx > 1)
2019-11-23 20:27:39 +08:00
{
2021-12-25 10:04:45 +08:00
if (x1 < x2)
2019-11-23 20:27:39 +08:00
{
_x_ += 1;
}
2021-12-25 10:04:45 +08:00
if (x1 > x2)
2019-11-23 20:27:39 +08:00
{
_x_ -= 1;
}
2021-12-25 10:04:45 +08:00
if (y1 < y2)
2019-11-23 20:27:39 +08:00
{
2021-12-25 10:04:45 +08:00
_y_ += dy / dx;
2019-11-23 20:27:39 +08:00
}
2021-12-25 10:04:45 +08:00
if (y1 > y2)
2019-11-23 20:27:39 +08:00
{
2021-12-25 10:04:45 +08:00
_y_ -= dy / dx;
2019-11-23 20:27:39 +08:00
}
2021-12-25 10:04:45 +08:00
sched->performFunctionInCocosThread([=]() {
2019-11-23 20:27:39 +08:00
float tempx = _x_, tempy = _y_;
Director::getInstance()->getOpenGLView()->handleTouchesMove(1, &_touchId, &tempx, &tempy);
});
dx -= 1;
}
}
else
{
2021-12-25 10:04:45 +08:00
while (dy > 1)
2019-11-23 20:27:39 +08:00
{
2021-12-25 10:04:45 +08:00
if (x1 < x2)
2019-11-23 20:27:39 +08:00
{
2021-12-25 10:04:45 +08:00
_x_ += dx / dy;
2019-11-23 20:27:39 +08:00
}
2021-12-25 10:04:45 +08:00
if (x1 > x2)
2019-11-23 20:27:39 +08:00
{
2021-12-25 10:04:45 +08:00
_x_ -= dx / dy;
2019-11-23 20:27:39 +08:00
}
2021-12-25 10:04:45 +08:00
if (y1 < y2)
2019-11-23 20:27:39 +08:00
{
_y_ += 1;
}
2021-12-25 10:04:45 +08:00
if (y1 > y2)
2019-11-23 20:27:39 +08:00
{
_y_ -= 1;
}
2021-12-25 10:04:45 +08:00
sched->performFunctionInCocosThread([=]() {
2019-11-23 20:27:39 +08:00
float tempx = _x_, tempy = _y_;
Director::getInstance()->getOpenGLView()->handleTouchesMove(1, &_touchId, &tempx, &tempy);
});
dy -= 1;
}
}
2021-12-25 10:04:45 +08:00
sched->performFunctionInCocosThread([=]() {
2019-11-23 20:27:39 +08:00
float tempx = x2, tempy = y2;
Director::getInstance()->getOpenGLView()->handleTouchesEnd(1, &_touchId, &tempx, &tempy);
});
}
else
{
const char msg[] = "touch: invalid arguments.\n";
Console::Utility::sendToConsole(fd, msg, strlen(msg));
}
}
static char invalid_filename_char[] = {':', '/', '\\', '?', '%', '*', '<', '>', '"', '|', '\r', '\n', '\t'};
2021-10-09 13:48:56 +08:00
void Console::commandUpload(socket_native_type fd)
2019-11-23 20:27:39 +08:00
{
ssize_t n, rc;
char buf[512] = {0};
2021-12-25 10:04:45 +08:00
char c = 0;
char* ptr = buf;
// read file name
for (n = 0; n < sizeof(buf) - 1; n++)
2019-11-23 20:27:39 +08:00
{
2021-12-25 10:04:45 +08:00
if ((rc = recv(fd, &c, 1, 0)) == 1)
2019-11-23 20:27:39 +08:00
{
2021-12-25 10:04:45 +08:00
for (char x : invalid_filename_char)
2019-11-23 20:27:39 +08:00
{
if (c == x)
{
const char err[] = "upload: invalid file name!\n";
Console::Utility::sendToConsole(fd, err, strlen(err));
return;
}
}
if (c == ' ')
{
break;
}
*ptr++ = c;
2021-12-25 10:04:45 +08:00
}
else if (rc == 0)
2019-11-23 20:27:39 +08:00
{
break;
2021-12-25 10:04:45 +08:00
}
else if (errno == EINTR)
2019-11-23 20:27:39 +08:00
{
continue;
2021-12-25 10:04:45 +08:00
}
else
2019-11-23 20:27:39 +08:00
{
break;
}
}
*ptr = 0;
static std::string writablePath = FileUtils::getInstance()->getWritablePath();
2021-12-25 10:04:45 +08:00
std::string filepath = writablePath + std::string(buf);
2019-11-23 20:27:39 +08:00
auto fs = FileUtils::getInstance()->openFileStream(filepath, FileStream::Mode::WRITE);
2021-12-25 10:04:45 +08:00
if (!fs)
2019-11-23 20:27:39 +08:00
{
const char err[] = "can't create file!\n";
Console::Utility::sendToConsole(fd, err, strlen(err));
return;
}
while (true)
{
char data[4];
2021-12-25 10:04:45 +08:00
for (int i = 0; i < 4; i++)
2019-11-23 20:27:39 +08:00
{
data[i] = '=';
}
bool more_data;
readBytes(fd, data, 4, &more_data);
2021-12-25 10:04:45 +08:00
if (!more_data)
2019-11-23 20:27:39 +08:00
{
break;
}
2021-12-25 10:04:45 +08:00
unsigned char* decode;
unsigned char* in = (unsigned char*)data;
int dt = base64Decode(in, 4, &decode);
2019-11-23 20:27:39 +08:00
if (dt > 0)
{
fs->write(decode, dt);
2019-11-23 20:27:39 +08:00
}
free(decode);
}
}
void Console::commandVersion(socket_native_type fd, std::string_view /*args*/)
2019-11-23 20:27:39 +08:00
{
2021-10-25 20:29:40 +08:00
Console::Utility::mydprintf(fd, "%s\n", adxeVersion());
2019-11-23 20:27:39 +08:00
}
// helper free functions
2021-10-09 13:48:56 +08:00
int Console::printSceneGraph(socket_native_type fd, Node* node, int level)
2019-11-23 20:27:39 +08:00
{
int total = 1;
2021-12-25 10:04:45 +08:00
for (int i = 0; i < level; ++i)
2019-11-23 20:27:39 +08:00
Console::Utility::sendToConsole(fd, "-", 1);
2021-12-25 10:04:45 +08:00
2019-11-23 20:27:39 +08:00
Console::Utility::mydprintf(fd, " %s\n", node->getDescription().c_str());
2021-12-25 10:04:45 +08:00
for (const auto& child : node->getChildren())
total += printSceneGraph(fd, child, level + 1);
2019-11-23 20:27:39 +08:00
return total;
}
2021-10-09 13:48:56 +08:00
void Console::printSceneGraphBoot(socket_native_type fd)
2019-11-23 20:27:39 +08:00
{
2021-12-25 10:04:45 +08:00
Console::Utility::sendToConsole(fd, "\n", 1);
2019-11-23 20:27:39 +08:00
auto scene = Director::getInstance()->getRunningScene();
2021-12-25 10:04:45 +08:00
int total = printSceneGraph(fd, scene, 0);
2019-11-23 20:27:39 +08:00
Console::Utility::mydprintf(fd, "Total Nodes: %d\n", total);
Console::Utility::sendPrompt(fd);
}
2021-10-09 13:48:56 +08:00
void Console::printFileUtils(socket_native_type fd)
2019-11-23 20:27:39 +08:00
{
FileUtils* fu = FileUtils::getInstance();
2021-12-25 10:04:45 +08:00
2019-11-23 20:27:39 +08:00
Console::Utility::mydprintf(fd, "\nSearch Paths:\n");
auto& list = fu->getSearchPaths();
2021-12-25 10:04:45 +08:00
for (const auto& item : list)
{
2019-11-23 20:27:39 +08:00
Console::Utility::mydprintf(fd, "%s\n", item.c_str());
}
2021-12-25 10:04:45 +08:00
2019-11-23 20:27:39 +08:00
Console::Utility::mydprintf(fd, "\nResolution Order:\n");
auto& list1 = fu->getSearchResolutionsOrder();
2021-12-25 10:04:45 +08:00
for (const auto& item : list1)
{
2019-11-23 20:27:39 +08:00
Console::Utility::mydprintf(fd, "%s\n", item.c_str());
}
2021-12-25 10:04:45 +08:00
2019-11-23 20:27:39 +08:00
Console::Utility::mydprintf(fd, "\nWritable Path:\n");
Console::Utility::mydprintf(fd, "%s\n", fu->getWritablePath().c_str());
2021-12-25 10:04:45 +08:00
2019-11-23 20:27:39 +08:00
Console::Utility::mydprintf(fd, "\nFull Path Cache:\n");
auto& cache = fu->getFullPathCache();
2021-12-25 10:04:45 +08:00
for (const auto& item : cache)
{
2019-11-23 20:27:39 +08:00
Console::Utility::mydprintf(fd, "%s -> %s\n", item.first.c_str(), item.second.c_str());
}
Console::Utility::sendPrompt(fd);
}
void Console::sendHelp(socket_native_type fd, const hlookup::string_map<Command*>& commands, const char* msg)
2019-11-23 20:27:39 +08:00
{
Console::Utility::sendToConsole(fd, msg, strlen(msg));
2021-12-25 10:04:45 +08:00
for (auto& it : commands)
2019-11-23 20:27:39 +08:00
{
auto command = it.second;
2021-12-25 10:04:45 +08:00
if (command->getHelp().empty())
continue;
Console::Utility::mydprintf(fd, "\t%s", command->getName().data());
ssize_t tabs = command->getName().length() / 8;
2021-12-25 10:04:45 +08:00
tabs = 3 - tabs;
for (int j = 0; j < tabs; j++)
{
2019-11-23 20:27:39 +08:00
Console::Utility::mydprintf(fd, "\t");
}
Console::Utility::mydprintf(fd, "%s\n", command->getHelp().data());
2019-11-23 20:27:39 +08:00
}
}
NS_CC_END