Use std::shared_ptr for Request to avoid leaking

This commit is contained in:
Benau 2019-11-30 16:01:31 +08:00
parent 77d563d082
commit 13975cc5db
41 changed files with 128 additions and 227 deletions

View File

@ -391,7 +391,7 @@ void Achievement::onCompletion()
// completed, if a user is signed in.
if (PlayerManager::isCurrentLoggedIn())
{
Online::HTTPRequest * request = new Online::HTTPRequest(true);
auto request = std::make_shared<Online::HTTPRequest>();
PlayerManager::setUserDetails(request, "achieving");
request->addParameter("achievementid", getID());
request->queue();

View File

@ -370,7 +370,7 @@ void AchievementsStatus::sync(const std::vector<uint32_t> & achieved_ids)
ids = ids.substr(0, ids.size() - 1); // delete the last "," in the string
Log::info("Achievements", "Synching achievement %s to server.",
ids.c_str());
Online::HTTPRequest * request = new Online::HTTPRequest(true, 2);
auto request = std::make_shared<Online::HTTPRequest>(true, 2);
PlayerManager::setUserDetails(request, "achieving");
request->addParameter("achievementid", ids);
request->queue();

View File

@ -126,17 +126,15 @@ void AddonsManager::init(const XMLNode *xml,
if (download)
{
Log::info("addons", "Downloading updated addons.xml.");
Online::HTTPRequest *download_request = new Online::HTTPRequest("addons.xml");
auto download_request = std::make_shared<Online::HTTPRequest>("addons.xml");
download_request->setURL(addon_list_url);
download_request->executeNow();
if(download_request->hadDownloadError())
{
Log::error("addons", "Error on download addons.xml: %s.",
download_request->getDownloadErrorMessage());
delete download_request;
return;
}
delete download_request;
UserConfigParams::m_addons_last_updated=StkTime::getTimeSinceEpoch();
}
else
@ -403,7 +401,7 @@ void AddonsManager::downloadIcons()
m_addon = addon; setURL(url);
} // IconRequest
};
IconRequest *r = new IconRequest("icons/"+icon, url, &addon);
auto r = std::make_shared<IconRequest>("icons/"+icon, url, &addon);
r->queue();
}
else

View File

@ -150,7 +150,7 @@ void* NewsManager::downloadNews(void *obj)
{
core::stringw error_message("");
HTTPRequest *download_req = new HTTPRequest(m_news_filename);
auto download_req = std::make_shared<HTTPRequest>(m_news_filename);
download_req->setAddonsURL(m_news_filename);
// Initialise the online portion of the addons manager.
@ -164,11 +164,9 @@ void* NewsManager::downloadNews(void *obj)
// with the default server address again (just in case
// that a redirect went wrong, or a wrong/incorrect
// address somehow made its way into the config file.
delete download_req;
// We need a new object, since the state of the old
// download request is now done.
download_req = new HTTPRequest(m_news_filename);
download_req = std::make_shared<HTTPRequest>(m_news_filename);
// make sure the new server address is actually used
download_req->setAddonsURL(m_news_filename);
@ -190,7 +188,6 @@ void* NewsManager::downloadNews(void *obj)
if(!download_req->hadDownloadError())
UserConfigParams::m_news_last_updated = StkTime::getTimeSinceEpoch();
delete download_req;
// No download error, update the last_updated time value, and delete
// the potentially loaded xml file

View File

@ -401,7 +401,7 @@ void reportHardwareStats()
}; // HWReportRequest
// ------------------------------------------------------------------------
Online::HTTPRequest *request = new HWReportRequest(report_version);
auto request = std::make_shared<HWReportRequest>(report_version);
request->addParameter("user_id", UserConfigParams::m_random_identifier);
request->addParameter("time", StkTime::getTimeSinceEpoch());
request->addParameter("type", "hwdetect");

View File

@ -49,7 +49,7 @@ void PlayerManager::create()
* \param request The http request.
* \param action If not empty, the action to be set.
*/
void PlayerManager::setUserDetails(Online::HTTPRequest *request,
void PlayerManager::setUserDetails(std::shared_ptr<Online::HTTPRequest> request,
const std::string &action,
const std::string &php_name)
{

View File

@ -28,6 +28,7 @@
#include <irrString.h>
#include <cstddef> // NULL
#include <memory>
class AchievementsStatus;
@ -97,7 +98,7 @@ public:
const PlayerProfile *getPlayerById(unsigned int id);
void enforceCurrentPlayer();
unsigned int getNumNonGuestPlayers() const;
static void setUserDetails(Online::HTTPRequest *request,
static void setUserDetails(std::shared_ptr<Online::HTTPRequest> request,
const std::string &action,
const std::string &php_name = "");
static unsigned int getCurrentOnlineId();

View File

@ -129,7 +129,7 @@ public:
void addIcon();
/** Abstract virtual classes, to be implemented by the OnlinePlayer. */
virtual void setUserDetails(Online::HTTPRequest *request,
virtual void setUserDetails(std::shared_ptr<Online::HTTPRequest> request,
const std::string &action,
const std::string &url_path = "") const = 0;
virtual uint32_t getOnlineId() const = 0;

View File

@ -73,7 +73,7 @@ void NetworkConfig::unsetNetworking()
} // unsetNetworking
// ----------------------------------------------------------------------------
void NetworkConfig::setUserDetails(Online::XMLRequest* r,
void NetworkConfig::setUserDetails(std::shared_ptr<Online::XMLRequest> r,
const std::string& name)
{
assert(!m_cur_user_token.empty());
@ -83,8 +83,8 @@ void NetworkConfig::setUserDetails(Online::XMLRequest* r,
} // setUserDetails
// ----------------------------------------------------------------------------
void NetworkConfig::setServerDetails(Online::XMLRequest* r,
const std::string& name)
void NetworkConfig::setServerDetails(std::shared_ptr<Online::XMLRequest> r,
const std::string& name)
{
assert(!m_cur_user_token.empty());
r->setApiURL(Online::API::SERVER_PATH, name);

View File

@ -27,6 +27,7 @@
#include "utils/no_copy.hpp"
#include "irrString.h"
#include <memory>
#include <set>
#include <tuple>
#include <vector>
@ -213,9 +214,11 @@ public:
// ------------------------------------------------------------------------
const std::string& getCurrentUserToken() const { return m_cur_user_token; }
// ------------------------------------------------------------------------
void setUserDetails(Online::XMLRequest* r, const std::string& name);
void setUserDetails(std::shared_ptr<Online::XMLRequest> r,
const std::string& name);
// ------------------------------------------------------------------------
void setServerDetails(Online::XMLRequest* r, const std::string& name);
void setServerDetails(std::shared_ptr<Online::XMLRequest> r,
const std::string& name);
// ------------------------------------------------------------------------
void setServerIdFile(const std::string& id) { m_server_id_file = id; }
// ------------------------------------------------------------------------

View File

@ -113,8 +113,7 @@ ClientLobby::~ClientLobby()
{
if (m_server->supportsEncryption())
{
Online::XMLRequest* request =
new Online::XMLRequest(true/*manager_memory*/);
auto request = std::make_shared<Online::XMLRequest>();
NetworkConfig::get()->setServerDetails(request,
"clear-user-joined-server");
request->queue();

View File

@ -74,8 +74,7 @@ ConnectToServer::~ConnectToServer()
auto cl = LobbyProtocol::get<ClientLobby>();
if (!cl && m_server && m_server->supportsEncryption())
{
Online::XMLRequest* request =
new Online::XMLRequest(true/*manager_memory*/);
auto request = std::make_shared<Online::XMLRequest>();
NetworkConfig::get()->setServerDetails(request,
"clear-user-joined-server");
request->queue();
@ -463,7 +462,7 @@ void ConnectToServer::registerWithSTKServer()
}
const TransportAddress& addr = STKHost::get()->getPublicAddress();
Online::XMLRequest *request = new Online::XMLRequest();
auto request = std::make_shared<Online::XMLRequest>();
NetworkConfig::get()->setServerDetails(request, "join-server-key");
request->addParameter("server-id", m_server->getServerId());
request->addParameter("address", addr.getIP());
@ -495,6 +494,4 @@ void ConnectToServer::registerWithSTKServer()
error.c_str());
m_state = DONE;
}
delete request;
} // registerWithSTKServer

View File

@ -2025,6 +2025,7 @@ bool ServerLobby::registerServer(bool now)
{
private:
std::weak_ptr<ServerLobby> m_server_lobby;
const bool m_execute_now;
protected:
virtual void afterOperation()
{
@ -2062,15 +2063,15 @@ bool ServerLobby::registerServer(bool now)
StringUtils::wideToUtf8(getInfo()).c_str());
// For auto server recovery wait 3 seconds for next try
// This sleep only the request manager thread
if (manageMemory())
if (!m_execute_now)
StkTime::sleep(3000);
}
public:
RegisterServerRequest(bool now, std::shared_ptr<ServerLobby> sl)
: XMLRequest(!now/*manage memory*/), m_server_lobby(sl) {}
: XMLRequest(), m_server_lobby(sl), m_execute_now(now) {}
}; // RegisterServerRequest
RegisterServerRequest *request = new RegisterServerRequest(now,
auto request = std::make_shared<RegisterServerRequest>(now,
std::dynamic_pointer_cast<ServerLobby>(shared_from_this()));
NetworkConfig::get()->setServerDetails(request, "create");
request->addParameter("address", m_server_address.getIP() );
@ -2099,7 +2100,6 @@ bool ServerLobby::registerServer(bool now)
if (now)
{
request->executeNow();
delete request;
if (m_server_id_online.load() == 0)
return false;
}
@ -2118,8 +2118,7 @@ bool ServerLobby::registerServer(bool now)
*/
void ServerLobby::unregisterServer(bool now)
{
Online::XMLRequest* request =
new Online::XMLRequest(!now/*manage memory*/);
auto request = std::make_shared<Online::XMLRequest>();
m_server_unregistered = request->observeExistence();
NetworkConfig::get()->setServerDetails(request, "stop");
@ -2132,7 +2131,6 @@ void ServerLobby::unregisterServer(bool now)
if (now)
{
request->executeNow();
delete request;
}
else
request->queue();
@ -2470,7 +2468,7 @@ void ServerLobby::checkIncomingConnectionRequests()
}; // PollServerRequest
// ========================================================================
PollServerRequest* request = new PollServerRequest(
auto request = std::make_shared<PollServerRequest>(
std::dynamic_pointer_cast<ServerLobby>(shared_from_this()));
NetworkConfig::get()->setServerDetails(request,
"poll-connection-requests");
@ -3952,7 +3950,7 @@ bool ServerLobby::decryptConnectionRequest(std::shared_ptr<STKPeer> peer,
//-----------------------------------------------------------------------------
void ServerLobby::getRankingForPlayer(std::shared_ptr<NetworkPlayerProfile> p)
{
Online::XMLRequest* request = new Online::XMLRequest();
auto request = std::make_shared<Online::XMLRequest>();
NetworkConfig::get()->setUserDetails(request, "get-ranking");
const uint32_t id = p->getOnlineId();
@ -3987,7 +3985,6 @@ void ServerLobby::getRankingForPlayer(std::shared_ptr<NetworkPlayerProfile> p)
m_scores[id] = score;
m_max_scores[id] = max_score;
m_num_ranked_races[id] = num_races;
delete request;
} // getRankingForPlayer
//-----------------------------------------------------------------------------
@ -4004,7 +4001,7 @@ void ServerLobby::submitRankingsToAddons()
SumbitRankingRequest(uint32_t online_id, double scores,
double max_scores, unsigned num_races,
const std::string& country_code)
: XMLRequest(true)
: XMLRequest()
{
addParameter("id", online_id);
addParameter("scores", scores);
@ -4029,7 +4026,7 @@ void ServerLobby::submitRankingsToAddons()
for (unsigned i = 0; i < race_manager->getNumPlayers(); i++)
{
const uint32_t id = race_manager->getKartInfo(i).getOnlineId();
SumbitRankingRequest* request = new SumbitRankingRequest
auto request = std::make_shared<SumbitRankingRequest>
(id, m_scores.at(id), m_max_scores.at(id),
m_num_ranked_races.at(id),
race_manager->getKartInfo(i).getCountryCode());
@ -4495,8 +4492,7 @@ void ServerLobby::handleServerConfiguration(Event* event)
Log::info("ServerLobby", "Updating server info with new "
"difficulty: %d, game mode: %d to stk-addons.", new_difficulty,
new_game_mode);
Online::XMLRequest* request =
new Online::XMLRequest(true/*manage_memory*/);
auto request = std::make_shared<Online::XMLRequest>();
NetworkConfig::get()->setServerDetails(request, "update-config");
request->addParameter("address", m_server_address.getIP());
request->addParameter("port", m_server_address.getPort());

View File

@ -77,7 +77,7 @@ ServersManager::~ServersManager()
/** Returns a WAN update-list-of-servers request. It queries the
* STK server for an up-to-date list of servers.
*/
Online::XMLRequest* ServersManager::getWANRefreshRequest() const
std::shared_ptr<Online::XMLRequest> ServersManager::getWANRefreshRequest() const
{
// ========================================================================
/** A small local class that triggers an update of the ServersManager
@ -97,7 +97,7 @@ Online::XMLRequest* ServersManager::getWANRefreshRequest() const
}; // RefreshRequest
// ========================================================================
Online::XMLRequest *request = new WANRefreshRequest();
auto request = std::make_shared<WANRefreshRequest>();
request->setApiURL(Online::API::SERVER_PATH, "get-all");
return request;
@ -108,7 +108,7 @@ Online::XMLRequest* ServersManager::getWANRefreshRequest() const
* to find LAN servers, and waits for a certain amount of time fr
* answers.
*/
Online::XMLRequest* ServersManager::getLANRefreshRequest() const
std::shared_ptr<Online::XMLRequest> ServersManager::getLANRefreshRequest() const
{
/** A simple class that uses LAN broadcasts to find local servers.
* It is based on XML request, but actually does not use any of the
@ -222,7 +222,7 @@ Online::XMLRequest* ServersManager::getLANRefreshRequest() const
}; // LANRefreshRequest
// ========================================================================
return new LANRefreshRequest();
return std::make_shared<LANRefreshRequest>();
} // getLANRefreshRequest

View File

@ -55,9 +55,9 @@ private:
// ------------------------------------------------------------------------
void setWanServers(bool success, const XMLNode* input);
// ------------------------------------------------------------------------
Online::XMLRequest* getWANRefreshRequest() const;
std::shared_ptr<Online::XMLRequest> getWANRefreshRequest() const;
// ------------------------------------------------------------------------
Online::XMLRequest* getLANRefreshRequest() const;
std::shared_ptr<Online::XMLRequest> getLANRefreshRequest() const;
// ------------------------------------------------------------------------
void setLanServers(const std::map<irr::core::stringw,
std::shared_ptr<Server> >& servers);

View File

@ -53,8 +53,8 @@ namespace Online
{
virtual void callback();
public:
SignInRequest(bool manage_memory)
: XMLRequest(manage_memory, /*priority*/10) {}
SignInRequest()
: XMLRequest(true/*manage_memory*/, /*priority*/10) {}
}; // SignInRequest
// ----------------------------------------------------------------
@ -71,7 +71,7 @@ namespace Online
* \param request The http request.
* \param action the action performed
*/
void OnlinePlayerProfile::setUserDetails(HTTPRequest *request,
void OnlinePlayerProfile::setUserDetails(std::shared_ptr<HTTPRequest> request,
const std::string &action,
const std::string &url_path) const
{
@ -115,8 +115,7 @@ namespace Online
{
if (m_online_state == OS_SIGNED_OUT && hasSavedSession())
{
PrivateRequest::SignInRequest *request =
new PrivateRequest::SignInRequest(true);
auto request = std::make_shared<PrivateRequest::SignInRequest>();
setUserDetails(request, "saved-session");
// The userid must be taken from the saved data,
@ -140,8 +139,7 @@ namespace Online
// logout stil happening.
assert(m_online_state == OS_SIGNED_OUT ||
m_online_state == OS_SIGNING_OUT);
PrivateRequest::SignInRequest * request =
new PrivateRequest::SignInRequest(true);
auto request = std::make_shared<PrivateRequest::SignInRequest>();
// We can't use setUserDetail here, since there is no token yet
request->setApiURL(API::USER_PATH, "connect");
@ -303,15 +301,14 @@ namespace Online
: XMLRequest(true,/*priority*/RequestManager::HTTP_MAX_PRIORITY)
{
m_player = player;
m_player->setUserDetails(this,
m_player->rememberPassword() ? "client-quit"
: "disconnect");
setAbortable(false);
} // SignOutRequest
}; // SignOutRequest
// ----------------------------------------------------------------
HTTPRequest *request = new SignOutRequest(this);
auto request = std::make_shared<SignOutRequest>(this);
setUserDetails(request,
rememberPassword() ? "client-quit" : "disconnect");
request->queue();
m_online_state = OS_SIGNING_OUT;
} // requestSignOut
@ -362,8 +359,7 @@ namespace Online
{
assert(m_online_state == OS_SIGNED_IN);
PrivateRequest::PollRequest *request =
new PrivateRequest::PollRequest();
auto request = std::make_shared<PrivateRequest::PollRequest>();
setUserDetails(request, "poll");
request->queue();
} // requestPoll()

View File

@ -51,7 +51,7 @@ namespace Online
virtual void signOut(bool success, const XMLNode * input,
const irr::core::stringw &info);
virtual uint32_t getOnlineId() const;
virtual void setUserDetails(Online::HTTPRequest *request,
virtual void setUserDetails(std::shared_ptr<HTTPRequest> request,
const std::string &action,
const std::string &url_path = "") const;

View File

@ -154,7 +154,7 @@ void OnlineProfile::fetchAchievements()
}; // class AchievementsRequest
// ------------------------------------------------------------------------
AchievementsRequest * request = new AchievementsRequest();
auto request = std::make_shared<AchievementsRequest>();
PlayerManager::setUserDetails(request, "get-achievements");
request->addParameter("visitingid", m_id);
RequestManager::get()->addRequest(request);
@ -207,7 +207,7 @@ void OnlineProfile::fetchFriends()
}; // class FriendsListRequest
// ------------------------------------------------------------------------
FriendsListRequest * request = new FriendsListRequest();
auto request = std::make_shared<FriendsListRequest>();
PlayerManager::setUserDetails(request, "get-friends-list");
request->addParameter("visitingid", m_id);
RequestManager::get()->addRequest(request);

View File

@ -50,7 +50,7 @@ namespace Online
*/
void Request::queue()
{
RequestManager::get()->addRequest(this);
RequestManager::get()->addRequest(shared_from_this());
} // queue
// ------------------------------------------------------------------------

View File

@ -20,7 +20,6 @@
#define HEADER_ONLINE_REQUEST_HPP
#include "utils/cpp2011.hpp"
#include "utils/leak_check.hpp"
#include "utils/no_copy.hpp"
#include "utils/synchronised.hpp"
@ -29,6 +28,7 @@
#endif
#include <curl/curl.h>
#include <assert.h>
#include <memory>
#include <string>
namespace Online
@ -57,11 +57,10 @@ namespace Online
*
* \ingroup online
*/
class Request : public NoCopy
class Request : public std::enable_shared_from_this<Request>,
public NoCopy
{
private:
LEAK_CHECK()
/** Type of the request. Has 0 as default value. */
const int m_type;
@ -236,7 +235,8 @@ namespace Online
public:
/** Compares two requests, returns if the first request has a lower
* priority than the second one. */
bool operator() (const Request *a, const Request *b) const
bool operator() (const std::shared_ptr<Request>& a,
const std::shared_ptr<Request>& b) const
{
return a->getPriority() < b->getPriority();
}

View File

@ -143,7 +143,10 @@ namespace Online
// Put in a high priortity quit request in. It has the same priority
// as a sign-out request (so the sign-out will be executed before the
// quit request).
Request *quit = new Request(true, HTTP_MAX_PRIORITY, Request::RT_QUIT);
// Required for std::make_shared as it takes reference
int priority = HTTP_MAX_PRIORITY;
auto quit = std::make_shared<Request>(true, priority,
Request::RT_QUIT);
quit->setAbortable(false);
addRequest(quit);
@ -163,7 +166,7 @@ namespace Online
* sorted by priority.
* \param request The pointer to the new request to insert.
*/
void RequestManager::addRequest(Request *request)
void RequestManager::addRequest(std::shared_ptr<Online::Request> request)
{
if (UserConfigParams::m_internet_status == RequestManager::IPERM_NOT_ALLOWED
&& request->getType() != Request::RT_QUIT)
@ -193,7 +196,7 @@ namespace Online
VS::setThreadName("RequestManager");
RequestManager *me = (RequestManager*) obj;
me->m_current_request = NULL;
me->m_current_request = nullptr;
me->m_request_queue.lock();
while (me->m_request_queue.getData().empty() ||
me->m_request_queue.getData().top()->getType() != Request::RT_QUIT)
@ -213,7 +216,6 @@ namespace Online
if (me->m_current_request->getType() == Request::RT_QUIT)
{
delete me->m_current_request;
break;
}
@ -223,11 +225,7 @@ namespace Online
// (otherwise the assert in addResult will be triggered).
if (!me->getAbort())
me->addResult(me->m_current_request);
else if (me->m_current_request->manageMemory())
{
delete me->m_current_request;
me->m_current_request = NULL;
}
me->m_current_request = nullptr;
me->m_request_queue.lock();
} // while handle all requests
@ -239,12 +237,7 @@ namespace Online
// At this stage we have the lock for m_request_queue
while (!me->m_request_queue.getData().empty())
{
Online::Request *request = me->m_request_queue.getData().top();
me->m_request_queue.getData().pop();
// Manage memory can be ignored here, all requests
// need to be freed.
delete request;
}
me->m_request_queue.unlock();
pthread_exit(NULL);
@ -256,7 +249,7 @@ namespace Online
/** Inserts a request into the queue of results.
* \param request The pointer to the request to insert.
*/
void RequestManager::addResult(Online::Request *request)
void RequestManager::addResult(std::shared_ptr<Online::Request> request)
{
assert(request->hasBeenExecuted());
m_result_queue.lock();
@ -271,7 +264,7 @@ namespace Online
*/
void RequestManager::handleResultQueue()
{
Request * request = NULL;
std::shared_ptr<Request> request;
m_result_queue.lock();
if (!m_result_queue.getData().empty())
{
@ -279,16 +272,10 @@ namespace Online
m_result_queue.getData().pop();
}
m_result_queue.unlock();
if (request != NULL)
if (request)
{
request->callback();
if(request->manageMemory())
{
delete request;
request = NULL;
}
else
request->setDone();
request->setDone();
}
} // handleResultQueue

View File

@ -34,6 +34,7 @@
#endif
#include <curl/curl.h>
#include <memory>
#include <queue>
#include <pthread.h>
@ -94,7 +95,7 @@ namespace Online
float m_time_since_poll;
/** The current requested being worked on. */
Online::Request * m_current_request;
std::shared_ptr<Online::Request> m_current_request;
/** A conditional variable to wake up the main loop. */
pthread_cond_t m_cond_request;
@ -114,8 +115,8 @@ namespace Online
/** The list of pointers to all requests that still need to be
* handled. */
Synchronised< std::priority_queue <
Online::Request*,
std::vector<Online::Request*>,
std::shared_ptr<Online::Request>,
std::vector<std::shared_ptr<Online::Request> >,
Online::Request::Compare
>
> m_request_queue;
@ -123,9 +124,9 @@ namespace Online
/** The list of pointers to all requests that are already executed
* by the networking thread, but still need to be processed by the
* main thread. */
Synchronised< std::queue<Online::Request*> > m_result_queue;
Synchronised< std::queue<std::shared_ptr<Online::Request> > > m_result_queue;
void addResult(Online::Request *request);
void addResult(std::shared_ptr<Online::Request> request);
void handleResultQueue();
static void *mainLoop(void *obj);
@ -154,7 +155,7 @@ namespace Online
static void deallocate();
static bool isRunning();
void addRequest(Online::Request *request);
void addRequest(std::shared_ptr<Online::Request> request);
void startNetworkThread();
void stopNetworkThread();

View File

@ -57,7 +57,6 @@ AddonsLoading::AddonsLoading(const std::string &id)
{
m_icon_shown = false;
m_download_request = NULL;
loadFromFile("addons_loading.stkgui");
@ -304,7 +303,6 @@ void AddonsLoading::onUpdate(float delta)
{
// Avoid displaying '-100%' in case of an error.
m_progress->setVisible(false);
m_download_request->setManageMemory(true);
dismiss();
new MessageDialog( _("Sorry, downloading the add-on failed"));
return;
@ -346,8 +344,8 @@ void AddonsLoading::startDownload()
#ifndef SERVER_ONLY
std::string save = "tmp/"
+ StringUtils::getBasename(m_addon.getZipFileName());
m_download_request = new Online::HTTPRequest(save, /*manage mem*/false,
/*priority*/5);
m_download_request = std::make_shared<Online::HTTPRequest>(
save, /*manage mem*/false, /*priority*/5);
m_download_request->setURL(m_addon.getZipFileName());
m_download_request->queue();
#endif
@ -361,17 +359,10 @@ void AddonsLoading::stopDownload()
{
// Cancel a download only if we are installing/upgrading one
// (and not uninstalling an installed one):
if(m_download_request)
if (m_download_request)
{
// In case of a cancel we can't free the memory, since the
// request manager thread is potentially working on this request. So
// in order to avoid a memory leak, we let the request manager
// free the data. This is thread safe since freeing the data is done
// when the request manager handles the result queue - and this is
// done by the main thread (i.e. this thread).
m_download_request->setManageMemory(true);
m_download_request->cancel();
m_download_request = NULL;
m_download_request = nullptr;
};
} // startDownload
@ -382,8 +373,7 @@ void AddonsLoading::stopDownload()
void AddonsLoading::doInstall()
{
#ifndef SERVER_ONLY
delete m_download_request;
m_download_request = NULL;
m_download_request = nullptr;
assert(!m_addon.isInstalled() || m_addon.needsUpdate());
bool error = !addons_manager->install(m_addon);
@ -431,8 +421,7 @@ void AddonsLoading::doInstall()
void AddonsLoading::doUninstall()
{
#ifndef SERVER_ONLY
delete m_download_request;
m_download_request = NULL;
m_download_request = nullptr;
bool error = !addons_manager->uninstall(m_addon);
if(error)
{

View File

@ -54,7 +54,7 @@ private:
/** A pointer to the download request, which gives access
* to the progress of a download. */
Online::HTTPRequest *m_download_request;
std::shared_ptr<Online::HTTPRequest> m_download_request;
public:
AddonsLoading(const std::string &addon_name);

View File

@ -110,7 +110,7 @@ AddonsPack::AddonsPack(const std::string& url) : ModalDialog(0.8f, 0.8f)
GUIEngine::RibbonWidget* actions_ribbon =
getWidget<GUIEngine::RibbonWidget>("actions");
actions_ribbon->setVisible(false);
m_download_request = new AddonsPackRequest(url);
m_download_request = std::make_shared<AddonsPackRequest>(url);
m_download_request->queue();
} // AddonsPack
@ -191,15 +191,8 @@ void AddonsPack::stopDownload()
// (and not uninstalling an installed one):
if (m_download_request)
{
// In case of a cancel we can't free the memory, since the
// request manager thread is potentially working on this request. So
// in order to avoid a memory leak, we let the request manager
// free the data. This is thread safe since freeing the data is done
// when the request manager handles the result queue - and this is
// done by the main thread (i.e. this thread).
m_download_request->setManageMemory(true);
m_download_request->cancel();
m_download_request = NULL;
m_download_request = nullptr;
}
} // startDownload
@ -220,13 +213,12 @@ void AddonsPack::doInstall()
if (!msg.empty())
{
delete m_download_request;
dismiss();
new MessageDialog(msg);
}
else
{
AddonsPackRequest* request = m_download_request;
std::shared_ptr<AddonsPackRequest> request = m_download_request;
dismiss();
std::set<std::string> result;
std::string tmp_extract = file_manager->getAddonsFile("tmp_extract");
@ -300,7 +292,6 @@ void AddonsPack::doInstall()
as->loadList();
if (auto cl = LobbyProtocol::get<ClientLobby>())
cl->updateAssetsToServer();
delete request;
}
} // doInstall

View File

@ -37,7 +37,7 @@ private:
/** A pointer to the download request, which gives access
* to the progress of a download. */
AddonsPackRequest* m_download_request;
std::shared_ptr<AddonsPackRequest> m_download_request;
AddonsPack(const std::string& url);
public:
virtual GUIEngine::EventPropagation processEvent(const std::string& event_source) OVERRIDE;

View File

@ -106,11 +106,11 @@ void ChangePasswordDialog::changePassword(const stringw &current_password,
} // callback
public:
ChangePasswordRequest() : XMLRequest(true) {}
ChangePasswordRequest() : XMLRequest() {}
}; // ChangePasswordRequest
// ------------------------------------------------------------------------
ChangePasswordRequest * request = new ChangePasswordRequest();
auto request = std::make_shared<ChangePasswordRequest>();
PlayerManager::setUserDetails(request, "change-password");
request->addParameter("current", current_password);

View File

@ -81,8 +81,6 @@ public:
DownloadAssets::DownloadAssets()
: ModalDialog(0.8f, 0.8f)
{
m_download_request = NULL;
loadFromFile("addons_loading.stkgui");
m_install_button = getWidget<IconButtonWidget> ("install" );
m_progress = getWidget<ProgressBarWidget>("progress");
@ -178,7 +176,6 @@ void DownloadAssets::onUpdate(float delta)
{
// Avoid displaying '-100%' in case of an error.
m_progress->setVisible(false);
m_download_request->setManageMemory(true);
dismiss();
new MessageDialog(_("Sorry, downloading the add-on failed"));
return;
@ -199,7 +196,7 @@ void DownloadAssets::onUpdate(float delta)
**/
void DownloadAssets::startDownload()
{
m_download_request = new DownloadAssetsRequest();
m_download_request = std::make_shared<DownloadAssetsRequest>();
m_download_request->queue();
} // startDownload
@ -213,15 +210,8 @@ void DownloadAssets::stopDownload()
// (and not uninstalling an installed one):
if (m_download_request)
{
// In case of a cancel we can't free the memory, since the
// request manager thread is potentially working on this request. So
// in order to avoid a memory leak, we let the request manager
// free the data. This is thread safe since freeing the data is done
// when the request manager handles the result queue - and this is
// done by the main thread (i.e. this thread).
m_download_request->setManageMemory(true);
m_download_request->cancel();
m_download_request = NULL;
m_download_request = nullptr;
}
} // startDownload
@ -239,8 +229,7 @@ void DownloadAssets::doInstall()
// in the first run
msg = _("Failed to download assets, check your storage space or internet connection and try again later.");
}
delete m_download_request;
m_download_request = NULL;
m_download_request = nullptr;
if (!msg.empty())
{
getWidget<BubbleWidget>("description")->setText(msg);

View File

@ -41,7 +41,7 @@ private:
/** A pointer to the download request, which gives access
* to the progress of a download. */
DownloadAssetsRequest* m_download_request;
std::shared_ptr<DownloadAssetsRequest> m_download_request;
public:
DownloadAssets();

View File

@ -229,7 +229,7 @@ GUIEngine::EventPropagation
}
else if (selection == m_friend_widget->m_properties[PROP_ID])
{
XMLRequest *request = new XMLRequest();
auto request = std::make_shared<XMLRequest>();
PlayerManager::setUserDetails(request, "friend-request");
request->addParameter("friendid", m_online_id);
request->queue();

View File

@ -105,11 +105,11 @@ void PlayerRankingsDialog::updateTopTenList()
}
} // callback
public:
UpdateTopTenRequest() : XMLRequest(true) {}
UpdateTopTenRequest() : XMLRequest() {}
}; // UpdateTopTenRequest
// ------------------------------------------------------------------------
UpdateTopTenRequest *request = new UpdateTopTenRequest();
auto request = std::make_shared<UpdateTopTenRequest>();
PlayerManager::setUserDetails(request, "top-players");
request->addParameter("ntop", 10);
request->queue();

View File

@ -90,8 +90,8 @@ protected:
}; // UpdatePlayerRankingRequest
// --------------------------------------------------------------------
UpdatePlayerRankingRequest* request =
new UpdatePlayerRankingRequest(name, online_id, info, done);
auto request = std::make_shared<UpdatePlayerRankingRequest>(
name, online_id, info, done);
PlayerManager::setUserDetails(request, "get-ranking");
request->addParameter("id", online_id);
request->queue();

View File

@ -37,7 +37,6 @@ using namespace Online;
*/
RecoveryDialog::RecoveryDialog() : ModalDialog(0.8f,0.8f)
{
m_recovery_request = NULL;
m_self_destroy = false;
m_show_recovery_input = true;
m_show_recovery_info = false;
@ -49,7 +48,6 @@ RecoveryDialog::RecoveryDialog() : ModalDialog(0.8f,0.8f)
*/
RecoveryDialog::~RecoveryDialog()
{
delete m_recovery_request;
} //~RecoverDialog
// -----------------------------------------------------------------------------
@ -127,7 +125,7 @@ void RecoveryDialog::processInput()
m_info_widget->setDefaultColor();
m_options_widget->setActive(false);
m_recovery_request = new XMLRequest();
m_recovery_request = std::make_shared<XMLRequest>();
// This function also works when the current user is not logged in
PlayerManager::setUserDetails(m_recovery_request, "recover");
@ -185,7 +183,7 @@ void RecoveryDialog::onEnterPressedInternal()
*/
void RecoveryDialog::onUpdate(float dt)
{
if(m_recovery_request != NULL)
if (m_recovery_request)
{
if(m_recovery_request->isDone())
{
@ -201,8 +199,7 @@ void RecoveryDialog::onUpdate(float dt)
m_options_widget->setActive(true);
}
delete m_recovery_request;
m_recovery_request = NULL;
m_recovery_request = nullptr;
}
else
{

View File

@ -55,7 +55,7 @@ private:
bool m_show_recovery_input;
bool m_show_recovery_info;
Online::XMLRequest * m_recovery_request;
std::shared_ptr<Online::XMLRequest> m_recovery_request;
GUIEngine::TextBoxWidget * m_username_widget;
GUIEngine::TextBoxWidget * m_email_widget;

View File

@ -174,12 +174,12 @@ void UserInfoDialog::sendFriendRequest()
} // callback
public:
FriendRequest() : XMLRequest(true) {}
FriendRequest() : XMLRequest() {}
}; // FriendRequest
// ------------------------------------------------------------------------
FriendRequest *request = new FriendRequest();
auto request = std::make_shared<FriendRequest>();
PlayerManager::setUserDetails(request, "friend-request");
request->addParameter("friendid", m_online_profile->getID());
request->queue();
@ -230,11 +230,11 @@ void UserInfoDialog::acceptFriendRequest()
} // callback
public:
AcceptFriendRequest() : XMLRequest(true) {}
AcceptFriendRequest() : XMLRequest() {}
}; // AcceptFriendRequest
// ------------------------------------------------------------------------
AcceptFriendRequest *request = new AcceptFriendRequest();
auto request = std::make_shared<AcceptFriendRequest>();
PlayerManager::setUserDetails(request, "accept-friend-request");
request->addParameter("friendid", m_online_profile->getID());
request->queue();
@ -282,10 +282,10 @@ void UserInfoDialog::declineFriendRequest()
true), true);
} // callback
public:
DeclineFriendRequest() : XMLRequest(true) {}
DeclineFriendRequest() : XMLRequest() {}
}; // DeclineFriendRequest
// ----------------------------------------------------------------
DeclineFriendRequest *request = new DeclineFriendRequest();
auto request = std::make_shared<DeclineFriendRequest>();
PlayerManager::setUserDetails(request, "decline-friend-request");
request->addParameter("friendid", m_online_profile->getID());
request->queue();
@ -331,12 +331,12 @@ void UserInfoDialog::removeExistingFriend()
// --------------------------------------------------------------------
public:
RemoveFriendRequest(unsigned int id)
: XMLRequest(true), m_id(id) {}
: XMLRequest(), m_id(id) {}
}; // RemoveFriendRequest
// ------------------------------------------------------------------------
int friend_id = m_online_profile->getID();
RemoveFriendRequest * request = new RemoveFriendRequest(friend_id);
auto request = std::make_shared<RemoveFriendRequest>(friend_id);
PlayerManager::setUserDetails(request, "remove-friend");
request->addParameter("friendid", friend_id);
request->queue();
@ -378,11 +378,11 @@ void UserInfoDialog::removePendingFriend()
GUIEngine::DialogQueue::get()->pushDialog(dia, true);
} // callback
public:
CancelFriendRequest() : XMLRequest(true) {}
CancelFriendRequest() : XMLRequest() {}
}; // CancelFriendRequest
// ------------------------------------------------------------------------
CancelFriendRequest * request = new CancelFriendRequest();
auto request = std::make_shared<CancelFriendRequest>();
PlayerManager::setUserDetails(request, "cancel-friend-request");
request->addParameter("friendid", m_online_profile->getID());
request->queue();

View File

@ -39,8 +39,6 @@ using namespace Online;
VoteDialog::VoteDialog(const std::string & addon_id)
: ModalDialog(0.8f,0.6f), m_addon_id(addon_id)
{
m_fetch_vote_request = NULL;
m_perform_vote_request = NULL;
m_self_destroy = false;
loadFromFile("online/vote_dialog.stkgui");
@ -60,7 +58,7 @@ VoteDialog::VoteDialog(const std::string & addon_id)
m_options_widget->setFocusForPlayer(PLAYER_ID_GAME_MASTER);
m_fetch_vote_request = new XMLRequest();
m_fetch_vote_request = std::make_shared<XMLRequest>();
PlayerManager::setUserDetails(m_fetch_vote_request, "get-addon-vote");
m_fetch_vote_request->addParameter("addonid", addon_id.substr(6));
m_fetch_vote_request->queue();
@ -74,8 +72,6 @@ VoteDialog::VoteDialog(const std::string & addon_id)
*/
VoteDialog::~VoteDialog()
{
delete m_fetch_vote_request;
delete m_perform_vote_request;
} // ~VoteDialog
// -----------------------------------------------------------------------------
@ -119,7 +115,7 @@ void VoteDialog::sendVote()
}; // SetAddonVoteRequest
// ------------------------------------------------------------------------
m_perform_vote_request = new SetAddonVoteRequest();
m_perform_vote_request = std::make_shared<SetAddonVoteRequest>();
PlayerManager::setUserDetails(m_perform_vote_request, "set-addon-vote");
m_perform_vote_request->addParameter("addonid", m_addon_id.substr(6));
m_perform_vote_request->addParameter("rating", m_rating_widget->getRating());
@ -209,8 +205,7 @@ void VoteDialog::updateFetchVote()
m_cancel_widget->setActive(true);
} // !isSuccess
delete m_fetch_vote_request;
m_fetch_vote_request = NULL;
m_fetch_vote_request = nullptr;
} // updateFetchVote
@ -222,7 +217,7 @@ void VoteDialog::onUpdate(float dt)
{
updateFetchVote();
if(m_perform_vote_request != NULL)
if(m_perform_vote_request)
{
if(m_perform_vote_request->isDone())
{
@ -241,8 +236,7 @@ void VoteDialog::onUpdate(float dt)
m_cancel_widget->setActive(true);
m_rating_widget->setActive(true);
} // !isSuccess
delete m_perform_vote_request;
m_perform_vote_request = NULL;
m_perform_vote_request = nullptr;
} // isDone
else
{

View File

@ -45,10 +45,10 @@ private:
/** The request to fetch the current vote, which is submitted
* immediately when this dialog is opened. */
Online::XMLRequest * m_fetch_vote_request;
std::shared_ptr<Online::XMLRequest> m_fetch_vote_request;
/** The request to perform a vote. */
Online::XMLRequest* m_perform_vote_request;
std::shared_ptr<Online::XMLRequest> m_perform_vote_request;
/** Pointer to the info widget of this dialog. */
GUIEngine::LabelWidget * m_info_widget;

View File

@ -37,7 +37,6 @@ using namespace Online;
OnlineUserSearch::OnlineUserSearch() : Screen("online/user_search.stkgui")
{
m_search_request = NULL;
m_search_string = "";
m_last_search_string = "";
} // OnlineUserSearch
@ -86,45 +85,14 @@ void OnlineUserSearch::init()
*/
void OnlineUserSearch::tearDown()
{
// The search request can be in one of three states:
// 1. It does not exist, nothing more to do.
// 2. It has been executed by the request manager, had its callback done
// and waits for this widget to collect the results. In this case, the
// requests state is 'isDone', and the memory of this object need to be
// freed here.
// 3. It is being executed by the request manager thread. In this case the
// request can not be freed (since the request manager might still
// write to it). In this case we set the flag that the request manager
// should manage the memory for the request, i.e. the request will be
// deleted once it is in the request manager's ready queue.
// Note that there is no race condition here: setting a request to be
// 'done', and checking if its memory need to be freed is done by the
// main thread (i.e. the same thread that executes this function ). So it
// is not possible that the thread stage changes to be 'isDone' while
// this function executes, or that the request is checked if it should
// be freed.
// Cancel the work in progress request when leaving the screen
if (m_search_request)
{
// Check if the request is ready (but its result have not been
// received here ... otherwise it would have been deleted).
if (m_search_request->isDone())
if (!m_search_request->isDone())
{
delete m_search_request;
}
else
{
// This request is currently being handled by the request manager.
// We can set the memory management flag, since the separate
// request manager thread does not read or write this flag.
// The actual deletion of the request is done by the main
// thread, so there is no risk that the request is deleted
// between the next two calls!!
m_search_request->setManageMemory(true);
// Set cancel flag to speed up cancellation of this request
m_search_request->cancel();
}
m_search_request = nullptr;
} // if m_search_request
} // tearDown
@ -201,7 +169,7 @@ void OnlineUserSearch::search()
{
if (m_search_string != "" && m_last_search_string != m_search_string)
{
m_search_request = new XMLRequest();
m_search_request = std::make_shared<XMLRequest>();
PlayerManager::setUserDetails(m_search_request, "user-search");
m_search_request->addParameter("search-string", m_search_string);
m_search_request->queue();
@ -248,7 +216,7 @@ void OnlineUserSearch::eventCallback(GUIEngine::Widget* widget,
*/
void OnlineUserSearch::onUpdate(float dt)
{
if(m_search_request != NULL)
if (m_search_request)
{
if(m_search_request->isDone())
{
@ -263,8 +231,7 @@ void OnlineUserSearch::onUpdate(float dt)
new MessageDialog(m_search_request->getInfo());
}
delete m_search_request;
m_search_request = NULL;
m_search_request = nullptr;
m_back_widget->setActive(true);
m_search_box_widget->setActive(true);
m_search_button_widget->setActive(true);

View File

@ -58,7 +58,7 @@ private:
Online::OnlineProfile::IDList m_users;
/** The online request to search for users. */
Online::XMLRequest *m_search_request;
std::shared_ptr<Online::XMLRequest> m_search_request;
void parseResult(const XMLNode * input);
void showList();

View File

@ -110,7 +110,7 @@ void RegisterScreen::init()
m_password_widget->setPasswordBox(true, L'*');
getWidget<TextBoxWidget>("password_confirm")->setPasswordBox(true, L'*');
m_signup_request = NULL;
m_signup_request = nullptr;
m_info_message_shown = false;
onDialogClose();
@ -364,7 +364,7 @@ void RegisterScreen::acceptTerms()
core::stringw password_confirm= getWidget<TextBoxWidget>("password_confirm")->getText().trim();
core::stringw email = getWidget<TextBoxWidget>("email")->getText().trim();
m_signup_request = new XMLRequest();
m_signup_request = std::make_shared<XMLRequest>();
m_signup_request->setApiURL(API::USER_PATH, "register");
m_signup_request->addParameter("username", username );
m_signup_request->addParameter("password", password );
@ -403,8 +403,7 @@ void RegisterScreen::onUpdate(float dt)
m_info_widget->setErrorColor();
m_info_widget->setText(m_signup_request->getInfo(), false);
}
delete m_signup_request;
m_signup_request = NULL;
m_signup_request = nullptr;
m_options_widget->setActive(true);
}
}

View File

@ -53,7 +53,7 @@ private:
GUIEngine::TextBoxWidget *m_password_widget;
/** The XML request to the server. */
Online::XMLRequest *m_signup_request;
std::shared_ptr<Online::XMLRequest> m_signup_request;
/** Pointer to an existing player if the screen is doing a rename,
* NULL otherwise. */