summaryrefslogtreecommitdiff
path: root/src/gui/windows
diff options
context:
space:
mode:
Diffstat (limited to 'src/gui/windows')
-rw-r--r--src/gui/windows/bankwindow.cpp102
-rw-r--r--src/gui/windows/bankwindow.h64
-rw-r--r--src/gui/windows/buydialog.cpp794
-rw-r--r--src/gui/windows/buydialog.h207
-rw-r--r--src/gui/windows/buyingstoreselldialog.cpp70
-rw-r--r--src/gui/windows/buyingstoreselldialog.h55
-rw-r--r--src/gui/windows/buyselldialog.cpp167
-rw-r--r--src/gui/windows/buyselldialog.h86
-rw-r--r--src/gui/windows/changeemaildialog.cpp186
-rw-r--r--src/gui/windows/changeemaildialog.h81
-rw-r--r--src/gui/windows/changepassworddialog.cpp177
-rw-r--r--src/gui/windows/changepassworddialog.h76
-rw-r--r--src/gui/windows/charcreatedialog.cpp885
-rw-r--r--src/gui/windows/charcreatedialog.h171
-rw-r--r--src/gui/windows/chardeleteconfirm.h65
-rw-r--r--src/gui/windows/charselectdialog.cpp644
-rw-r--r--src/gui/windows/charselectdialog.h136
-rw-r--r--src/gui/windows/chatwindow.cpp2181
-rw-r--r--src/gui/windows/chatwindow.h406
-rw-r--r--src/gui/windows/confirmdialog.cpp120
-rw-r--r--src/gui/windows/confirmdialog.h71
-rw-r--r--src/gui/windows/connectiondialog.cpp90
-rw-r--r--src/gui/windows/connectiondialog.h69
-rw-r--r--src/gui/windows/cutinwindow.cpp153
-rw-r--r--src/gui/windows/cutinwindow.h61
-rw-r--r--src/gui/windows/debugwindow.cpp173
-rw-r--r--src/gui/windows/debugwindow.h78
-rw-r--r--src/gui/windows/didyouknowwindow.cpp188
-rw-r--r--src/gui/windows/didyouknowwindow.h76
-rw-r--r--src/gui/windows/editdialog.cpp80
-rw-r--r--src/gui/windows/editdialog.h72
-rw-r--r--src/gui/windows/editserverdialog.cpp297
-rw-r--r--src/gui/windows/editserverdialog.h86
-rw-r--r--src/gui/windows/eggselectiondialog.cpp67
-rw-r--r--src/gui/windows/eggselectiondialog.h45
-rw-r--r--src/gui/windows/emotewindow.cpp278
-rw-r--r--src/gui/windows/emotewindow.h89
-rw-r--r--src/gui/windows/equipmentwindow.cpp848
-rw-r--r--src/gui/windows/equipmentwindow.h167
-rw-r--r--src/gui/windows/helpwindow.cpp220
-rw-r--r--src/gui/windows/helpwindow.h92
-rw-r--r--src/gui/windows/insertcarddialog.cpp79
-rw-r--r--src/gui/windows/insertcarddialog.h49
-rw-r--r--src/gui/windows/inventorywindow.cpp1083
-rw-r--r--src/gui/windows/inventorywindow.h210
-rw-r--r--src/gui/windows/itemamountwindow.cpp504
-rw-r--r--src/gui/windows/itemamountwindow.h123
-rw-r--r--src/gui/windows/killstats.cpp479
-rw-r--r--src/gui/windows/killstats.h116
-rw-r--r--src/gui/windows/logindialog.cpp402
-rw-r--r--src/gui/windows/logindialog.h113
-rw-r--r--src/gui/windows/maileditwindow.cpp278
-rw-r--r--src/gui/windows/maileditwindow.h92
-rw-r--r--src/gui/windows/mailviewwindow.cpp269
-rw-r--r--src/gui/windows/mailviewwindow.h80
-rw-r--r--src/gui/windows/mailwindow.cpp393
-rw-r--r--src/gui/windows/mailwindow.h108
-rw-r--r--src/gui/windows/minimap.cpp540
-rw-r--r--src/gui/windows/minimap.h95
-rw-r--r--src/gui/windows/ministatuswindow.cpp594
-rw-r--r--src/gui/windows/ministatuswindow.h151
-rw-r--r--src/gui/windows/npcdialog.cpp1395
-rw-r--r--src/gui/windows/npcdialog.h324
-rw-r--r--src/gui/windows/npcselldialog.cpp154
-rw-r--r--src/gui/windows/npcselldialog.h59
-rw-r--r--src/gui/windows/okdialog.cpp94
-rw-r--r--src/gui/windows/okdialog.h72
-rw-r--r--src/gui/windows/outfitwindow.cpp749
-rw-r--r--src/gui/windows/outfitwindow.h133
-rw-r--r--src/gui/windows/questswindow.cpp483
-rw-r--r--src/gui/windows/questswindow.h105
-rw-r--r--src/gui/windows/quitdialog.cpp260
-rw-r--r--src/gui/windows/quitdialog.h84
-rw-r--r--src/gui/windows/registerdialog.cpp317
-rw-r--r--src/gui/windows/registerdialog.h95
-rw-r--r--src/gui/windows/serverdialog.cpp902
-rw-r--r--src/gui/windows/serverdialog.h150
-rw-r--r--src/gui/windows/serverinfowindow.cpp184
-rw-r--r--src/gui/windows/serverinfowindow.h68
-rw-r--r--src/gui/windows/setupwindow.cpp335
-rw-r--r--src/gui/windows/setupwindow.h96
-rw-r--r--src/gui/windows/shopselldialog.cpp60
-rw-r--r--src/gui/windows/shopselldialog.h54
-rw-r--r--src/gui/windows/shopwindow.cpp1175
-rw-r--r--src/gui/windows/shopwindow.h207
-rw-r--r--src/gui/windows/shortcutwindow.cpp269
-rw-r--r--src/gui/windows/shortcutwindow.h100
-rw-r--r--src/gui/windows/skilldialog.cpp1432
-rw-r--r--src/gui/windows/skilldialog.h237
-rw-r--r--src/gui/windows/socialwindow.cpp659
-rw-r--r--src/gui/windows/socialwindow.h171
-rw-r--r--src/gui/windows/statuswindow.cpp652
-rw-r--r--src/gui/windows/statuswindow.h119
-rw-r--r--src/gui/windows/textcommandeditor.cpp344
-rw-r--r--src/gui/windows/textcommandeditor.h116
-rw-r--r--src/gui/windows/textdialog.cpp135
-rw-r--r--src/gui/windows/textdialog.h85
-rw-r--r--src/gui/windows/textselectdialog.cpp192
-rw-r--r--src/gui/windows/textselectdialog.h104
-rw-r--r--src/gui/windows/tradewindow.cpp553
-rw-r--r--src/gui/windows/tradewindow.h214
-rw-r--r--src/gui/windows/updaterwindow.cpp1217
-rw-r--r--src/gui/windows/updaterwindow.h252
-rw-r--r--src/gui/windows/whoisonline.cpp909
-rw-r--r--src/gui/windows/whoisonline.h182
-rw-r--r--src/gui/windows/worldselectdialog.cpp134
-rw-r--r--src/gui/windows/worldselectdialog.h77
107 files changed, 0 insertions, 31439 deletions
diff --git a/src/gui/windows/bankwindow.cpp b/src/gui/windows/bankwindow.cpp
deleted file mode 100644
index 242d30aa1..000000000
--- a/src/gui/windows/bankwindow.cpp
+++ /dev/null
@@ -1,102 +0,0 @@
-/*
- * The ManaPlus Client
- * Copyright (C) 2011-2017 The ManaPlus Developers
- *
- * This file is part of The ManaPlus Client.
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-#include "gui/windows/bankwindow.h"
-
-#include "net/bankhandler.h"
-
-#include "gui/windows/setupwindow.h"
-
-#include "gui/widgets/button.h"
-#include "gui/widgets/containerplacer.h"
-#include "gui/widgets/inttextfield.h"
-#include "gui/widgets/label.h"
-
-#include "utils/gettext.h"
-#include "utils/stringutils.h"
-
-#include "resources/db/unitsdb.h"
-
-#include "debug.h"
-
-BankWindow *bankWindow = nullptr;
-
-BankWindow::BankWindow() :
- // TRANSLATORS: bank window name
- Window(_("Bank"), Modal_false, nullptr, "bank.xml"),
- ActionListener(),
- BankListener(),
- mBankMoneyLabel(new Label(this, strprintf(
- // TRANSLATORS: bank window money label
- _("Money in bank: %s"), " "))),
- mInputMoneyTextField(new IntTextField(this, 0, 0, 2147483647)),
- // TRANSLATORS: bank window button
- mWithdrawButton(new Button(this, _("Withdraw"), "withdraw", this)),
- // TRANSLATORS: bank window button
- mDepositButton(new Button(this, _("Deposit"), "deposit", this))
-{
- setWindowName("Bank");
- setCloseButton(true);
-
- if (setupWindow != nullptr)
- setupWindow->registerWindowForReset(this);
-
- mBankMoneyLabel->adjustSize();
- ContainerPlacer placer = getPlacer(0, 0);
- placer(0, 0, mBankMoneyLabel, 7);
- placer(0, 1, mInputMoneyTextField, 10);
- placer(0, 2, mDepositButton, 5);
- placer(5, 2, mWithdrawButton, 5);
-
- setContentSize(300, 100);
- setDefaultSize(300, 100, ImagePosition::CENTER, 0, 0);
-
- center();
- setDefaultSize();
- loadWindowState();
- reflowLayout(300);
- enableVisibleSound(true);
-}
-
-BankWindow::~BankWindow()
-{
-}
-
-void BankWindow::widgetShown(const Event &event)
-{
- if (event.getSource() == this)
- bankHandler->check();
-}
-
-void BankWindow::bankMoneyChanged(const int money)
-{
- // TRANSLATORS: bank window money label
- mBankMoneyLabel->setCaption(strprintf(_("Money in bank: %s"),
- UnitsDb::formatCurrency(money).c_str()));
-}
-
-void BankWindow::action(const ActionEvent &event)
-{
- const std::string &eventId = event.getId();
- if (eventId == "deposit")
- bankHandler->deposit(mInputMoneyTextField->getValue());
- else if (eventId == "withdraw")
- bankHandler->withdraw(mInputMoneyTextField->getValue());
-}
diff --git a/src/gui/windows/bankwindow.h b/src/gui/windows/bankwindow.h
deleted file mode 100644
index 046b11ec4..000000000
--- a/src/gui/windows/bankwindow.h
+++ /dev/null
@@ -1,64 +0,0 @@
-/*
- * The ManaPlus Client
- * Copyright (C) 2011-2017 The ManaPlus Developers
- *
- * This file is part of The ManaPlus Client.
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-#ifndef GUI_WINDOWS_BANKWINDOW_H
-#define GUI_WINDOWS_BANKWINDOW_H
-
-#include "gui/widgets/window.h"
-
-#include "listeners/actionlistener.h"
-#include "listeners/banklistener.h"
-
-class Button;
-class IntTextField;
-class Label;
-
-/**
- * A dialog to choose between buying or selling at a shop.
- *
- * \ingroup Interface
- */
-class BankWindow final : public Window,
- public ActionListener,
- public BankListener
-{
- public:
- BankWindow();
-
- A_DELETE_COPY(BankWindow)
-
- ~BankWindow();
-
- void action(const ActionEvent &event) override final;
-
- void widgetShown(const Event &event) override final;
-
- void bankMoneyChanged(const int money) override final;
-
- private:
- Label *mBankMoneyLabel;
- IntTextField *mInputMoneyTextField;
- Button *mWithdrawButton;
- Button *mDepositButton;
-};
-
-extern BankWindow *bankWindow;
-
-#endif // GUI_WINDOWS_BANKWINDOW_H
diff --git a/src/gui/windows/buydialog.cpp b/src/gui/windows/buydialog.cpp
deleted file mode 100644
index db1dc6e50..000000000
--- a/src/gui/windows/buydialog.cpp
+++ /dev/null
@@ -1,794 +0,0 @@
-/*
- * The ManaPlus Client
- * Copyright (C) 2004-2009 The Mana World Development Team
- * Copyright (C) 2009-2010 The Mana Developers
- * Copyright (C) 2011-2017 The ManaPlus Developers
- *
- * This file is part of The ManaPlus Client.
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-#include "gui/windows/buydialog.h"
-
-#include "actormanager.h"
-#include "configuration.h"
-
-#include "being/being.h"
-
-#include "enums/gui/layouttype.h"
-
-#include "gui/windows/setupwindow.h"
-#ifdef TMWA_SUPPORT
-#include "gui/windows/tradewindow.h"
-#endif // TMWA_SUPPORT
-
-#include "gui/models/shopitems.h"
-#include "gui/models/sortlistmodelbuy.h"
-
-#include "gui/widgets/button.h"
-#include "gui/widgets/containerplacer.h"
-#include "gui/widgets/createwidget.h"
-#include "gui/widgets/dropdown.h"
-#include "gui/widgets/inttextfield.h"
-#include "gui/widgets/label.h"
-#include "gui/widgets/layout.h"
-#include "gui/widgets/scrollarea.h"
-#include "gui/widgets/shoplistbox.h"
-#include "gui/widgets/slider.h"
-
-#include "net/adminhandler.h"
-#include "net/buysellhandler.h"
-#include "net/cashshophandler.h"
-#include "net/markethandler.h"
-#include "net/net.h"
-#include "net/vendinghandler.h"
-#include "net/npchandler.h"
-
-#include "resources/iteminfo.h"
-
-#include "resources/db/unitsdb.h"
-
-#include "utils/delete2.h"
-#include "utils/foreach.h"
-
-#include <algorithm>
-
-#include "debug.h"
-
-namespace
-{
- class SortItemPriceFunctor final
- {
- public:
- A_DEFAULT_COPY(SortItemPriceFunctor)
-
- bool operator() (const ShopItem *const item1,
- const ShopItem *const item2) const
- {
- if ((item1 == nullptr) || (item2 == nullptr))
- return false;
-
- const int price1 = item1->getPrice();
- const int price2 = item2->getPrice();
- if (price1 == price2)
- return item1->getDisplayName() < item2->getDisplayName();
- return price1 < price2;
- }
- } itemPriceBuySorter;
-
- class SortItemNameFunctor final
- {
- public:
- A_DEFAULT_COPY(SortItemNameFunctor)
-
- bool operator() (const ShopItem *const item1,
- const ShopItem *const item2) const
- {
- if ((item1 == nullptr) || (item2 == nullptr))
- return false;
-
- const std::string &name1 = item1->getDisplayName();
- const std::string &name2 = item2->getDisplayName();
- if (name1 == name2)
- return item1->getPrice() < item2->getPrice();
- return name1 < name2;
- }
- } itemNameBuySorter;
-
- class SortItemIdFunctor final
- {
- public:
- A_DEFAULT_COPY(SortItemIdFunctor)
-
- bool operator() (const ShopItem *const item1,
- const ShopItem *const item2) const
- {
- if ((item1 == nullptr) || (item2 == nullptr))
- return false;
-
- const int id1 = item1->getId();
- const int id2 = item2->getId();
- if (id1 == id2)
- return item1->getPrice() < item2->getPrice();
- return id1 < id2;
- }
- } itemIdBuySorter;
-
- class SortItemWeightFunctor final
- {
- public:
- A_DEFAULT_COPY(SortItemWeightFunctor)
-
- bool operator() (const ShopItem *const item1,
- const ShopItem *const item2) const
- {
- if ((item1 == nullptr) || (item2 == nullptr))
- return false;
-
- const int weight1 = item1->getInfo().getWeight();
- const int weight2 = item2->getInfo().getWeight();
- if (weight1 == weight2)
- return item1->getPrice() < item2->getPrice();
- return weight1 < weight2;
- }
- } itemWeightBuySorter;
-
- class SortItemAmountFunctor final
- {
- public:
- A_DEFAULT_COPY(SortItemAmountFunctor)
-
- bool operator() (const ShopItem *const item1,
- const ShopItem *const item2) const
- {
- if ((item1 == nullptr) || (item2 == nullptr))
- return false;
-
- const int amount1 = item1->getQuantity();
- const int amount2 = item2->getQuantity();
- if (amount1 == amount2)
- return item1->getPrice() < item2->getPrice();
- return amount1 < amount2;
- }
- } itemAmountBuySorter;
-
- class SortItemTypeFunctor final
- {
- public:
- A_DEFAULT_COPY(SortItemTypeFunctor)
-
- bool operator() (const ShopItem *const item1,
- const ShopItem *const item2) const
- {
- if ((item1 == nullptr) || (item2 == nullptr))
- return false;
-
- const ItemDbTypeT type1 = item1->getInfo().getType();
- const ItemDbTypeT type2 = item2->getInfo().getType();
- if (type1 == type2)
- return item1->getPrice() < item2->getPrice();
- return type1 < type2;
- }
- } itemTypeBuySorter;
-} // namespace
-
-BuyDialog::DialogList BuyDialog::instances;
-
-BuyDialog::BuyDialog() :
- // TRANSLATORS: buy dialog name
- Window(_("Create items"), Modal_false, nullptr, "buy.xml"),
- ActionListener(),
- SelectionListener(),
- mSortModel(nullptr),
- mSortDropDown(nullptr),
- mFilterTextField(new TextField(this, "", LoseFocusOnTab_true,
- this, "namefilter", true)),
- mFilterLabel(nullptr),
- mNick(),
- mCurrency(),
- mNpcId(fromInt(Items, BeingId)),
- mMoney(0),
- mAmountItems(0),
- mMaxItems(0),
- mAdvanced(false)
-{
- init();
-}
-
-BuyDialog::BuyDialog(const BeingId npcId,
- const std::string &currency) :
- // TRANSLATORS: buy dialog name
- Window(_("Buy"), Modal_false, nullptr, "buy.xml"),
- ActionListener(),
- SelectionListener(),
- mSortModel(nullptr),
- mSortDropDown(nullptr),
- mFilterTextField(new TextField(this, "", LoseFocusOnTab_true,
- this, "namefilter", true)),
- mFilterLabel(nullptr),
- mNick(),
- mCurrency(currency),
- mNpcId(npcId),
- mMoney(0),
- mAmountItems(0),
- mMaxItems(0),
- mAdvanced(Net::getNetworkType() != ServerType::TMWATHENA)
-{
- init();
-}
-
-#ifdef TMWA_SUPPORT
-BuyDialog::BuyDialog(const std::string &nick,
- const std::string &currency) :
- // TRANSLATORS: buy dialog name
- Window(_("Buy"), Modal_false, nullptr, "buy.xml"),
- ActionListener(),
- SelectionListener(),
- mSortModel(new SortListModelBuy),
- mSortDropDown(new DropDown(this, mSortModel, false,
- Modal_false, this, "sort")),
- mFilterTextField(new TextField(this, "", LoseFocusOnTab_true,
- this, "namefilter", true)),
- mFilterLabel(nullptr),
- mNick(nick),
- mCurrency(currency),
- mNpcId(fromInt(Nick, BeingId)),
- mMoney(0),
- mAmountItems(0),
- mMaxItems(0),
- mAdvanced(false)
-{
- init();
-}
-#endif // TMWA_SUPPORT
-
-BuyDialog::BuyDialog(const Being *const being,
- const std::string &currency) :
- // TRANSLATORS: buy dialog name
- Window(_("Buy"), Modal_false, nullptr, "buy.xml"),
- ActionListener(),
- SelectionListener(),
- mSortModel(new SortListModelBuy),
- mSortDropDown(new DropDown(this, mSortModel, false,
- Modal_false, this, "sort")),
- mFilterTextField(new TextField(this, "", LoseFocusOnTab_true,
- this, "namefilter", true)),
- mFilterLabel(nullptr),
- mNick(being != nullptr ? being->getName() : std::string()),
- mCurrency(currency),
- mNpcId(fromInt(Vending, BeingId)),
- mMoney(0),
- mAmountItems(0),
- mMaxItems(0),
- mAdvanced(true)
-{
- init();
-}
-
-void BuyDialog::init()
-{
- setWindowName("Buy");
- setResizable(true);
- setCloseButton(true);
- setStickyButtonLock(true);
- setMinWidth(260);
- setMinHeight(220);
- setDefaultSize(260, 230, ImagePosition::CENTER);
-
-#ifdef TMWA_SUPPORT
- // reset advance flag for personal shops
- if (mAdvanced &&
- mNpcId == fromInt(Nick, BeingId))
- {
- mAdvanced = false;
- }
-#endif // TMWA_SUPPORT
-
- if (setupWindow != nullptr)
- setupWindow->registerWindowForReset(this);
-
- mShopItems = new ShopItems(false,
- mCurrency);
-
- CREATEWIDGETV(mShopItemList, ShopListBox, this,
- mShopItems, mShopItems, ShopListBoxType::Unknown);
- mScrollArea = new ScrollArea(this, mShopItemList,
- fromBool(getOptionBool("showbackground"), Opaque),
- "buy_background.xml");
- mScrollArea->setHorizontalScrollPolicy(ScrollArea::SHOW_NEVER);
-
- mSlider = new Slider(this, 1.0, 1.0);
- mQuantityLabel = new Label(this, strprintf(
- "%d / %d", mAmountItems, mMaxItems));
- mQuantityLabel->setAlignment(Graphics::CENTER);
- mMoneyLabel = new Label(this, strprintf(
- // TRANSLATORS: buy dialog label
- _("Price: %s / Total: %s"), "", ""));
-
- mAmountField = new IntTextField(this, 1, 1, 123);
- mAmountField->setActionEventId("amount");
- mAmountField->addActionListener(this);
- mAmountField->setSendAlwaysEvents(true);
- mAmountField->setEnabled(false);
-
- // TRANSLATORS: buy dialog label
- mAmountLabel = new Label(this, _("Amount:"));
- mAmountLabel->adjustSize();
-
- // TRANSLATORS: This is a narrow symbol used to denote 'increasing'.
- // You may change this symbol if your language uses another.
- mIncreaseButton = new Button(this, _("+"), "inc", this);
- // TRANSLATORS: This is a narrow symbol used to denote 'decreasing'.
- // You may change this symbol if your language uses another.
- mDecreaseButton = new Button(this, _("-"), "dec", this);
- mBuyButton = new Button(this, mNpcId == fromInt(Items, BeingId)
- // TRANSLATORS: buy dialog button
- ? _("Create") : (mAdvanced ? _("Add") : _("Buy")), "buy", this);
- if (mAdvanced)
- {
- // TRANSLATORS: buy dialog button
- mConfirmButton = new Button(this, _("Buy"), "confirm", this);
- mConfirmButton->setEnabled(false);
- }
- else
- {
- mConfirmButton = nullptr;
- }
- // TRANSLATORS: buy dialog button
- mQuitButton = new Button(this, _("Quit"), "quit", this);
- // TRANSLATORS: buy dialog button
- mAddMaxButton = new Button(this, _("Max"), "max", this);
-
- mDecreaseButton->adjustSize();
- mDecreaseButton->setWidth(mIncreaseButton->getWidth());
-
- mIncreaseButton->setEnabled(false);
- mDecreaseButton->setEnabled(false);
- mBuyButton->setEnabled(false);
- mSlider->setEnabled(false);
-
- mSlider->setActionEventId("slider");
- mSlider->addActionListener(this);
-
- mShopItemList->setDistributeMousePressed(false);
- mShopItemList->setActionEventId("buy");
- mShopItemList->addActionListener(this);
- mShopItemList->addSelectionListener(this);
-
- mFilterTextField->setWidth(100);
-
- ContainerPlacer placer = getPlacer(0, 0);
- placer(0, 0, mScrollArea, 9, 5).setPadding(3);
- placer(0, 5, mDecreaseButton);
- placer(1, 5, mSlider, 4);
- placer(5, 5, mIncreaseButton);
- placer(6, 5, mQuantityLabel, 2);
- placer(8, 5, mAddMaxButton);
- placer(0, 6, mAmountLabel, 2);
- placer(2, 6, mAmountField, 2);
- placer(0, 7, mMoneyLabel, 8);
- if (mSortDropDown != nullptr)
- {
- placer(0, 8, mSortDropDown, 2);
- }
- else
- {
- // TRANSLATORS: buy dialog label
- mFilterLabel = new Label(this, _("Filter:"));
- mFilterLabel->adjustSize();
- placer(0, 8, mFilterLabel, 2);
- }
- placer(2, 8, mFilterTextField, 2);
- if (mAdvanced)
- {
- placer(6, 8, mBuyButton);
- placer(7, 8, mConfirmButton);
- }
- else
- {
- placer(7, 8, mBuyButton);
- }
- placer(8, 8, mQuitButton);
-
- Layout &layout = getLayout();
- layout.setRowHeight(0, LayoutType::SET);
-
- center();
- loadWindowState();
- enableVisibleSound(true);
-
- instances.push_back(this);
- setVisible(Visible_true);
-
- if (mSortDropDown != nullptr)
- mSortDropDown->setSelected(config.getIntValue("buySortOrder"));
-}
-
-BuyDialog::~BuyDialog()
-{
- delete2(mShopItems);
- delete2(mSortModel);
- instances.remove(this);
- if (buySellHandler != nullptr)
- buySellHandler->cleanDialogReference(this);
-}
-
-void BuyDialog::setMoney(const int amount)
-{
- mMoney = amount;
- mShopItemList->setPlayersMoney(amount);
-
- updateButtonsAndLabels();
-}
-
-void BuyDialog::reset()
-{
- mShopItems->clear();
- mShopItemList->adjustSize();
-
- // Reset previous selected items to prevent failing asserts
- mShopItemList->setSelected(-1);
- mSlider->setValue(0);
-
- setMoney(0);
-}
-
-ShopItem *BuyDialog::addItem(const int id,
- const ItemTypeT type,
- const ItemColor color,
- const int amount,
- const int price)
-{
- ShopItem *const item = mShopItems->addItem(id,
- type,
- color,
- amount,
- price);
- mShopItemList->adjustSize();
- return item;
-}
-
-void BuyDialog::sort()
-{
- if ((mSortDropDown != nullptr) && (mShopItems != nullptr))
- {
- STD_VECTOR<ShopItem*> &items = mShopItems->items();
- switch (mSortDropDown->getSelected())
- {
- case 1:
- std::sort(items.begin(), items.end(), itemPriceBuySorter);
- break;
- case 2:
- std::sort(items.begin(), items.end(), itemNameBuySorter);
- break;
- case 3:
- std::sort(items.begin(), items.end(), itemIdBuySorter);
- break;
- case 4:
- std::sort(items.begin(), items.end(), itemWeightBuySorter);
- break;
- case 5:
- std::sort(items.begin(), items.end(), itemAmountBuySorter);
- break;
- case 6:
- std::sort(items.begin(), items.end(), itemTypeBuySorter);
- break;
- case 0:
- default:
- break;
- }
- }
-}
-
-void BuyDialog::close()
-{
- switch (toInt(mNpcId, int))
- {
-#ifdef TMWA_SUPPORT
- case Nick:
-#endif // TMWA_SUPPORT
- case Items:
- break;
- case Market:
- marketHandler->close();
- break;
- case Cash:
- cashShopHandler->close();
- break;
- case Vending:
- vendingHandler->close();
- break;
- default:
- buySellHandler->close();
- break;
- }
- Window::close();
-}
-
-void BuyDialog::action(const ActionEvent &event)
-{
- const std::string &eventId = event.getId();
- if (eventId == "quit")
- {
- close();
- return;
- }
- else if (eventId == "sort")
- {
- sort();
- if (mSortDropDown != nullptr)
- config.setValue("buySortOrder", mSortDropDown->getSelected());
- return;
- }
- else if (eventId == "namefilter")
- {
- applyNameFilter(mFilterTextField->getText());
- }
-
- const int selectedItem = mShopItemList->getSelected();
-
- // The following actions require a valid selection
- if (selectedItem < 0 || selectedItem >= mShopItems->getNumberOfElements())
- return;
-
- if (eventId == "slider")
- {
- mAmountItems = CAST_S32(mSlider->getValue());
- mAmountField->setValue(mAmountItems);
- updateButtonsAndLabels();
- }
- else if (eventId == "inc" && mAmountItems < mMaxItems)
- {
- mAmountItems++;
- mSlider->setValue(mAmountItems);
- mAmountField->setValue(mAmountItems);
- updateButtonsAndLabels();
- }
- else if (eventId == "dec" && mAmountItems > 1)
- {
- mAmountItems--;
- mSlider->setValue(mAmountItems);
- mAmountField->setValue(mAmountItems);
- updateButtonsAndLabels();
- }
- else if (eventId == "max")
- {
- mAmountItems = mMaxItems;
- mSlider->setValue(mAmountItems);
- mAmountField->setValue(mAmountItems);
- updateButtonsAndLabels();
- }
- else if (eventId == "amount")
- {
- mAmountItems = mAmountField->getValue();
- mSlider->setValue(mAmountItems);
- updateButtonsAndLabels();
- }
- else if (eventId == "buy" && mAmountItems > 0 && mAmountItems <= mMaxItems)
- {
- ShopItem *const item = mShopItems->at(selectedItem);
- if (item == nullptr)
- return;
- if (mNpcId == fromInt(Items, BeingId))
- {
- adminHandler->createItems(item->getId(),
- item->getColor(),
- mAmountItems);
- }
-#ifdef TMWA_SUPPORT
- else if (mNpcId == fromInt(Nick, BeingId))
- {
- if (tradeWindow != nullptr)
- {
- buySellHandler->sendBuyRequest(mNick,
- item, mAmountItems);
- tradeWindow->addAutoMoney(mNick,
- item->getPrice() * mAmountItems);
- }
- }
-#endif // TMWA_SUPPORT
- else if (mNpcId == fromInt(Vending, BeingId))
- {
- item->increaseUsedQuantity(mAmountItems);
- item->update();
- if (mConfirmButton != nullptr)
- mConfirmButton->setEnabled(true);
- }
-#ifdef TMWA_SUPPORT
- else if (mNpcId != fromInt(Nick, BeingId))
-#else
- else
-#endif // TMWA_SUPPORT
- {
- if (mAdvanced)
- {
- item->increaseUsedQuantity(mAmountItems);
- item->update();
- if (mConfirmButton != nullptr)
- mConfirmButton->setEnabled(true);
- }
- else if (mNpcId == fromInt(Market, BeingId))
- {
- marketHandler->buyItem(item->getId(),
- item->getType(),
- item->getColor(),
- mAmountItems);
- item->increaseQuantity(-mAmountItems);
- item->update();
- }
- else if (mNpcId == fromInt(Cash, BeingId))
- {
- cashShopHandler->buyItem(item->getPrice(),
- item->getId(),
- item->getColor(),
- mAmountItems);
- }
- else
- {
- npcHandler->buyItem(mNpcId,
- item->getId(),
- item->getColor(),
- mAmountItems);
- }
-
- updateSlider(selectedItem);
- }
- }
- else if (eventId == "confirm")
- {
- STD_VECTOR<ShopItem*> &items = mShopItems->allItems();
-
- if (mNpcId == fromInt(Market, BeingId))
- {
- marketHandler->buyItems(items);
- }
- else if (mNpcId == fromInt(Vending, BeingId))
- {
- const Being *const being = actorManager->findBeingByName(
- mNick,
- ActorType::Player);
- if (being != nullptr)
- {
- vendingHandler->buyItems(being,
- items);
- }
- }
- else if (mNpcId == fromInt(Cash, BeingId))
- {
- cashShopHandler->buyItems(0, items);
- }
- else
- {
- npcHandler->buyItems(items);
- }
- close();
- }
-}
-
-void BuyDialog::updateSlider(const int selectedItem)
-{
- // Update money and adjust the max number of items
- // that can be bought
- mMaxItems -= mAmountItems;
- const ShopItem *const item = mShopItems->at(selectedItem);
- if (item != nullptr)
- setMoney(mMoney - mAmountItems * item->getPrice());
- else
- setMoney(mMoney);
-
- // Reset selection
- mAmountItems = 1;
- mSlider->setScale(1, mMaxItems);
- mSlider->setValue(1);
-}
-
-void BuyDialog::valueChanged(const SelectionEvent &event A_UNUSED)
-{
- // Reset amount of items and update labels
- mAmountItems = 1;
- mSlider->setValue(1);
-
- updateButtonsAndLabels();
- mSlider->setScale(1, mMaxItems);
- mAmountField->setRange(1, mMaxItems);
- mAmountField->setValue(1);
-}
-
-void BuyDialog::updateButtonsAndLabels()
-{
- const int selectedItem = mShopItemList->getSelected();
- int price = 0;
-
- if (selectedItem > -1)
- {
- const ShopItem *const item = mShopItems->at(selectedItem);
- if (item != nullptr)
- {
- const int itemPrice = item->getPrice();
-
- // Calculate how many the player can afford
- if (mNpcId == fromInt(Items, BeingId))
- mMaxItems = 100;
- else if (itemPrice != 0)
- mMaxItems = mMoney / itemPrice;
- else
- mMaxItems = 1;
-
- if (item->getQuantity() > 0 && mMaxItems > item->getQuantity())
- mMaxItems = item->getQuantity();
-
- if (mAmountItems > mMaxItems)
- mAmountItems = mMaxItems;
-
- price = mAmountItems * itemPrice;
- }
- }
- else
- {
- mMaxItems = 0;
- mAmountItems = 0;
- }
-
- mIncreaseButton->setEnabled(mAmountItems < mMaxItems);
- mDecreaseButton->setEnabled(mAmountItems > 1);
- mBuyButton->setEnabled(mAmountItems > 0);
- mSlider->setEnabled(mMaxItems > 1);
- mAmountField->setEnabled(mAmountItems > 0);
-
- mQuantityLabel->setCaption(strprintf("%d / %d", mAmountItems, mMaxItems));
- // TRANSLATORS: buy dialog label
- mMoneyLabel->setCaption(strprintf(_("Price: %s / Total: %s"),
- UnitsDb::formatCurrency(mCurrency, price).c_str(),
- UnitsDb::formatCurrency(mCurrency, mMoney - price).c_str()));
-}
-
-void BuyDialog::setVisible(Visible visible)
-{
- Window::setVisible(visible);
-
- if (visible == Visible_true && (mShopItemList != nullptr))
- mShopItemList->requestFocus();
- else
- scheduleDelete();
-}
-
-void BuyDialog::closeAll()
-{
- FOR_EACH (DialogList::const_iterator, it, instances)
- {
- if (*it != nullptr)
- (*it)->close();
- }
-}
-
-void BuyDialog::applyNameFilter(const std::string &filter)
-{
- STD_VECTOR<ShopItem*> &items = mShopItems->allItems();
- std::string filterStr = filter;
- toLower(filterStr);
- FOR_EACH (STD_VECTOR<ShopItem*>::iterator, it, items)
- {
- ShopItem *const item = *it;
- if (item == nullptr)
- continue;
- std::string name = item->getName();
- toLower(name);
- if (name.find(filterStr) != std::string::npos)
- item->setVisible(true);
- else
- item->setVisible(false);
- }
- mShopItems->updateList();
-}
diff --git a/src/gui/windows/buydialog.h b/src/gui/windows/buydialog.h
deleted file mode 100644
index 7914c0ef3..000000000
--- a/src/gui/windows/buydialog.h
+++ /dev/null
@@ -1,207 +0,0 @@
-/*
- * The ManaPlus Client
- * Copyright (C) 2004-2009 The Mana World Development Team
- * Copyright (C) 2009-2010 The Mana Developers
- * Copyright (C) 2011-2017 The ManaPlus Developers
- *
- * This file is part of The ManaPlus Client.
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-#ifndef GUI_WINDOWS_BUYDIALOG_H
-#define GUI_WINDOWS_BUYDIALOG_H
-
-#include "enums/resources/item/itemtype.h"
-
-#include "enums/simpletypes/beingid.h"
-#include "enums/simpletypes/itemcolor.h"
-
-#include "gui/widgets/window.h"
-
-#include "listeners/actionlistener.h"
-#include "listeners/selectionlistener.h"
-
-class Being;
-class Button;
-class DropDown;
-class ShopItem;
-class ShopItems;
-class ShopListBox;
-class SortListModelBuy;
-class IntTextField;
-class Label;
-class ScrollArea;
-class Slider;
-class TextField;
-
-/**
- * The buy dialog.
- *
- * \ingroup Interface
- */
-class BuyDialog final : public Window,
- public ActionListener,
- public SelectionListener
-{
- public:
- /**
- * Constructor.
- *
- * @see Window::Window
- */
- BuyDialog();
-
- /**
- * Constructor.
- *
- * @see Window::Window
- */
- BuyDialog(const BeingId npcId,
- const std::string &currency);
-
-#ifdef TMWA_SUPPORT
- /**
- * Constructor.
- *
- * @see Window::Window
- */
- BuyDialog(const std::string &nick,
- const std::string &currency);
-#endif // TMWA_SUPPORT
-
- /**
- * Constructor.
- *
- * @see Window::Window
- */
- BuyDialog(const Being *const being,
- const std::string &currency);
-
- A_DELETE_COPY(BuyDialog)
-
- /**
- * Destructor
- */
- ~BuyDialog();
-
- enum
- {
-#ifdef TMWA_SUPPORT
- Nick = -1,
-#endif // TMWA_SUPPORT
- Items = -2,
- Market = -3,
- Cash = -4,
- Vending = -5
- };
-
- void init();
-
- /**
- * Resets the dialog, clearing shop inventory.
- */
- void reset();
-
- /**
- * Sets the amount of available money.
- */
- void setMoney(const int amount);
-
- /**
- * Adds an item to the shop inventory.
- */
- ShopItem *addItem(const int id,
- const ItemTypeT type,
- const ItemColor color,
- const int amount,
- const int price);
-
- /**
- * Called when receiving actions from the widgets.
- */
- void action(const ActionEvent &event) override final;
-
- /**
- * Returns the number of items in the shop inventory.
- */
- int getNumberOfElements() A_WARN_UNUSED;
-
- /**
- * Updates the labels according to the selected item.
- */
- void valueChanged(const SelectionEvent &event) override final;
-
- /**
- * Updates the state of buttons and labels.
- */
- void updateButtonsAndLabels();
-
- /**
- * Sets the visibility of this window.
- */
- void setVisible(Visible visible) override final;
-
- void sort();
-
- void close() override final;
-
- /**
- * Returns true if any instances exist.
- */
- static bool isActive() A_WARN_UNUSED
- { return !instances.empty(); }
-
- /**
- * Closes all instances.
- */
- static void closeAll();
-
- private:
- void updateSlider(const int selectedItem);
-
- void applyNameFilter(const std::string &filter);
-
- typedef std::list<BuyDialog*> DialogList;
- static DialogList instances;
-
- Button *mBuyButton A_NONNULLPOINTER;
- Button *mConfirmButton A_NONNULLPOINTER;
- Button *mQuitButton A_NONNULLPOINTER;
- Button *mAddMaxButton A_NONNULLPOINTER;
- Button *mIncreaseButton A_NONNULLPOINTER;
- Button *mDecreaseButton A_NONNULLPOINTER;
- ShopListBox *mShopItemList A_NONNULLPOINTER;
- ScrollArea *mScrollArea A_NONNULLPOINTER;
- Label *mMoneyLabel A_NONNULLPOINTER;
- Label *mQuantityLabel A_NONNULLPOINTER;
- Slider *mSlider A_NONNULLPOINTER;
- Label *mAmountLabel A_NONNULLPOINTER;
- IntTextField *mAmountField A_NONNULLPOINTER;
- ShopItems *mShopItems A_NONNULLPOINTER;
- SortListModelBuy *mSortModel;
- DropDown *mSortDropDown;
- TextField *mFilterTextField A_NONNULLPOINTER;
- Label *mFilterLabel;
-
- std::string mNick;
- std::string mCurrency;
- BeingId mNpcId;
- int mMoney;
- int mAmountItems;
- int mMaxItems;
- bool mAdvanced;
-};
-
-#endif // GUI_WINDOWS_BUYDIALOG_H
diff --git a/src/gui/windows/buyingstoreselldialog.cpp b/src/gui/windows/buyingstoreselldialog.cpp
deleted file mode 100644
index 369d52223..000000000
--- a/src/gui/windows/buyingstoreselldialog.cpp
+++ /dev/null
@@ -1,70 +0,0 @@
-/*
- * The ManaPlus Client
- * Copyright (C) 2004-2009 The Mana World Development Team
- * Copyright (C) 2009-2010 The Mana Developers
- * Copyright (C) 2011-2017 The ManaPlus Developers
- *
- * This file is part of The ManaPlus Client.
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-#include "gui/windows/buyingstoreselldialog.h"
-
-#include "actormanager.h"
-
-#include "being/playerinfo.h"
-
-#include "gui/models/shopitems.h"
-
-#include "gui/widgets/shoplistbox.h"
-
-#include "net/buyingstorehandler.h"
-
-#include "resources/inventory/inventory.h"
-
-#include "resources/item/shopitem.h"
-
-#include "debug.h"
-
-BuyingStoreSellDialog::BuyingStoreSellDialog(const BeingId accountId,
- const int storeId) :
- SellDialog(IsSell_true, Advanced_false),
- mAccountId(accountId),
- mStoreId(storeId)
-{
-}
-
-void BuyingStoreSellDialog::sellAction(const ActionEvent &event A_UNUSED)
-{
- if (mAmountItems <= 0 || mAmountItems > mMaxItems)
- return;
-
- const int selectedItem = mShopItemList->getSelected();
- const ShopItem *const item1 = mShopItems->at(selectedItem);
- if ((item1 == nullptr) || PlayerInfo::isItemProtected(item1->getId()))
- return;
- const Being *const being = actorManager->findBeing(mAccountId);
- if (being == nullptr)
- return;
- const Item *const item2 = PlayerInfo::getInventory()->findItem(
- item1->getId(),
- item1->getColor());
- if (item2 == nullptr)
- return;
-
- mPlayerMoney += mAmountItems * item1->getPrice();
- mMaxItems -= mAmountItems;
- buyingStoreHandler->sell(being, mStoreId, item2, mAmountItems);
-}
diff --git a/src/gui/windows/buyingstoreselldialog.h b/src/gui/windows/buyingstoreselldialog.h
deleted file mode 100644
index db2005213..000000000
--- a/src/gui/windows/buyingstoreselldialog.h
+++ /dev/null
@@ -1,55 +0,0 @@
-/*
- * The ManaPlus Client
- * Copyright (C) 2004-2009 The Mana World Development Team
- * Copyright (C) 2009-2010 The Mana Developers
- * Copyright (C) 2011-2017 The ManaPlus Developers
- *
- * This file is part of The ManaPlus Client.
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-#ifndef GUI_WINDOWS_BUYINGSTORESELLDIALOG_H
-#define GUI_WINDOWS_BUYINGSTORESELLDIALOG_H
-
-#include "enums/simpletypes/beingid.h"
-
-#include "gui/widgets/selldialog.h"
-
-/**
- * The sell dialog.
- *
- * \ingroup Interface
- */
-class BuyingStoreSellDialog final : public SellDialog
-{
- public:
- /**
- * Constructor.
- *
- * @see Window::Window
- */
- BuyingStoreSellDialog(const BeingId accountId,
- const int storeId);
-
- A_DELETE_COPY(BuyingStoreSellDialog)
-
- protected:
- void sellAction(const ActionEvent &event) override final;
-
- BeingId mAccountId;
- int mStoreId;
-};
-
-#endif // GUI_WINDOWS_BUYINGSTORESELLDIALOG_H
diff --git a/src/gui/windows/buyselldialog.cpp b/src/gui/windows/buyselldialog.cpp
deleted file mode 100644
index 26cf2af17..000000000
--- a/src/gui/windows/buyselldialog.cpp
+++ /dev/null
@@ -1,167 +0,0 @@
-/*
- * The ManaPlus Client
- * Copyright (C) 2004-2009 The Mana World Development Team
- * Copyright (C) 2009-2010 The Mana Developers
- * Copyright (C) 2011-2017 The ManaPlus Developers
- *
- * This file is part of The ManaPlus Client.
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-#include "gui/windows/buyselldialog.h"
-
-#include "actormanager.h"
-
-#include "net/buysellhandler.h"
-#include "net/npchandler.h"
-
-#include "gui/windows/setupwindow.h"
-
-#include "gui/widgets/button.h"
-
-#include "utils/foreach.h"
-#include "utils/gettext.h"
-
-#include "debug.h"
-
-BuySellDialog::DialogList BuySellDialog::dialogInstances;
-
-BuySellDialog::BuySellDialog(const BeingId npcId) :
- // TRANSLATORS: shop window name
- Window(_("Shop"), Modal_false, nullptr, "buysell.xml"),
- ActionListener(),
- mNpcId(npcId),
- mNick(""),
- mBuyButton(nullptr)
-{
- init();
-}
-
-BuySellDialog::BuySellDialog(const std::string &nick) :
- // TRANSLATORS: shop window name
- Window(_("Shop"), Modal_false, nullptr, "buysell.xml"),
- ActionListener(),
- mNpcId(BeingId_negOne),
- mNick(nick),
- mBuyButton(nullptr)
-{
- init();
-}
-
-void BuySellDialog::init()
-{
- setWindowName("BuySell");
- setCloseButton(true);
-
- if (setupWindow != nullptr)
- setupWindow->registerWindowForReset(this);
-
- static const char *const buttonNames[] =
- {
- // TRANSLATORS: shop window button
- N_("Buy"),
- // TRANSLATORS: shop window button
- N_("Sell"),
- // TRANSLATORS: shop window button
- N_("Cancel"),
- nullptr
- };
- const int buttonPadding = getOption("buttonpadding", 10);
- int x = buttonPadding;
- const int y = buttonPadding;
-
- for (const char *const *curBtn = buttonNames;
- *curBtn != nullptr;
- curBtn++)
- {
- Button *const btn = new Button(this, gettext(*curBtn), *curBtn, this);
- if (mBuyButton == nullptr)
- mBuyButton = btn; // For focus request
- btn->setPosition(x, y);
- add(btn);
- x += btn->getWidth() + buttonPadding;
- }
- if (mBuyButton != nullptr)
- {
- mBuyButton->requestFocus();
- setContentSize(x, 2 * y + mBuyButton->getHeight());
- }
-
- center();
- setDefaultSize();
- loadWindowState();
- enableVisibleSound(true);
-
- dialogInstances.push_back(this);
- setVisible(Visible_true);
-}
-
-BuySellDialog::~BuySellDialog()
-{
- dialogInstances.remove(this);
-}
-
-void BuySellDialog::setVisible(Visible visible)
-{
- Window::setVisible(visible);
-
- if (visible == Visible_true)
- {
- if (mBuyButton != nullptr)
- mBuyButton->requestFocus();
- }
- else
- {
- scheduleDelete();
- }
-}
-
-void BuySellDialog::action(const ActionEvent &event)
-{
- const std::string &eventId = event.getId();
- if (eventId == "Buy")
- {
- if (mNpcId != BeingId_negOne)
- {
- const Being *const being = actorManager->findBeing(mNpcId);
- if (being != nullptr)
- npcHandler->buy(being);
- else
- npcHandler->buy(mNpcId);
- }
- else
- {
- buySellHandler->requestSellList(mNick);
- }
- }
- else if (eventId == "Sell")
- {
- if (mNpcId != BeingId_negOne)
- npcHandler->sell(mNpcId);
- else
- buySellHandler->requestBuyList(mNick);
- }
-
- close();
-}
-
-void BuySellDialog::closeAll()
-{
- FOR_EACH (DialogList::const_iterator, it, dialogInstances)
- {
- if (*it != nullptr)
- (*it)->close();
- }
-}
diff --git a/src/gui/windows/buyselldialog.h b/src/gui/windows/buyselldialog.h
deleted file mode 100644
index b2a527d16..000000000
--- a/src/gui/windows/buyselldialog.h
+++ /dev/null
@@ -1,86 +0,0 @@
-/*
- * The ManaPlus Client
- * Copyright (C) 2004-2009 The Mana World Development Team
- * Copyright (C) 2009-2010 The Mana Developers
- * Copyright (C) 2011-2017 The ManaPlus Developers
- *
- * This file is part of The ManaPlus Client.
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-#ifndef GUI_WINDOWS_BUYSELLDIALOG_H
-#define GUI_WINDOWS_BUYSELLDIALOG_H
-
-#include "enums/simpletypes/beingid.h"
-
-#include "gui/widgets/window.h"
-
-#include "listeners/actionlistener.h"
-
-class Button;
-
-/**
- * A dialog to choose between buying or selling at a shop.
- *
- * \ingroup Interface
- */
-class BuySellDialog final : public Window,
- public ActionListener
-{
- public:
- /**
- * Constructor. The action listener passed will receive "sell", "buy"
- * or "cancel" events when the respective buttons are pressed.
- *
- * @see Window::Window
- */
- explicit BuySellDialog(const BeingId npcId);
-
- explicit BuySellDialog(const std::string &nick);
-
- A_DELETE_COPY(BuySellDialog)
-
- ~BuySellDialog();
-
- void init();
-
- void setVisible(Visible visible) override final;
-
- /**
- * Called when receiving actions from the widgets.
- */
- void action(const ActionEvent &event) override final;
-
- /**
- * Returns true if any instances exist.
- */
- static bool isActive() A_WARN_UNUSED
- { return !dialogInstances.empty(); }
-
- /**
- * Closes all instances.
- */
- static void closeAll();
-
- private:
- typedef std::list<BuySellDialog*> DialogList;
- static DialogList dialogInstances;
-
- BeingId mNpcId;
- std::string mNick;
- Button *mBuyButton;
-};
-
-#endif // GUI_WINDOWS_BUYSELLDIALOG_H
diff --git a/src/gui/windows/changeemaildialog.cpp b/src/gui/windows/changeemaildialog.cpp
deleted file mode 100644
index 9d9358967..000000000
--- a/src/gui/windows/changeemaildialog.cpp
+++ /dev/null
@@ -1,186 +0,0 @@
-/*
- * The ManaPlus Client
- * Copyright (C) 2008-2009 The Mana World Development Team
- * Copyright (C) 2009-2010 The Mana Developers
- * Copyright (C) 2011-2017 The ManaPlus Developers
- *
- * This file is part of The ManaPlus Client.
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-#include "gui/windows/changeemaildialog.h"
-
-#include "client.h"
-
-#include "gui/windows/okdialog.h"
-
-#include "gui/widgets/button.h"
-#include "gui/widgets/createwidget.h"
-#include "gui/widgets/label.h"
-#include "gui/widgets/textfield.h"
-
-#include "listeners/wrongdatanoticelistener.h"
-
-#include "net/logindata.h"
-#include "net/loginhandler.h"
-
-#include "utils/delete2.h"
-#include "utils/gettext.h"
-
-#include <sstream>
-
-#include "debug.h"
-
-ChangeEmailDialog::ChangeEmailDialog(LoginData &data) :
- // TRANSLATORS: change email dialog header
- Window(_("Change Email Address"), Modal_true, nullptr, "changeemail.xml"),
- ActionListener(),
- mFirstEmailField(new TextField(this)),
- mSecondEmailField(new TextField(this)),
- // TRANSLATORS: button in change email dialog
- mChangeEmailButton(new Button(this, _("Change Email Address"),
- "change_email", this)),
- // TRANSLATORS: button in change email dialog
- mCancelButton(new Button(this, _("Cancel"), "cancel", this)),
- mWrongDataNoticeListener(new WrongDataNoticeListener),
- mLoginData(&data)
-{
- // TRANSLATORS: label in change email dialog
- Label *const accountLabel = new Label(this, strprintf(_("Account: %s"),
- mLoginData->username.c_str()));
- Label *const newEmailLabel = new Label(this,
- // TRANSLATORS: label in change email dialog
- _("Type new email address twice:"));
-
- const int width = 200;
- const int height = 130;
- setContentSize(width, height);
-
- accountLabel->setPosition(5, 5);
- accountLabel->setWidth(130);
-
- newEmailLabel->setPosition(
- 5, accountLabel->getY() + accountLabel->getHeight() + 7);
- newEmailLabel->setWidth(width - 5);
-
- mFirstEmailField->setPosition(
- 5, newEmailLabel->getY() + newEmailLabel->getHeight() + 7);
- mFirstEmailField->setWidth(130);
-
- mSecondEmailField->setPosition(
- 5, mFirstEmailField->getY() + mFirstEmailField->getHeight() + 7);
- mSecondEmailField->setWidth(130);
-
- mCancelButton->setPosition(
- width - 5 - mCancelButton->getWidth(),
- height - 5 - mCancelButton->getHeight());
- mChangeEmailButton->setPosition(
- mCancelButton->getX() - 5 - mChangeEmailButton->getWidth(),
- mCancelButton->getY());
-
- add(accountLabel);
- add(newEmailLabel);
- add(mFirstEmailField);
- add(mSecondEmailField);
- add(mChangeEmailButton);
- add(mCancelButton);
-
- center();
- mFirstEmailField->requestFocus();
-
- mFirstEmailField->setActionEventId("change_email");
- mSecondEmailField->setActionEventId("change_email");
-}
-
-ChangeEmailDialog::~ChangeEmailDialog()
-{
- delete2(mWrongDataNoticeListener);
-}
-
-void ChangeEmailDialog::action(const ActionEvent &event)
-{
- const std::string &eventId = event.getId();
- if (eventId == "cancel")
- {
- client->setState(State::CHAR_SELECT);
- }
- else if (eventId == "change_email")
- {
- const std::string username = mLoginData->username;
- const std::string &newFirstEmail = mFirstEmailField->getText();
- const std::string &newSecondEmail = mSecondEmailField->getText();
- logger->log("ChangeEmailDialog::Email change, Username is %s",
- username.c_str());
-
- std::stringstream errorMsg;
- int error = 0;
-
- const unsigned int min = loginHandler->getMinPasswordLength();
- const unsigned int max = loginHandler->getMaxPasswordLength();
-
- if (newFirstEmail.length() < min)
- {
- // First email address too short
- // TRANSLATORS: change email error
- errorMsg << strprintf(_("The new email address needs to be at "
- "least %u characters long."), min);
- error = 1;
- }
- else if (newFirstEmail.length() > max)
- {
- // First email address too long
- // TRANSLATORS: change email error
- errorMsg << strprintf(_("The new email address needs to be "
- "less than %u characters long."), max);
- error = 1;
- }
- else if (newFirstEmail != newSecondEmail)
- {
- // Second Pass mismatch
- // TRANSLATORS: change email error
- errorMsg << _("The email address entries mismatch.");
- error = 2;
- }
-
- if (error > 0)
- {
- if (error == 1)
- mWrongDataNoticeListener->setTarget(this->mFirstEmailField);
- else // if (error == 2)
- mWrongDataNoticeListener->setTarget(this->mSecondEmailField);
-
- OkDialog *const dlg = CREATEWIDGETR(OkDialog,
- // TRANSLATORS: change email error header
- _("Error"),
- errorMsg.str(),
- // TRANSLATORS: ok dialog button
- _("OK"),
- DialogType::ERROR,
- Modal_true,
- ShowCenter_true,
- nullptr,
- 260);
- dlg->addActionListener(mWrongDataNoticeListener);
- }
- else
- {
- // No errors detected, change account password.
- mChangeEmailButton->setEnabled(false);
- // Set the new email address
- mLoginData->email = newFirstEmail;
- client->setState(State::CHANGEEMAIL_ATTEMPT);
- }
- }
-}
diff --git a/src/gui/windows/changeemaildialog.h b/src/gui/windows/changeemaildialog.h
deleted file mode 100644
index c20dffd9e..000000000
--- a/src/gui/windows/changeemaildialog.h
+++ /dev/null
@@ -1,81 +0,0 @@
-/*
- * The ManaPlus Client
- * Copyright (C) 2008-2009 The Mana World Development Team
- * Copyright (C) 2009-2010 The Mana Developers
- * Copyright (C) 2011-2017 The ManaPlus Developers
- *
- * This file is part of The ManaPlus Client.
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-#ifndef GUI_WINDOWS_CHANGEEMAILDIALOG_H
-#define GUI_WINDOWS_CHANGEEMAILDIALOG_H
-
-#include "gui/widgets/window.h"
-
-#include "listeners/actionlistener.h"
-
-class Button;
-class LoginData;
-class TextField;
-class WrongDataNoticeListener;
-
-/**
- * The Change email dialog.
- *
- * \ingroup Interface
- */
-class ChangeEmailDialog final : public Window,
- public ActionListener
-{
- public:
- /**
- * Constructor.
- *
- * @see Window::Window
- */
- explicit ChangeEmailDialog(LoginData &data);
-
- A_DELETE_COPY(ChangeEmailDialog)
-
- /**
- * Destructor.
- */
- ~ChangeEmailDialog();
-
- /**
- * Called when receiving actions from the widgets.
- */
- void action(const ActionEvent &event) override final;
-
- /**
- * This is used to pass the pointer to where the new email should be
- * put when the dialog finishes.
- */
- static void setEmail(std::string *email);
-
- private:
- TextField *mFirstEmailField A_NONNULLPOINTER;
- TextField *mSecondEmailField A_NONNULLPOINTER;
-
- Button *mChangeEmailButton A_NONNULLPOINTER;
- Button *mCancelButton A_NONNULLPOINTER;
-
- WrongDataNoticeListener *mWrongDataNoticeListener A_NONNULLPOINTER;
-
- LoginData *mLoginData A_NONNULLPOINTER;
-};
-
-#endif // GUI_WINDOWS_CHANGEEMAILDIALOG_H
diff --git a/src/gui/windows/changepassworddialog.cpp b/src/gui/windows/changepassworddialog.cpp
deleted file mode 100644
index ca29a8ef1..000000000
--- a/src/gui/windows/changepassworddialog.cpp
+++ /dev/null
@@ -1,177 +0,0 @@
-/*
- * The ManaPlus Client
- * Copyright (C) 2004-2009 The Mana World Development Team
- * Copyright (C) 2009-2010 The Mana Developers
- * Copyright (C) 2011-2017 The ManaPlus Developers
- *
- * This file is part of The ManaPlus Client.
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-#include "gui/windows/changepassworddialog.h"
-
-#include "client.h"
-
-#include "gui/windows/okdialog.h"
-
-#include "gui/widgets/button.h"
-#include "gui/widgets/createwidget.h"
-#include "gui/widgets/passwordfield.h"
-#include "gui/widgets/label.h"
-#include "gui/widgets/layoutcell.h"
-
-#include "listeners/wrongdatanoticelistener.h"
-
-#include "net/logindata.h"
-#include "net/loginhandler.h"
-
-#include "utils/delete2.h"
-#include "utils/gettext.h"
-
-#include <sstream>
-
-#include "debug.h"
-
-ChangePasswordDialog::ChangePasswordDialog(LoginData &data) :
- // TRANSLATORS: change password window name
- Window(_("Change Password"), Modal_true, nullptr, "changepassword.xml"),
- ActionListener(),
- mOldPassField(new PasswordField(this)),
- mFirstPassField(new PasswordField(this)),
- mSecondPassField(new PasswordField(this)),
- // TRANSLATORS: change password dialog button
- mChangePassButton(new Button(this, _("Change Password"),
- "change_password", this)),
- // TRANSLATORS: change password dialog button
- mCancelButton(new Button(this, _("Cancel"), "cancel", this)),
- mWrongDataNoticeListener(new WrongDataNoticeListener),
- mLoginData(&data)
-{
- Label *const accountLabel = new Label(this,
- // TRANSLATORS: change password dialog label
- strprintf(_("Account: %s"), mLoginData->username.c_str()));
-
- place(0, 0, accountLabel, 3);
- // TRANSLATORS: change password dialog label
- place(0, 1, new Label(this, _("Password:")), 3);
- place(0, 2, mOldPassField, 3).setPadding(1);
- // TRANSLATORS: change password dialog label
- place(0, 3, new Label(this, _("Type new password twice:")), 3);
- place(0, 4, mFirstPassField, 3).setPadding(1);
- place(0, 5, mSecondPassField, 3).setPadding(1);
- place(1, 6, mCancelButton);
- place(2, 6, mChangePassButton);
- reflowLayout(200);
-
- center();
- mOldPassField->requestFocus();
-
- mOldPassField->setActionEventId("change_password");
- mFirstPassField->setActionEventId("change_password");
- mSecondPassField->setActionEventId("change_password");
-}
-
-ChangePasswordDialog::~ChangePasswordDialog()
-{
- delete2(mWrongDataNoticeListener);
-}
-
-void ChangePasswordDialog::action(const ActionEvent &event)
-{
- const std::string &eventId = event.getId();
- if (eventId == "cancel")
- {
- client->setState(State::CHAR_SELECT);
- }
- else if (eventId == "change_password")
- {
- const std::string username = mLoginData->username;
- const std::string &oldPassword = mOldPassField->getText();
- const std::string &newFirstPass = mFirstPassField->getText();
- const std::string &newSecondPass = mSecondPassField->getText();
- logger->log("ChangePasswordDialog::Password change, Username is %s",
- username.c_str());
-
- std::stringstream errorMsg;
- int error = 0;
-
- const unsigned int min = loginHandler->getMinPasswordLength();
- const unsigned int max = loginHandler->getMaxPasswordLength();
-
- // Check old Password
- if (oldPassword.empty())
- {
- // No old password
- // TRANSLATORS: change password error
- errorMsg << _("Enter the old password first.");
- error = 1;
- }
- else if (newFirstPass.length() < min)
- {
- // First password too short
- // TRANSLATORS: change password error
- errorMsg << strprintf(_("The new password needs to be at least"
- " %u characters long."), min);
- error = 2;
- }
- else if (newFirstPass.length() > max)
- {
- // First password too long
- // TRANSLATORS: change password error
- errorMsg << strprintf(_("The new password needs to be less "
- "than %u characters long."), max);
- error = 2;
- }
- else if (newFirstPass != newSecondPass)
- {
- // Second Pass mismatch
- // TRANSLATORS: change password error
- errorMsg << _("The new password entries mismatch.");
- error = 3;
- }
-
- if (error > 0)
- {
- if (error == 1)
- mWrongDataNoticeListener->setTarget(this->mOldPassField);
- else if (error == 2)
- mWrongDataNoticeListener->setTarget(this->mFirstPassField);
- else // if (error == 3)
- mWrongDataNoticeListener->setTarget(this->mSecondPassField);
-
- OkDialog *const dlg = CREATEWIDGETR(OkDialog,
- // TRANSLATORS: change password error header
- _("Error"),
- errorMsg.str(),
- // TRANSLATORS: ok dialog button
- _("OK"),
- DialogType::ERROR,
- Modal_true,
- ShowCenter_true,
- nullptr,
- 260);
- dlg->addActionListener(mWrongDataNoticeListener);
- }
- else
- {
- // No errors detected, change account password.
- mChangePassButton->setEnabled(false);
- // Set the new password
- mLoginData->password = oldPassword;
- mLoginData->newPassword = newFirstPass;
- client->setState(State::CHANGEPASSWORD_ATTEMPT);
- }
- }
-}
diff --git a/src/gui/windows/changepassworddialog.h b/src/gui/windows/changepassworddialog.h
deleted file mode 100644
index dd5c0d152..000000000
--- a/src/gui/windows/changepassworddialog.h
+++ /dev/null
@@ -1,76 +0,0 @@
-/*
- * The ManaPlus Client
- * Copyright (C) 2004-2009 The Mana World Development Team
- * Copyright (C) 2009-2010 The Mana Developers
- * Copyright (C) 2011-2017 The ManaPlus Developers
- *
- * This file is part of The ManaPlus Client.
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-#ifndef GUI_WINDOWS_CHANGEPASSWORDDIALOG_H
-#define GUI_WINDOWS_CHANGEPASSWORDDIALOG_H
-
-#include "gui/widgets/window.h"
-
-#include "listeners/actionlistener.h"
-
-class Button;
-class LoginData;
-class TextField;
-class WrongDataNoticeListener;
-
-/**
- * The Change password dialog.
- *
- * \ingroup Interface
- */
-class ChangePasswordDialog final : public Window,
- public ActionListener
-{
- public:
- /**
- * Constructor
- *
- * @see Window::Window
- */
- explicit ChangePasswordDialog(LoginData &data);
-
- A_DELETE_COPY(ChangePasswordDialog)
-
- /**
- * Destructor
- */
- ~ChangePasswordDialog();
-
- /**
- * Called when receiving actions from the widgets.
- */
- void action(const ActionEvent &event) override final;
-
- private:
- TextField *mOldPassField A_NONNULLPOINTER;
- TextField *mFirstPassField A_NONNULLPOINTER;
- TextField *mSecondPassField A_NONNULLPOINTER;
-
- Button *mChangePassButton A_NONNULLPOINTER;
- Button *mCancelButton A_NONNULLPOINTER;
-
- WrongDataNoticeListener *mWrongDataNoticeListener A_NONNULLPOINTER;
-
- LoginData *mLoginData A_NONNULLPOINTER;
-};
-
-#endif // GUI_WINDOWS_CHANGEPASSWORDDIALOG_H
diff --git a/src/gui/windows/charcreatedialog.cpp b/src/gui/windows/charcreatedialog.cpp
deleted file mode 100644
index 9037ac614..000000000
--- a/src/gui/windows/charcreatedialog.cpp
+++ /dev/null
@@ -1,885 +0,0 @@
-/*
- * The ManaPlus Client
- * Copyright (C) 2004-2009 The Mana World Development Team
- * Copyright (C) 2009-2010 The Mana Developers
- * Copyright (C) 2011-2017 The ManaPlus Developers
- *
- * This file is part of The ManaPlus Client.
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-#include "gui/windows/charcreatedialog.h"
-
-#include "configuration.h"
-
-#include "enums/being/beingdirection.h"
-
-#include "being/being.h"
-
-#include "gui/windows/okdialog.h"
-
-#include "gui/widgets/button.h"
-#include "gui/windows/charselectdialog.h"
-#include "gui/widgets/createwidget.h"
-#include "gui/widgets/label.h"
-#include "gui/widgets/playerbox.h"
-#include "gui/widgets/slider.h"
-#include "gui/widgets/tabstrip.h"
-#include "gui/widgets/textfield.h"
-
-#include "net/charserverhandler.h"
-#include "net/serverfeatures.h"
-
-#include "resources/iteminfo.h"
-
-#include "resources/db/chardb.h"
-#include "resources/db/colordb.h"
-#include "resources/db/itemdb.h"
-
-#include "utils/delete2.h"
-#include "utils/gettext.h"
-
-#include "debug.h"
-
-#undef ERROR
-
-static const BeingActionT actions[] =
-{
- BeingAction::STAND,
- BeingAction::SIT,
- BeingAction::MOVE,
- BeingAction::ATTACK,
- BeingAction::DEAD
-};
-
-static const uint8_t directions[] =
-{
- BeingDirection::DOWN,
- BeingDirection::RIGHT,
- BeingDirection::UP,
- BeingDirection::LEFT
-};
-
-CharCreateDialog::CharCreateDialog(CharSelectDialog *const parent,
- const int slot) :
- // TRANSLATORS: char create dialog name
- Window(_("New Character"), Modal_true, parent, "charcreate.xml"),
- ActionListener(),
- KeyListener(),
- mCharSelectDialog(parent),
- mNameField(new TextField(this, "")),
- // TRANSLATORS: char create dialog label
- mNameLabel(new Label(this, _("Name:"))),
- mNextHairColorButton(nullptr),
- mPrevHairColorButton(nullptr),
- mHairColorLabel(nullptr),
- mHairColorNameLabel(nullptr),
- mNextHairStyleButton(nullptr),
- mPrevHairStyleButton(nullptr),
- mHairStyleLabel(nullptr),
- mHairStyleNameLabel(nullptr),
- mNextRaceButton(nullptr),
- mPrevRaceButton(nullptr),
- mRaceLabel(nullptr),
- mRaceNameLabel(nullptr),
- mNextLookButton(nullptr),
- mPrevLookButton(nullptr),
- mLookLabel(nullptr),
- mLookNameLabel(nullptr),
- // TRANSLATORS: char create dialog button
- mActionButton(new Button(this, _("^"), "action", this)),
- // TRANSLATORS: char create dialog button
- mRotateButton(new Button(this, _(">"), "rotate", this)),
- mAttributeSlider(),
- mAttributeLabel(),
- mAttributeValue(),
- mAttributesLeft(new Label(this,
- // TRANSLATORS: char create dialog label
- strprintf(_("Please distribute %d points"), 99))),
- // TRANSLATORS: char create dialog button
- mCreateButton(new Button(this, _("Create"), "create", this)),
- // TRANSLATORS: char create dialog button
- mCancelButton(new Button(this, _("Cancel"), "cancel", this)),
- mPlayer(Being::createBeing(BeingId_zero,
- ActorType::Player,
- BeingTypeId_zero,
- nullptr)),
- mPlayerBox(new PlayerBox(this, mPlayer, "charcreate_playerbox.xml",
- "charcreate_selectedplayerbox.xml")),
- mGenderStrip(nullptr),
- mMaxPoints(0),
- mUsedPoints(0),
- mRace(CharDB::getMinRace()),
- mLook(0),
- mMinLook(CharDB::getMinLook()),
- mMaxLook(CharDB::getMaxLook()),
- mMinRace(CharDB::getMinRace()),
- mMaxRace(CharDB::getMaxRace()),
- mHairStyle(0),
- mHairColor(0),
- mMaxY(0U),
- mSlot(slot),
- mDefaultGender(Gender::FEMALE),
- mGender(Gender::UNSPECIFIED),
- maxHairColor(CharDB::getMaxHairColor()),
- minHairColor(CharDB::getMinHairColor()),
- maxHairStyle(CharDB::getMaxHairStyle()),
- minHairStyle(CharDB::getMinHairStyle()),
- mAction(0),
- mDirection(0)
-{
- setStickyButtonLock(true);
- setSticky(true);
- setWindowName("NewCharacter");
-
- const int w = 480;
- const int h = 350;
- setContentSize(w, h);
-
- mPlayer->setGender(Gender::MALE);
- const STD_VECTOR<BeingSlot> &items = CharDB::getDefaultItems();
- int i = 1;
- for (STD_VECTOR<BeingSlot>::const_iterator it = items.begin(),
- it_fend = items.end();
- it != it_fend;
- ++ it, i ++)
- {
- const BeingSlot &beingSlot = *it;
- mPlayer->setSpriteCards(i,
- beingSlot.spriteId,
- beingSlot.cardsId);
- }
-
- if (maxHairColor == 0u)
- maxHairColor = ColorDB::getHairSize();
- if (maxHairStyle == 0u)
- maxHairStyle = ItemDB::getNumOfHairstyles();
-
- if (maxHairStyle != 0u)
- {
- mHairStyle = (CAST_U32(rand())
- % maxHairStyle) + minHairStyle;
- }
- else
- {
- mHairStyle = 0;
- }
- if (maxHairColor != 0u)
- {
- mHairColor = (CAST_U32(rand())
- % maxHairColor) + minHairColor;
- }
- else
- {
- mHairColor = 0;
- }
-
- mNameField->setMaximum(24);
-
- if (maxHairColor > minHairColor)
- {
- // TRANSLATORS: This is a narrow symbol used to denote 'next'.
- // You may change this symbol if your language uses another.
- // TRANSLATORS: char create dialog button
- mNextHairColorButton = new Button(this, _(">"), "nextcolor", this);
- // TRANSLATORS: This is a narrow symbol used to denote 'previous'.
- // You may change this symbol if your language uses another.
- // TRANSLATORS: char create dialog button
- mPrevHairColorButton = new Button(this, _("<"), "prevcolor", this);
- // TRANSLATORS: char create dialog label
- mHairColorLabel = new Label(this, _("Hair color:"));
- mHairColorNameLabel = new Label(this, "");
- }
-
- if (maxHairStyle > minHairStyle)
- {
- // TRANSLATORS: char create dialog button
- mNextHairStyleButton = new Button(this, _(">"), "nextstyle", this);
- // TRANSLATORS: char create dialog button
- mPrevHairStyleButton = new Button(this, _("<"), "prevstyle", this);
- // TRANSLATORS: char create dialog label
- mHairStyleLabel = new Label(this, _("Hair style:"));
- mHairStyleNameLabel = new Label(this, "");
- }
-
- if (serverFeatures->haveRaceSelection() && mMinRace < mMaxRace)
- {
- // TRANSLATORS: char create dialog button
- mNextRaceButton = new Button(this, _(">"), "nextrace", this);
- // TRANSLATORS: char create dialog button
- mPrevRaceButton = new Button(this, _("<"), "prevrace", this);
- // TRANSLATORS: char create dialog label
- mRaceLabel = new Label(this, _("Race:"));
- mRaceNameLabel = new Label(this, "");
- }
- if (serverFeatures->haveLookSelection() && mMinLook < mMaxLook)
- {
- // TRANSLATORS: char create dialog button
- mNextLookButton = new Button(this, _(">"), "nextlook", this);
- // TRANSLATORS: char create dialog button
- mPrevLookButton = new Button(this, _("<"), "prevlook", this);
- // TRANSLATORS: char create dialog label
- mLookLabel = new Label(this, _("Look:"));
- mLookNameLabel = new Label(this, "");
- }
-
- if (serverFeatures->haveCreateCharGender())
- {
- const int forceGender = features.getIntValue("forceCharGender");
- if (forceGender == -1)
- {
- const int size = config.getIntValue("fontSize");
- mGenderStrip = new TabStrip(this,
- "gender_" + getWindowName(),
- size + 16);
- mGenderStrip->setPressFirst(false);
- mGenderStrip->addActionListener(this);
- mGenderStrip->setActionEventId("gender_");
- // TRANSLATORS: one char size female character gender
- mGenderStrip->addButton(_("F"), "f", false);
- if (features.getIntValue("forceAccountGender") == -1)
- {
- if (serverFeatures->haveCharOtherGender())
- {
- // TRANSLATORS: one char size male character gender
- mGenderStrip->addButton(_("M"), "m", true);
- // TRANSLATORS: one char size other character gender
- mGenderStrip->addButton(_("O"), "o", false);
- }
- else
- {
- // TRANSLATORS: one char size male character gender
- mGenderStrip->addButton(_("M"), "m", false);
- // TRANSLATORS: one char size unknown character gender
- mGenderStrip->addButton(_("U"), "u", true);
- }
- }
- else
- {
- // TRANSLATORS: one char size male character gender
- mGenderStrip->addButton(_("M"), "m", true);
- if (serverFeatures->haveCharOtherGender())
- {
- // TRANSLATORS: one char size other character gender
- mGenderStrip->addButton(_("O"), "o", false);
- }
- }
-
-
- mGenderStrip->setVisible(Visible_true);
- add(mGenderStrip);
-
- mGenderStrip->setPosition(385, 130);
- mGenderStrip->setWidth(500);
- mGenderStrip->setHeight(50);
- }
- else
- {
- mGender = Being::intToGender(CAST_U8(forceGender));
- mPlayer->setGender(mGender);
- }
- }
-
- mPlayerBox->setWidth(74);
-
- mNameField->setActionEventId("create");
- mNameField->addActionListener(this);
-
- mPlayerBox->setDimension(Rect(360, 0, 110, 90));
- mActionButton->setPosition(385, 100);
- mRotateButton->setPosition(415, 100);
-
- mNameLabel->setPosition(mPadding, 2);
- mNameField->setDimension(Rect(60, 2,
- 300, mNameField->getHeight()));
-
- const uint32_t labelPadding = getOption("labelPadding", 2);
- const uint32_t leftX = 120 + mPadding;
- const uint32_t rightX = 300 + mPadding;
- const uint32_t labelX = mPadding;
- uint32_t nameX = leftX + labelPadding;
- uint32_t y = 30;
- if (mPrevHairColorButton != nullptr)
- nameX += mPrevHairColorButton->getWidth();
- else if (mPrevHairStyleButton != nullptr)
- nameX += mPrevHairStyleButton->getWidth();
- else if (mPrevLookButton != nullptr)
- nameX += mPrevLookButton->getWidth();
- else if (mPrevRaceButton != nullptr)
- nameX += mPrevRaceButton->getWidth();
-
- if (maxHairColor > minHairColor)
- {
- mPrevHairColorButton->setPosition(leftX, y);
- mNextHairColorButton->setPosition(rightX, y);
- y += 5;
- mHairColorLabel->setPosition(labelX, y);
- mHairColorNameLabel->setPosition(nameX, y);
- y += 24;
- }
- if (maxHairStyle > minHairStyle)
- {
- mPrevHairStyleButton->setPosition(leftX, y);
- mNextHairStyleButton->setPosition(rightX, y);
- y += 5;
- mHairStyleLabel->setPosition(labelX, y);
- mHairStyleNameLabel->setPosition(nameX, y);
- y += 24;
- }
-
- if (serverFeatures->haveLookSelection() && mMinLook < mMaxLook)
- {
- if (mPrevLookButton != nullptr)
- mPrevLookButton->setPosition(leftX, y);
- if (mNextLookButton != nullptr)
- mNextLookButton->setPosition(rightX, y);
- y += 5;
- if (mLookLabel != nullptr)
- mLookLabel->setPosition(labelX, y);
- if (mLookNameLabel != nullptr)
- mLookNameLabel->setPosition(nameX, y); // 93
- y += 24;
- }
- if (serverFeatures->haveRaceSelection() && mMinRace < mMaxRace)
- {
- if (mPrevRaceButton != nullptr)
- mPrevRaceButton->setPosition(leftX, y);
- if (mNextRaceButton != nullptr)
- mNextRaceButton->setPosition(rightX, y);
- y += 5;
- if (mRaceLabel != nullptr)
- mRaceLabel->setPosition(labelX, y);
- if (mRaceNameLabel != nullptr)
- mRaceNameLabel->setPosition(nameX, y);
- }
- mMaxY = y + 29 + getTitlePadding();
-
- updateSliders();
- setButtonsPosition(w, h);
-
- add(mPlayerBox);
- add(mNameField);
- add(mNameLabel);
-
- if (maxHairColor > minHairColor)
- {
- add(mNextHairColorButton);
- add(mPrevHairColorButton);
- add(mHairColorLabel);
- add(mHairColorNameLabel);
- }
-
- if (maxHairStyle > minHairStyle)
- {
- add(mNextHairStyleButton);
- add(mPrevHairStyleButton);
- add(mHairStyleLabel);
- add(mHairStyleNameLabel);
- }
- add(mActionButton);
- add(mRotateButton);
-
- if (serverFeatures->haveLookSelection() && mMinLook < mMaxLook)
- {
- add(mNextLookButton);
- add(mPrevLookButton);
- add(mLookLabel);
- add(mLookNameLabel);
- }
-
- if (serverFeatures->haveRaceSelection() && mMinRace < mMaxRace)
- {
- add(mNextRaceButton);
- add(mPrevRaceButton);
- add(mRaceLabel);
- add(mRaceNameLabel);
- }
-
- add(mAttributesLeft);
- add(mCreateButton);
- add(mCancelButton);
-
- center();
- setVisible(Visible_true);
- mNameField->requestFocus();
-
- updateHair();
- if (serverFeatures->haveRaceSelection() && mMinRace < mMaxRace)
- updateRace();
- if (serverFeatures->haveLookSelection() && mMinLook < mMaxLook)
- updateLook();
- updatePlayer();
-
- addKeyListener(this);
-}
-
-CharCreateDialog::~CharCreateDialog()
-{
- delete2(mPlayer);
-
- if (charServerHandler != nullptr)
- charServerHandler->setCharCreateDialog(nullptr);
-}
-
-void CharCreateDialog::action(const ActionEvent &event)
-{
- const std::string &id = event.getId();
- if (id == "create")
- {
- if (getName().length() >= 4)
- {
- // Attempt to create the character
- mCreateButton->setEnabled(false);
-
- STD_VECTOR<int> atts;
- const size_t sz = mAttributeSlider.size();
- for (size_t i = 0; i < sz; i++)
- {
- atts.push_back(CAST_S32(
- mAttributeSlider[i]->getValue()));
- }
- for (size_t i = sz; i < 6; i ++)
- atts.push_back(1);
-
- const int characterSlot = mSlot;
-
- charServerHandler->newCharacter(getName(),
- characterSlot,
- mGender,
- mHairStyle,
- mHairColor,
- CAST_U8(mRace),
- CAST_U8(mLook),
- atts);
- }
- else
- {
- CREATEWIDGET(OkDialog,
- // TRANSLATORS: char creation error
- _("Error"),
- // TRANSLATORS: char creation error
- _("Your name needs to be at least 4 characters."),
- // TRANSLATORS: ok dialog button
- _("OK"),
- DialogType::ERROR,
- Modal_true,
- ShowCenter_true,
- nullptr,
- 260);
- }
- }
- else if (id == "cancel")
- {
- scheduleDelete();
- }
- else if (id == "nextcolor")
- {
- mHairColor ++;
- updateHair();
- }
- else if (id == "prevcolor")
- {
- mHairColor --;
- updateHair();
- }
- else if (id == "nextstyle")
- {
- mHairStyle ++;
- updateHair();
- }
- else if (id == "prevstyle")
- {
- mHairStyle --;
- updateHair();
- }
- else if (id == "nextrace")
- {
- mRace ++;
- updateRace();
- }
- else if (id == "prevrace")
- {
- mRace --;
- updateRace();
- }
- else if (id == "nextlook")
- {
- mLook ++;
- updateLook();
- }
- else if (id == "prevlook")
- {
- mLook --;
- updateLook();
- }
- else if (id == "statslider")
- {
- updateSliders();
- }
- else if (id == "action")
- {
- mAction ++;
- if (mAction >= 5)
- mAction = 0;
- updatePlayer();
- }
- else if (id == "rotate")
- {
- mDirection ++;
- if (mDirection >= 4)
- mDirection = 0;
- updatePlayer();
- }
- else if (id == "gender_m")
- {
- mGender = Gender::MALE;
- mPlayer->setGender(Gender::MALE);
- }
- else if (id == "gender_f")
- {
- mGender = Gender::FEMALE;
- mPlayer->setGender(Gender::FEMALE);
- }
- else if (id == "gender_u")
- {
- mGender = Gender::UNSPECIFIED;
- mPlayer->setGender(mDefaultGender);
- }
- else if (id == "gender_o")
- {
- mGender = Gender::OTHER;
- mPlayer->setGender(Gender::OTHER);
- }
-}
-
-std::string CharCreateDialog::getName() const
-{
- std::string name = mNameField->getText();
- trim(name);
- return name;
-}
-
-void CharCreateDialog::updateSliders()
-{
- for (size_t i = 0, sz = mAttributeSlider.size(); i < sz; i++)
- {
- // Update captions
- mAttributeValue[i]->setCaption(
- toString(CAST_S32(mAttributeSlider[i]->getValue())));
- mAttributeValue[i]->adjustSize();
- }
-
- // Update distributed points
- const int pointsLeft = mMaxPoints - getDistributedPoints();
- if (pointsLeft == 0)
- {
- // TRANSLATORS: char create dialog label
- mAttributesLeft->setCaption(_("Character stats OK"));
- mCreateButton->setEnabled(true);
- }
- else
- {
- mCreateButton->setEnabled(false);
- if (pointsLeft > 0)
- {
- mAttributesLeft->setCaption(
- // TRANSLATORS: char create dialog label
- strprintf(_("Please distribute %d points"), pointsLeft));
- }
- else
- {
- mAttributesLeft->setCaption(
- // TRANSLATORS: char create dialog label
- strprintf(_("Please remove %d points"), -pointsLeft));
- }
- }
-
- mAttributesLeft->adjustSize();
-}
-
-void CharCreateDialog::unlock()
-{
- mCreateButton->setEnabled(true);
-}
-
-int CharCreateDialog::getDistributedPoints() const
-{
- int points = 0;
-
- for (size_t i = 0, sz = mAttributeSlider.size(); i < sz; i++)
- points += CAST_S32(mAttributeSlider[i]->getValue());
- return points;
-}
-
-void CharCreateDialog::setAttributes(const StringVect &labels,
- int available,
- const int min, const int max)
-{
- size_t sz;
-
- if (min == max || available == 0)
- {
- sz = 0U;
- available = 0;
- }
- else
- {
- sz = labels.size();
- }
-
- mMaxPoints = available;
-
- for (size_t i = 0; i < mAttributeLabel.size(); i++)
- {
- remove(mAttributeLabel[i]);
- delete2(mAttributeLabel[i])
- remove(mAttributeSlider[i]);
- delete2(mAttributeSlider[i])
- remove(mAttributeValue[i]);
- delete2(mAttributeValue[i])
- }
-
- mAttributeLabel.resize(sz);
- mAttributeSlider.resize(sz);
- mAttributeValue.resize(sz);
-
- const uint32_t w = 480;
- uint32_t h = 350;
- uint32_t y = 89;
- if (serverFeatures->haveLookSelection() && mMinLook < mMaxLook)
- y += 29;
- if (serverFeatures->haveRaceSelection() && mMinRace < mMaxRace)
- y += 29;
-
- for (size_t i = 0; i < sz; i++)
- {
- mAttributeLabel[i] = new Label(this, labels[i]);
- mAttributeLabel[i]->setWidth(70);
- mAttributeLabel[i]->setPosition(mPadding,
- y + CAST_S32(i * 24));
- mAttributeLabel[i]->adjustSize();
- add(mAttributeLabel[i]);
-
- mAttributeSlider[i] = new Slider(this, min, max, 1.0);
- mAttributeSlider[i]->setDimension(Rect(140 + mPadding,
- y + CAST_S32(i * 24),
- 150,
- 12));
- mAttributeSlider[i]->setActionEventId("statslider");
- mAttributeSlider[i]->addActionListener(this);
- add(mAttributeSlider[i]);
-
- mAttributeValue[i] = new Label(this, toString(min));
- mAttributeValue[i]->setPosition(295 + mPadding,
- y + CAST_S32(i * 24));
- add(mAttributeValue[i]);
- }
-
- updateSliders();
- if (available == 0)
- {
- mAttributesLeft->setVisible(Visible_false);
- h = y;
- }
- else
- {
- h = y +
- CAST_S32(sz) * 24 +
- mAttributesLeft->getHeight() +
- getPadding();
- }
- if (serverFeatures->haveCreateCharGender() &&
- features.getIntValue("forceCharGender") == -1 &&
- y < 160)
- {
- if (h < 160)
- h = 160;
- }
- if (h < mMaxY)
- h = mMaxY;
- if (serverFeatures->haveCreateCharGender())
- {
- const int forceGender = features.getIntValue("forceCharGender");
- if (forceGender == -1 && h < 180)
- h = 180;
- else if (h < 120)
- h = 120;
- }
- h += mCreateButton->getHeight();
-
- setContentSize(w, h);
- setButtonsPosition(w, h);
-}
-
-void CharCreateDialog::setDefaultGender(const GenderT gender)
-{
- if (features.getIntValue("forceCharGender") != -1)
- return;
-
- mDefaultGender = gender;
- mPlayer->setGender(gender);
-}
-
-void CharCreateDialog::updateHair()
-{
- if (mHairStyle <= 0)
- mHairStyle = ItemDB::getNumOfHairstyles() - 1;
- else
- mHairStyle %= ItemDB::getNumOfHairstyles();
- if (mHairStyle < CAST_S32(minHairStyle)
- || mHairStyle > CAST_S32(maxHairStyle))
- {
- mHairStyle = minHairStyle;
- }
- const ItemInfo &item = ItemDB::get(-mHairStyle);
- if (mHairStyleNameLabel != nullptr)
- {
- mHairStyleNameLabel->setCaption(item.getName());
- mHairStyleNameLabel->resizeTo(150, 150);
- }
-
- if (ColorDB::getHairSize() != 0)
- mHairColor %= ColorDB::getHairSize();
- else
- mHairColor = 0;
- if (mHairColor < 0)
- mHairColor += ColorDB::getHairSize();
- if (mHairColor < CAST_S32(minHairColor)
- || mHairColor > CAST_S32(maxHairColor))
- {
- mHairColor = minHairColor;
- }
- if (mHairColorNameLabel != nullptr)
- {
- mHairColorNameLabel->setCaption(ColorDB::getHairColorName(
- fromInt(mHairColor, ItemColor)));
- mHairColorNameLabel->resizeTo(150, 150);
- }
-
- mPlayer->setSpriteColor(charServerHandler->hairSprite(),
- mHairStyle * -1,
- item.getDyeColorsString(fromInt(mHairColor, ItemColor)));
- updatePlayer();
-}
-
-void CharCreateDialog::updateRace()
-{
- if (mRace < mMinRace)
- mRace = mMaxRace;
- else if (mRace > mMaxRace)
- mRace = mMinRace;
-
- updateLook();
-}
-
-void CharCreateDialog::updateLook()
-{
- const ItemInfo &item = ItemDB::get(-100 - mRace);
- const int sz = item.getColorsSize();
- if (sz > 0 && serverFeatures->haveLookSelection())
- {
- if (mLook < 0)
- mLook = sz - 1;
- if (mLook > mMaxLook)
- mLook = mMinLook;
- if (mLook >= sz)
- mLook = mMinLook;
- }
- else
- {
- mLook = 0;
- }
- mPlayer->setSubtype(fromInt(mRace, BeingTypeId),
- CAST_U8(mLook));
- if (mRaceNameLabel != nullptr)
- {
- mRaceNameLabel->setCaption(item.getName());
- mRaceNameLabel->resizeTo(150, 150);
- }
- if (mLookNameLabel != nullptr)
- {
- mLookNameLabel->setCaption(item.getColorName(
- fromInt(mLook, ItemColor)));
- mLookNameLabel->resizeTo(150, 150);
- }
-}
-
-void CharCreateDialog::logic()
-{
- BLOCK_START("CharCreateDialog::logic")
- if (mPlayer != nullptr)
- mPlayer->logic();
- BLOCK_END("CharCreateDialog::logic")
-}
-
-void CharCreateDialog::updatePlayer()
-{
- if (mPlayer != nullptr)
- {
- mPlayer->setDirection(directions[mDirection]);
- mPlayer->setAction(actions[mAction], 0);
- }
-}
-
-void CharCreateDialog::keyPressed(KeyEvent &event)
-{
- const InputActionT actionId = event.getActionId();
- PRAGMA45(GCC diagnostic push)
- PRAGMA45(GCC diagnostic ignored "-Wswitch-enum")
- switch (actionId)
- {
- case InputAction::GUI_CANCEL:
- event.consume();
- action(ActionEvent(mCancelButton,
- mCancelButton->getActionEventId()));
- break;
-
- default:
- break;
- }
- PRAGMA45(GCC diagnostic pop)
-}
-
-void CharCreateDialog::setButtonsPosition(const int w, const int h)
-{
- const int h2 = h - 5 - mCancelButton->getHeight();
- if (mainGraphics->getHeight() < 480)
- {
- if (mMaxPoints != 0)
- {
- mCreateButton->setPosition(337, 160);
- mCancelButton->setPosition(337 + mCreateButton->getWidth(), 160);
- }
- else
- {
- mCancelButton->setPosition(
- w / 2,
- 160);
- mCreateButton->setPosition(
- mCancelButton->getX() - 5 - mCreateButton->getWidth(),
- 160);
- }
- }
- else
- {
- mCancelButton->setPosition(
- w / 2,
- h2);
- mCreateButton->setPosition(
- mCancelButton->getX() - 5 - mCreateButton->getWidth(),
- h2);
- }
- mAttributesLeft->setPosition(15, h2 - mAttributesLeft->getHeight());
-}
diff --git a/src/gui/windows/charcreatedialog.h b/src/gui/windows/charcreatedialog.h
deleted file mode 100644
index 5c4fdfcc3..000000000
--- a/src/gui/windows/charcreatedialog.h
+++ /dev/null
@@ -1,171 +0,0 @@
-/*
- * The ManaPlus Client
- * Copyright (C) 2009 The Mana World Development Team
- * Copyright (C) 2009-2010 The Mana Developers
- * Copyright (C) 2011-2017 The ManaPlus Developers
- *
- * This file is part of The ManaPlus Client.
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-#ifndef GUI_WINDOWS_CHARCREATEDIALOG_H
-#define GUI_WINDOWS_CHARCREATEDIALOG_H
-
-#include "enums/being/gender.h"
-
-#include "gui/widgets/window.h"
-
-#include "listeners/actionlistener.h"
-#include "listeners/keylistener.h"
-
-class Being;
-class Button;
-class CharSelectDialog;
-class Label;
-class PlayerBox;
-class Slider;
-class TabStrip;
-class TextField;
-
-/**
- * Character creation dialog.
- *
- * \ingroup Interface
- */
-class CharCreateDialog final : public Window,
- public ActionListener,
- public KeyListener
-{
- public:
- /**
- * Constructor.
- */
- CharCreateDialog(CharSelectDialog *const parent, const int slot);
-
- A_DELETE_COPY(CharCreateDialog)
-
- /**
- * Destructor.
- */
- ~CharCreateDialog();
-
- void action(const ActionEvent &event) override final;
-
- /**
- * Unlocks the dialog, enabling the create character button again.
- */
- void unlock();
-
- void setAttributes(const StringVect &labels,
- int available,
- const int min, const int max);
-
- void setDefaultGender(const GenderT gender = Gender::FEMALE);
-
- void logic() override final;
-
- void updatePlayer();
-
- void keyPressed(KeyEvent &event) override final;
-
- private:
- int getDistributedPoints() const A_WARN_UNUSED;
-
- void updateSliders();
-
- void setButtonsPosition(const int w, const int h);
-
- /**
- * Returns the name of the character to create.
- */
- std::string getName() const A_WARN_UNUSED;
-
- /**
- * Communicate character creation to the server.
- */
- void attemptCharCreate();
-
- void updateHair();
-
- void updateRace();
-
- void updateLook();
-
- CharSelectDialog *mCharSelectDialog;
-
- TextField *mNameField A_NONNULLPOINTER;
- Label *mNameLabel A_NONNULLPOINTER;
- Button *mNextHairColorButton A_NONNULLPOINTER;
- Button *mPrevHairColorButton A_NONNULLPOINTER;
- Label *mHairColorLabel A_NONNULLPOINTER;
- Label *mHairColorNameLabel A_NONNULLPOINTER;
- Button *mNextHairStyleButton A_NONNULLPOINTER;
- Button *mPrevHairStyleButton A_NONNULLPOINTER;
- Label *mHairStyleLabel A_NONNULLPOINTER;
- Label *mHairStyleNameLabel A_NONNULLPOINTER;
- Button *mNextRaceButton;
- Button *mPrevRaceButton;
- Label *mRaceLabel;
- Label *mRaceNameLabel;
- Button *mNextLookButton;
- Button *mPrevLookButton;
- Label *mLookLabel;
- Label *mLookNameLabel;
-
- Button *mActionButton;
- Button *mRotateButton;
-
- STD_VECTOR<Slider*> mAttributeSlider;
- STD_VECTOR<Label*> mAttributeLabel;
- STD_VECTOR<Label*> mAttributeValue;
- Label *mAttributesLeft;
-
- Button *mCreateButton;
- Button *mCancelButton;
-
- Being *mPlayer;
- PlayerBox *mPlayerBox;
-
- TabStrip *mGenderStrip;
-
- int mMaxPoints;
- int mUsedPoints;
-
- int mRace;
- int mLook;
- int mMinLook;
- int mMaxLook;
- int mMinRace;
- int mMaxRace;
-
- int mHairStyle;
- int mHairColor;
- uint32_t mMaxY;
-
- int mSlot;
-
- GenderT mDefaultGender;
- GenderT mGender;
-
- unsigned int maxHairColor;
- unsigned int minHairColor;
- unsigned int maxHairStyle;
- unsigned int minHairStyle;
-
- unsigned int mAction;
- unsigned int mDirection;
-};
-
-#endif // GUI_WINDOWS_CHARCREATEDIALOG_H
diff --git a/src/gui/windows/chardeleteconfirm.h b/src/gui/windows/chardeleteconfirm.h
deleted file mode 100644
index 7049050a3..000000000
--- a/src/gui/windows/chardeleteconfirm.h
+++ /dev/null
@@ -1,65 +0,0 @@
-/*
- * The ManaPlus Client
- * Copyright (C) 2004-2009 The Mana World Development Team
- * Copyright (C) 2009-2010 The Mana Developers
- * Copyright (C) 2011-2017 The ManaPlus Developers
- *
- * This file is part of The ManaPlus Client.
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-#ifndef GUI_WINDOWS_CHARDELETECONFIRM_H
-#define GUI_WINDOWS_CHARDELETECONFIRM_H
-
-#include "gui/windows/charselectdialog.h"
-#include "gui/windows/confirmdialog.h"
-
-#include "utils/gettext.h"
-
-#include "localconsts.h"
-
-/**
- * Listener for confirming character deletion.
- */
-class CharDeleteConfirm final : public ConfirmDialog
-{
- public:
- CharDeleteConfirm(CharSelectDialog *const m, const int index) :
- // TRANSLATORS: char deletion message
- ConfirmDialog(_("Confirm Character Delete"),
- // TRANSLATORS: char deletion message
- _("Are you sure you want to delete this character?"),
- SOUND_REQUEST, false, Modal_false, m),
- mMaster(m),
- mIndex(index)
- {
- }
-
- A_DELETE_COPY(CharDeleteConfirm)
-
- void action(const ActionEvent &event) override final
- {
- if (event.getId() == "yes" && (mMaster != nullptr))
- mMaster->askPasswordForDeletion(mIndex);
-
- ConfirmDialog::action(event);
- }
-
- private:
- CharSelectDialog *mMaster;
- int mIndex;
-};
-
-#endif // GUI_WINDOWS_CHARDELETECONFIRM_H
diff --git a/src/gui/windows/charselectdialog.cpp b/src/gui/windows/charselectdialog.cpp
deleted file mode 100644
index 5a0a02acb..000000000
--- a/src/gui/windows/charselectdialog.cpp
+++ /dev/null
@@ -1,644 +0,0 @@
-/*
- * The ManaPlus Client
- * Copyright (C) 2004-2009 The Mana World Development Team
- * Copyright (C) 2009-2010 The Mana Developers
- * Copyright (C) 2011-2017 The ManaPlus Developers
- *
- * This file is part of The ManaPlus Client.
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-#include "gui/windows/charselectdialog.h"
-
-#include "client.h"
-#include "configuration.h"
-
-#include "listeners/charrenamelistener.h"
-#include "listeners/pincodelistener.h"
-
-#include "gui/windows/charcreatedialog.h"
-#include "gui/windows/chardeleteconfirm.h"
-#include "gui/windows/editdialog.h"
-#include "gui/windows/logindialog.h"
-#include "gui/windows/okdialog.h"
-#include "gui/windows/textdialog.h"
-
-#include "gui/widgets/button.h"
-#include "gui/widgets/characterdisplay.h"
-#include "gui/widgets/characterviewnormal.h"
-#include "gui/widgets/characterviewsmall.h"
-#include "gui/widgets/containerplacer.h"
-#include "gui/widgets/createwidget.h"
-
-#include "net/character.h"
-#include "net/charserverhandler.h"
-#include "net/logindata.h"
-#ifdef TMWA_SUPPORT
-#include "net/net.h"
-#endif // TMWA_SUPPORT
-#include "net/serverfeatures.h"
-
-#include "utils/foreach.h"
-
-#include "resources/db/unitsdb.h"
-
-#include "debug.h"
-
-// Character slots per row in the dialog
-static const int SLOTS_PER_ROW = 5;
-
-CharSelectDialog::CharSelectDialog(LoginData &data) :
- // TRANSLATORS: char select dialog name
- Window(strprintf(_("Account %s (last login time %s)"),
- data.username.c_str(), data.lastLogin.c_str()),
- Modal_false,
- nullptr,
- "char.xml"),
- ActionListener(),
- KeyListener(),
- mLoginData(&data),
- // TRANSLATORS: char select dialog. button.
- mSwitchLoginButton(new Button(this, _("Switch"), "switch", this)),
- // TRANSLATORS: char select dialog. button.
- mChangePasswordButton(new Button(this, _("Password"),
- "change_password", this)),
- // TRANSLATORS: char select dialog. button.
- mPlayButton(new Button(this, _("Play"), "use", this)),
- // TRANSLATORS: char select dialog. button.
- mInfoButton(new Button(this, _("Info"), "info", this)),
- // TRANSLATORS: char select dialog. button.
- mDeleteButton(new Button(this, _("Delete"), "delete", this)),
- // TRANSLATORS: char select dialog. button.
- mRenameButton(nullptr),
- mCharacterView(nullptr),
- mCharacterEntries(0),
- mCharServerHandler(charServerHandler),
- mDeleteDialog(nullptr),
- mDeleteIndex(-1),
- mLocked(false),
- mSmallScreen(mainGraphics->getWidth() < 470
- || mainGraphics->getHeight() < 370)
-{
- setCloseButton(true);
- setFocusable(true);
-
- ContainerPlacer placer;
- placer = getPlacer(0, 0);
-
- placer(0, 0, mSwitchLoginButton);
-
- int n = 1;
- placer(n, 0, mChangePasswordButton);
- n ++;
- placer(n, 0, mDeleteButton);
- n ++;
-#ifdef TMWA_SUPPORT
- if (Net::getNetworkType() != ServerType::TMWATHENA)
-#endif
- {
- mRenameButton = new Button(this,
- // TRANSLATORS: character rename button
- _("Rename"),
- "rename",
- this);
- placer(n, 0, mRenameButton);
- n ++;
- }
- placer(n, 0, mInfoButton);
- n ++;
-
- for (int i = 0; i < CAST_S32(mLoginData->characterSlots); i++)
- {
- CharacterDisplay *const character = new CharacterDisplay(this, this);
- character->setVisible(Visible_false);
- mCharacterEntries.push_back(character);
- }
-
- placer(0, 2, mPlayButton);
-
- if (!mSmallScreen)
- {
- mCharacterView = new CharacterViewNormal(
- this, &mCharacterEntries, mPadding);
- placer(0, 1, mCharacterView, 10);
- int sz = 410 + 2 * mPadding;
- if (config.getIntValue("fontSize") > 18)
- sz = 500 + 2 * mPadding;
- const int width = mCharacterView->getWidth() + 2 * mPadding;
- if (sz < width)
- sz = width;
- if (sz > mainGraphics->getWidth())
- sz = mainGraphics->getWidth();
- reflowLayout(sz);
- }
- else
- {
- // TRANSLATORS: char select dialog name
- setCaption(strprintf(_("Account %s"), mLoginData->username.c_str()));
- mCharacterView = new CharacterViewSmall(
- this, &mCharacterEntries, mPadding);
- mCharacterView->setWidth(mainGraphics->getWidth()
- - 2 * getPadding());
- placer(0, 1, mCharacterView, 10);
- reflowLayout();
- }
- addKeyListener(this);
- center();
-
- charServerHandler->setCharSelectDialog(this);
- mCharacterView->show(0);
- updateState();
-}
-
-CharSelectDialog::~CharSelectDialog()
-{
-}
-
-void CharSelectDialog::postInit()
-{
- Window::postInit();
- setVisible(Visible_true);
- requestFocus();
- if (charServerHandler->isNeedCreatePin())
- {
- EditDialog *const dialog = CREATEWIDGETR(EditDialog,
- // TRANSLATORS: pin code dialog header.
- _("Please set new pincode"),
- "",
- "OK");
- dialog->addActionListener(&pincodeListener);
- }
-}
-
-void CharSelectDialog::action(const ActionEvent &event)
-{
- // Check if a button of a character was pressed
- const Widget *const sourceParent = event.getSource()->getParent();
- int selected = -1;
- for (unsigned int i = 0, fsz = CAST_U32(
- mCharacterEntries.size());
- i < fsz;
- ++i)
- {
- if (mCharacterEntries[i] == sourceParent)
- {
- selected = i;
- mCharacterView->show(i);
- updateState();
- break;
- }
- }
- if (selected == -1)
- selected = mCharacterView->getSelected();
-
- const std::string &eventId = event.getId();
-
- if (selected >= 0)
- {
- if (eventId == "use")
- {
- use(selected);
- return;
- }
- else if (eventId == "delete"
- && (mCharacterEntries[selected]->getCharacter() != nullptr))
- {
- CREATEWIDGET(CharDeleteConfirm, this, selected);
- return;
- }
- else if (eventId == "rename"
- && (mCharacterEntries[selected]->getCharacter() != nullptr))
- {
- const LocalPlayer *const player = mCharacterEntries[
- selected]->getCharacter()->dummy;
- EditDialog *const dialog = CREATEWIDGETR(EditDialog,
- // TRANSLATORS: character rename dialog header.
- _("Please enter new name"),
- player->getName(),
- "OK");
- charRenameListener.setId(player->getId());
- charRenameListener.setDialog(dialog);
- dialog->addActionListener(&charRenameListener);
- }
- else if (eventId == "info")
- {
- Net::Character *const character = mCharacterEntries[
- selected]->getCharacter();
- if (character == nullptr)
- return;
-
- const LocalPlayer *const data = character->dummy;
- if (data == nullptr)
- return;
-
- const std::string strExp = toString(CAST_U64(
- character->data.mAttributes[Attributes::PLAYER_EXP]));
- const std::string msg = strprintf(
- // TRANSLATORS: char select dialog. player info message.
- _("Hp: %u/%u\nMp: %u/%u\nLevel: %u\n"
- "Experience: %s\nMoney: %s"),
- CAST_U32(
- character->data.mAttributes[Attributes::PLAYER_HP]),
- CAST_U32(
- character->data.mAttributes[Attributes::PLAYER_MAX_HP]),
- CAST_U32(
- character->data.mAttributes[Attributes::PLAYER_MP]),
- CAST_U32(
- character->data.mAttributes[Attributes::PLAYER_MAX_MP]),
- CAST_U32(
- character->data.mAttributes[Attributes::PLAYER_BASE_LEVEL]),
- strExp.c_str(),
- UnitsDb::formatCurrency(CAST_S32(
- character->data.mAttributes[Attributes::MONEY])).c_str());
- CREATEWIDGET(OkDialog, data->getName(), msg,
- // TRANSLATORS: ok dialog button
- _("OK"),
- DialogType::SILENCE,
- Modal_true,
- ShowCenter_true,
- nullptr,
- 260);
- }
- }
- if (eventId == "switch")
- {
- charServerHandler->clear();
- close();
- }
- else if (eventId == "change_password")
- {
- client->setState(State::CHANGEPASSWORD);
- }
- else if (eventId == "change_email")
- {
- client->setState(State::CHANGEEMAIL);
- }
- else if (eventId == "try delete character")
- {
- if ((mDeleteDialog != nullptr) && mDeleteIndex != -1)
- {
- if (serverFeatures->haveEmailOnDelete())
- {
- attemptCharacterDelete(mDeleteIndex, mDeleteDialog->getText());
- mDeleteDialog = nullptr;
- }
- else if (mDeleteDialog->getText() == LoginDialog::savedPassword)
- {
- attemptCharacterDelete(mDeleteIndex, "");
- mDeleteDialog = nullptr;
- }
- else
- {
- CREATEWIDGET(OkDialog,
- // TRANSLATORS: error header
- _("Error"),
- // TRANSLATORS: error message
- _("Incorrect password"),
- // TRANSLATORS: ok dialog button
- _("OK"),
- DialogType::ERROR,
- Modal_true,
- ShowCenter_true,
- nullptr,
- 260);
- }
- }
- mDeleteIndex = -1;
- }
-}
-
-void CharSelectDialog::use(const int selected)
-{
- if ((mCharacterEntries[selected] != nullptr)
- && (mCharacterEntries[selected]->getCharacter() != nullptr))
- {
- attemptCharacterSelect(selected);
- }
- else
- {
- CharCreateDialog *const charCreateDialog =
- CREATEWIDGETR(CharCreateDialog, this, selected);
- mCharServerHandler->setCharCreateDialog(charCreateDialog);
- }
-}
-
-void CharSelectDialog::keyPressed(KeyEvent &event)
-{
- const InputActionT actionId = event.getActionId();
- PRAGMA45(GCC diagnostic push)
- PRAGMA45(GCC diagnostic ignored "-Wswitch-enum")
- switch (actionId)
- {
- case InputAction::GUI_CANCEL:
- event.consume();
- action(ActionEvent(mSwitchLoginButton,
- mSwitchLoginButton->getActionEventId()));
- break;
-
- case InputAction::GUI_RIGHT:
- {
- event.consume();
- int idx = mCharacterView->getSelected();
- if (idx >= 0)
- {
- idx ++;
- if (idx == SLOTS_PER_ROW)
- break;
- mCharacterView->show(idx);
- updateState();
- }
- break;
- }
-
- case InputAction::GUI_LEFT:
- {
- event.consume();
- int idx = mCharacterView->getSelected();
- if (idx >= 0)
- {
- if ((idx == 0) || idx == SLOTS_PER_ROW)
- break;
- idx --;
- mCharacterView->show(idx);
- updateState();
- }
- break;
- }
-
- case InputAction::GUI_UP:
- {
- event.consume();
- int idx = mCharacterView->getSelected();
- if (idx >= 0)
- {
- if (idx < SLOTS_PER_ROW)
- break;
- idx -= SLOTS_PER_ROW;
- mCharacterView->show(idx);
- updateState();
- }
- break;
- }
-
- case InputAction::GUI_DOWN:
- {
- event.consume();
- int idx = mCharacterView->getSelected();
- if (idx >= 0)
- {
- if (idx >= SLOTS_PER_ROW)
- break;
- idx += SLOTS_PER_ROW;
- mCharacterView->show(idx);
- updateState();
- }
- break;
- }
-
- case InputAction::GUI_DELETE:
- {
- event.consume();
- const int idx = mCharacterView->getSelected();
- if (idx >= 0 && (mCharacterEntries[idx] != nullptr)
- && (mCharacterEntries[idx]->getCharacter() != nullptr))
- {
- CREATEWIDGET(CharDeleteConfirm, this, idx);
- }
- break;
- }
-
- case InputAction::GUI_SELECT:
- {
- event.consume();
- use(mCharacterView->getSelected());
- break;
- }
- default:
- break;
- }
- PRAGMA45(GCC diagnostic pop)
-}
-
-/**
- * Communicate character deletion to the server.
- */
-void CharSelectDialog::attemptCharacterDelete(const int index,
- const std::string &email)
-{
- if (mLocked)
- return;
-
- if (mCharacterEntries[index] != nullptr)
- {
- mCharServerHandler->deleteCharacter(
- mCharacterEntries[index]->getCharacter(),
- email);
- }
- lock();
-}
-
-void CharSelectDialog::askPasswordForDeletion(const int index)
-{
- mDeleteIndex = index;
- if (serverFeatures->haveEmailOnDelete())
- {
- CREATEWIDGETV(mDeleteDialog, TextDialog,
- // TRANSLATORS: char deletion question.
- _("Enter your email for deleting character"),
- // TRANSLATORS: email label.
- _("Enter email:"),
- this, false);
- }
- else
- {
- CREATEWIDGETV(mDeleteDialog, TextDialog,
- // TRANSLATORS: char deletion question.
- _("Enter password for deleting character"),
- // TRANSLATORS: email label.
- _("Enter password:"),
- this, true);
- }
- mDeleteDialog->setActionEventId("try delete character");
- mDeleteDialog->addActionListener(this);
-}
-
-/**
- * Communicate character selection to the server.
- */
-void CharSelectDialog::attemptCharacterSelect(const int index)
-{
- if (mLocked || (mCharacterEntries[index] == nullptr))
- return;
-
- setVisible(Visible_false);
- if (mCharServerHandler != nullptr)
- {
- mCharServerHandler->chooseCharacter(
- mCharacterEntries[index]->getCharacter());
- }
- lock();
-}
-
-void CharSelectDialog::setCharacters(const Net::Characters &characters)
-{
- // Reset previous characters
- FOR_EACH (STD_VECTOR<CharacterDisplay*>::const_iterator,
- iter, mCharacterEntries)
- {
- if (*iter != nullptr)
- (*iter)->setCharacter(nullptr);
- }
-
- FOR_EACH (Net::Characters::const_iterator, i, characters)
- setCharacter(*i);
- updateState();
-}
-
-void CharSelectDialog::setCharacter(Net::Character *const character)
-{
- if (character == nullptr)
- return;
- const int characterSlot = character->slot;
- if (characterSlot >= CAST_S32(mCharacterEntries.size()))
- {
- logger->log("Warning: slot out of range: %d", character->slot);
- return;
- }
-
- if (mCharacterEntries[characterSlot] != nullptr)
- mCharacterEntries[characterSlot]->setCharacter(character);
-}
-
-void CharSelectDialog::lock()
-{
- if (!mLocked)
- setLocked(true);
-}
-
-void CharSelectDialog::unlock()
-{
- setLocked(false);
-}
-
-void CharSelectDialog::setLocked(const bool locked)
-{
- mLocked = locked;
-
- if (mSwitchLoginButton != nullptr)
- mSwitchLoginButton->setEnabled(!locked);
- if (mChangePasswordButton != nullptr)
- mChangePasswordButton->setEnabled(!locked);
- mPlayButton->setEnabled(!locked);
- if (mDeleteButton != nullptr)
- mDeleteButton->setEnabled(!locked);
-
- for (size_t i = 0, sz = mCharacterEntries.size(); i < sz; ++i)
- {
- if (mCharacterEntries[i] != nullptr)
- mCharacterEntries[i]->setActive(!mLocked);
- }
-}
-
-bool CharSelectDialog::selectByName(const std::string &name,
- const SelectAction selAction)
-{
- if (mLocked)
- return false;
-
- for (size_t i = 0, sz = mCharacterEntries.size(); i < sz; ++i)
- {
- if (mCharacterEntries[i] != nullptr)
- {
- const Net::Character *const character
- = mCharacterEntries[i]->getCharacter();
- if (character != nullptr)
- {
- if (character->dummy != nullptr &&
- character->dummy->getName() == name)
- {
- mCharacterView->show(CAST_S32(i));
- updateState();
- if (selAction == Choose)
- attemptCharacterSelect(CAST_S32(i));
- return true;
- }
- }
- }
- }
-
- return false;
-}
-
-void CharSelectDialog::close()
-{
- client->setState(State::SWITCH_LOGIN);
- Window::close();
-}
-
-void CharSelectDialog::widgetResized(const Event &event)
-{
- Window::widgetResized(event);
- mCharacterView->resize();
-}
-
-void CharSelectDialog::updateState()
-{
- const int idx = mCharacterView->getSelected();
- if (idx == -1)
- {
- mPlayButton->setEnabled(false);
- return;
- }
- mPlayButton->setEnabled(true);
-
- if (mCharacterEntries[idx] != nullptr &&
- mCharacterEntries[idx]->getCharacter() != nullptr)
- {
- // TRANSLATORS: char select dialog. button.
- mPlayButton->setCaption(_("Play"));
-
- const LocalPlayer *const player = mCharacterEntries[
- idx]->getCharacter()->dummy;
- if ((player != nullptr) && (mRenameButton != nullptr))
- mRenameButton->setEnabled(player->getRename() ? true : false);
- }
- else
- {
- // TRANSLATORS: char select dialog. button.
- mPlayButton->setCaption(_("Create"));
- }
-}
-
-void CharSelectDialog::setName(const BeingId id, const std::string &newName)
-{
- for (unsigned int i = 0, fsz = CAST_U32(
- mCharacterEntries.size());
- i < fsz;
- ++i)
- {
- if (mCharacterEntries[i] == nullptr)
- continue;
- CharacterDisplay *const character = mCharacterEntries[i];
- if (character == nullptr)
- continue;
- LocalPlayer *const player = character->getCharacter()->dummy;
- if ((player != nullptr) && player->getId() == id)
- {
- player->setName(newName);
- character->update();
- return;
- }
- }
-}
diff --git a/src/gui/windows/charselectdialog.h b/src/gui/windows/charselectdialog.h
deleted file mode 100644
index 9cf56bfd6..000000000
--- a/src/gui/windows/charselectdialog.h
+++ /dev/null
@@ -1,136 +0,0 @@
-/*
- * The ManaPlus Client
- * Copyright (C) 2004-2009 The Mana World Development Team
- * Copyright (C) 2009-2010 The Mana Developers
- * Copyright (C) 2011-2017 The ManaPlus Developers
- *
- * This file is part of The ManaPlus Client.
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-#ifndef GUI_WINDOWS_CHARSELECTDIALOG_H
-#define GUI_WINDOWS_CHARSELECTDIALOG_H
-
-#include "enums/simpletypes/beingid.h"
-
-#include "gui/widgets/window.h"
-
-#include "net/characters.h"
-
-#include "listeners/actionlistener.h"
-#include "listeners/keylistener.h"
-
-class Button;
-class CharacterDisplay;
-class CharacterViewBase;
-class LoginData;
-class TextDialog;
-
-namespace Net
-{
- class CharServerHandler;
-} // namespace Net
-
-/**
- * Character selection dialog.
- *
- * \ingroup Interface
- */
-class CharSelectDialog final : public Window,
- public ActionListener,
- public KeyListener
-{
- public:
- friend class CharDeleteConfirm;
- friend class Net::CharServerHandler;
-
- /**
- * Constructor.
- */
- explicit CharSelectDialog(LoginData &data);
-
- A_DELETE_COPY(CharSelectDialog)
-
- ~CharSelectDialog();
-
- void action(const ActionEvent &event) override final;
-
- void keyPressed(KeyEvent &event) override final;
-
- enum SelectAction
- {
- Focus = 0,
- Choose
- };
-
- /**
- * Attempt to select the character with the given name. Returns whether
- * a character with the given name was found.
- *
- * \param action determines what to do when a character with the given
- * name was found (just focus or also try to choose this
- * character).
- */
- bool selectByName(const std::string &name,
- const SelectAction action = Focus);
-
- void askPasswordForDeletion(const int index);
-
- void close() override final;
-
- void widgetResized(const Event &event) override final;
-
- void updateState();
-
- void postInit() override final;
-
- void setName(const BeingId id, const std::string &newName);
-
- private:
- void attemptCharacterDelete(const int index,
- const std::string &email);
-
- void attemptCharacterSelect(const int index);
-
- void setCharacters(const Net::Characters &characters);
-
- void setCharacter(Net::Character *const character);
-
- void use(const int selected);
-
- void lock();
- void unlock();
- void setLocked(const bool locked);
-
- LoginData *mLoginData A_NONNULLPOINTER;
-
- Button *mSwitchLoginButton A_NONNULLPOINTER;
- Button *mChangePasswordButton A_NONNULLPOINTER;
- Button *mPlayButton A_NONNULLPOINTER;
- Button *mInfoButton A_NONNULLPOINTER;
- Button *mDeleteButton A_NONNULLPOINTER;
- Button *mRenameButton;
- CharacterViewBase *mCharacterView;
-
- STD_VECTOR<CharacterDisplay*> mCharacterEntries;
-
- Net::CharServerHandler *mCharServerHandler;
- TextDialog *mDeleteDialog;
- int mDeleteIndex;
- bool mLocked;
- bool mSmallScreen;
-};
-
-#endif // GUI_WINDOWS_CHARSELECTDIALOG_H
diff --git a/src/gui/windows/chatwindow.cpp b/src/gui/windows/chatwindow.cpp
deleted file mode 100644
index aa899202d..000000000
--- a/src/gui/windows/chatwindow.cpp
+++ /dev/null
@@ -1,2181 +0,0 @@
-/*
- * The ManaPlus Client
- * Copyright (C) 2004-2009 The Mana World Development Team
- * Copyright (C) 2009-2010 The Mana Developers
- * Copyright (C) 2011-2017 The ManaPlus Developers
- *
- * This file is part of The ManaPlus Client.
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-#include "gui/windows/chatwindow.h"
-
-#include "actormanager.h"
-#include "game.h"
-#include "guild.h"
-#include "party.h"
-#include "settings.h"
-#include "spellmanager.h"
-
-#include "being/localplayer.h"
-#include "being/playerinfo.h"
-#include "being/playerrelations.h"
-
-#include "const/gui/chat.h"
-
-#include "fs/virtfs/tools.h"
-
-#include "input/inputmanager.h"
-
-#include "gui/focushandler.h"
-#include "gui/gui.h"
-#include "gui/skin.h"
-#include "gui/viewport.h"
-
-#include "gui/models/colorlistmodel.h"
-
-#include "gui/popups/popupmenu.h"
-
-#include "gui/windows/setupwindow.h"
-#include "gui/windows/whoisonline.h"
-
-#include "gui/widgets/button.h"
-#include "gui/widgets/chatinput.h"
-#include "gui/widgets/createwidget.h"
-#include "gui/widgets/dropdown.h"
-#include "gui/widgets/itemlinkhandler.h"
-#include "gui/widgets/scrollarea.h"
-#include "gui/widgets/tabbedarea.h"
-
-#include "gui/widgets/tabs/chat/battletab.h"
-#include "gui/widgets/tabs/chat/channeltab.h"
-#include "gui/widgets/tabs/chat/gmtab.h"
-#include "gui/widgets/tabs/chat/langtab.h"
-#include "gui/widgets/tabs/chat/tradetab.h"
-#include "gui/widgets/tabs/chat/whispertab.h"
-
-#include "render/opengl/opengldebug.h"
-
-#include "resources/db/textdb.h"
-
-#include "net/chathandler.h"
-#include "net/net.h"
-
-#include "utils/copynpaste.h"
-#include "utils/delete2.h"
-#include "utils/foreach.h"
-
-#include "utils/translation/podict.h"
-
-#include <sys/stat.h>
-
-#include <sstream>
-
-#include "debug.h"
-
-ChatWindow *chatWindow = nullptr;
-
-static const char *const ACTION_COLOR_PICKER = "color picker";
-
-ChatWindow::ChatWindow(const std::string &name) :
- // TRANSLATORS: chat window name
- Window(_("Chat"), Modal_false, nullptr, "chat.xml"),
- ActionListener(),
- KeyListener(),
- AttributeListener(),
- mItemLinkHandler(new ItemLinkHandler),
- mChatTabs(CREATEWIDGETR(TabbedArea, this)),
- mChatInput(new ChatInput(this)),
- mRainbowColor(0U),
- mWhispers(),
- mChannels(),
- mHistory(),
- mCurHist(),
- mCommands(),
- mCustomWords(),
- mTradeFilter(),
- mColorListModel(new ColorListModel),
- mColorPicker(new DropDown(this, mColorListModel)),
- mChatButton(new Button(this, ":)", "openemote", this)),
- mAwayLog(),
- mHighlights(),
- mGlobalsFilter(),
- mChatColor(config.getIntValue("chatColor")),
- mEmoteButtonSpacing(mSkin != nullptr ?
- mSkin->getOption("emoteButtonSpacing", 2) : 2),
- mEmoteButtonY(mSkin != nullptr ?
- mSkin->getOption("emoteButtonY", -2) : -2),
- mChatHistoryIndex(0),
- mReturnToggles(config.getBoolValue("ReturnToggles")),
- mGMLoaded(false),
- mHaveMouse(false),
- mAutoHide(config.getBoolValue("autohideChat")),
- mShowBattleEvents(config.getBoolValue("showBattleEvents")),
- mShowAllLang(serverConfig.getValue("showAllLang", 0) != 0),
- mEnableTradeFilter(config.getBoolValue("enableTradeFilter")),
- mTmpVisible(false)
-{
- setWindowName(name);
-
- if (setupWindow != nullptr)
- setupWindow->registerWindowForReset(this);
-
- setShowTitle(false);
- setResizable(true);
- setDefaultVisible(true);
- setSaveVisible(true);
- setStickyButtonLock(true);
-
- int w = 600;
-#ifdef ANDROID
- if (mainGraphics->getWidth() < 710)
- w = mainGraphics->getWidth() - 110;
- if (w < 100)
- w = 100;
- if (mainGraphics->getHeight() < 480)
- setDefaultSize(w, 90, ImagePosition::UPPER_LEFT, -110, -35);
- else
- setDefaultSize(w, 123, ImagePosition::UPPER_LEFT, -110, -35);
-#else // ANDROID
-
- if (mainGraphics->getWidth() < 600)
- w = mainGraphics->getWidth() - 10;
- if (w < 100)
- w = 100;
- setDefaultSize(w, 123, ImagePosition::LOWER_LEFT);
-#endif // ANDROID
-
- setMinWidth(150);
- setMinHeight(90);
-
- setTitleBarHeight(getPadding() + getTitlePadding());
-
- if (emoteWindow != nullptr)
- emoteWindow->addListeners(this);
-
- mChatButton->adjustSize();
-
- mChatTabs->enableScrollButtons(true);
- mChatTabs->setFollowDownScroll(true);
- mChatTabs->setResizeHeight(false);
-
- mChatInput->setActionEventId("chatinput");
- mChatInput->addActionListener(this);
- mChatInput->setAllowSpecialActions(false);
-
- mColorPicker->setActionEventId(ACTION_COLOR_PICKER);
- mColorPicker->addActionListener(this);
- mColorPicker->setSelected(mChatColor);
-
- mItemLinkHandler->setAllowCommands(false);
-
- loadWindowState();
-
- mColorPicker->setPosition(this->getWidth() - mColorPicker->getWidth()
- - 2 * mPadding - 8 - 16, mPadding);
-
- // Add key listener to chat input to be able to respond to up/down
- mChatInput->addKeyListener(this);
- mCurHist = mHistory.end();
- mColorPicker->setVisible(fromBool(config.getBoolValue(
- "showChatColorsList"), Visible));
- updateTabsMargin();
-
- fillCommands();
- if ((localPlayer != nullptr) && localPlayer->isGM())
- loadGMCommands();
- initTradeFilter();
- loadCustomList();
- parseHighlights();
- parseGlobalsFilter();
-
- config.addListener("autohideChat", this);
- config.addListener("showBattleEvents", this);
- config.addListener("globalsFilter", this);
- config.addListener("enableTradeFilter", this);
-
- enableVisibleSound(true);
-}
-
-ChatWindow::~ChatWindow()
-{
- config.removeListeners(this);
- CHECKLISTENERS
- saveState();
- config.setValue("ReturnToggles", mReturnToggles);
- removeAllWhispers();
- removeAllChannels();
- delete2(mItemLinkHandler);
- delete2(mColorPicker);
- delete2(mColorListModel);
-}
-
-void ChatWindow::postInit()
-{
- Window::postInit();
- add(mChatTabs);
- add(mChatInput);
- add(mColorPicker);
- add(mChatButton);
- updateVisibility();
-}
-
-void ChatWindow::loadCommandsFile(const std::string &name)
-{
- StringVect list;
- VirtFs::loadTextFile(name, list);
- StringVectCIter it = list.begin();
- const StringVectCIter it_end = list.end();
-
- while (it != it_end)
- {
- const std::string str = *it;
- if (!str.empty())
- mCommands.push_back(str);
- ++ it;
- }
-}
-
-void ChatWindow::fillCommands()
-{
- loadCommandsFile("chatcommands.txt");
- inputManager.addChatCommands(mCommands);
-}
-
-void ChatWindow::loadGMCommands()
-{
- if (mGMLoaded)
- return;
-
- loadCommandsFile("gmcommands.txt");
- mGMLoaded = true;
-}
-
-void ChatWindow::updateTabsMargin()
-{
- if (mColorPicker->mVisible == Visible_true)
- mChatTabs->setRightMargin(mColorPicker->getWidth() + 16 + 8);
- else
- mChatTabs->setRightMargin(8);
-}
-
-void ChatWindow::adjustTabSize()
-{
- const Rect area = getChildrenArea();
-
- const int aw = area.width;
- const int ah = area.height;
- const int frame = mChatInput->getFrameSize();
- const int inputHeight = mChatInput->getHeight();
- const bool showEmotes = config.getBoolValue("showEmotesButton");
- int maxHeight = inputHeight;
- if (showEmotes)
- {
- const int buttonHeight = mChatButton->getHeight();
- if (buttonHeight > maxHeight)
- maxHeight = buttonHeight;
- }
- const int frame2 = 2 * frame;
- const int awFrame2 = aw - frame2;
- int y = ah - maxHeight - frame;
- mChatInput->setPosition(frame, y);
- mChatTabs->setWidth(awFrame2);
- const int height = ah - frame2 - (maxHeight + frame2);
- if (mChatInput->mVisible == Visible_true ||
- !config.getBoolValue("hideChatInput"))
- {
- mChatTabs->setHeight(height);
- }
- else
- {
- mChatTabs->setHeight(height + maxHeight);
- }
- updateTabsMargin();
-
- if (showEmotes)
- {
- const int chatButtonSize = mChatButton->getWidth();
- int w = awFrame2 - chatButtonSize;
- const int x = aw - frame - chatButtonSize;
- w -= mEmoteButtonSpacing;
- y += mEmoteButtonY;
- mChatInput->setWidth(w);
- mChatButton->setVisible(mChatInput->mVisible);
- mChatButton->setPosition(x, y);
- }
- else
- {
- mChatInput->setWidth(awFrame2);
- mChatButton->setVisible(Visible_false);
- }
-
- const ChatTab *const tab = getFocused();
- if (tab != nullptr)
- {
- Widget *const content = tab->mScrollArea;
- if (content != nullptr)
- {
- const int contentFrame2 = 2 * content->getFrameSize();
- content->setSize(mChatTabs->getWidth() - contentFrame2,
- mChatTabs->getContainerHeight() - contentFrame2);
- content->logic();
- }
- }
-
- mColorPicker->setPosition(this->getWidth() - mColorPicker->getWidth()
- - 2 * mPadding - 8 - 16, mPadding);
-
- mChatTabs->adjustSize();
-}
-
-void ChatWindow::widgetResized(const Event &event)
-{
- Window::widgetResized(event);
-
- adjustTabSize();
-}
-
-ChatTab *ChatWindow::getFocused() const
-{
- return static_cast<ChatTab*>(mChatTabs->getSelectedTab());
-}
-
-void ChatWindow::clearTab(ChatTab *const tab)
-{
- if (tab != nullptr)
- tab->clearText();
-}
-
-void ChatWindow::clearTab() const
-{
- clearTab(getFocused());
-}
-
-void ChatWindow::prevTab()
-{
- if (mChatTabs == nullptr)
- return;
-
- int tab = mChatTabs->getSelectedTabIndex();
-
- if (tab <= 0)
- tab = mChatTabs->getNumberOfTabs();
- tab--;
-
- mChatTabs->setSelectedTabByIndex(tab);
-}
-
-void ChatWindow::nextTab()
-{
- if (mChatTabs == nullptr)
- return;
-
- int tab = mChatTabs->getSelectedTabIndex();
-
- tab++;
- if (tab == mChatTabs->getNumberOfTabs())
- tab = 0;
-
- mChatTabs->setSelectedTabByIndex(tab);
-}
-
-void ChatWindow::selectTabByType(const ChatTabTypeT &type)
-{
- if (mChatTabs == nullptr)
- return;
-
- int sz = mChatTabs->getNumberOfTabs();
- for (int f = 0; f < sz; f ++)
- {
- ChatTab *const tab = dynamic_cast<ChatTab*>(
- mChatTabs->getTabByIndex(f));
- if ((tab != nullptr) && tab->getType() == type)
- {
- mChatTabs->setSelectedTab(tab);
- break;
- }
- }
-}
-
-void ChatWindow::closeTab() const
-{
- if (mChatTabs == nullptr)
- return;
-
- ChatTab *const tab = dynamic_cast<ChatTab*>(mChatTabs->getTabByIndex(
- mChatTabs->getSelectedTabIndex()));
- if (tab == nullptr)
- return;
- const ChatTabTypeT &type = tab->getType();
- if (type == ChatTabType::WHISPER || type == ChatTabType::CHANNEL)
- tab->handleCommand("close", "");
-}
-
-void ChatWindow::defaultTab()
-{
- if (mChatTabs != nullptr)
- mChatTabs->setSelectedTabByIndex(CAST_U32(0));
-}
-
-void ChatWindow::action(const ActionEvent &event)
-{
- const std::string &eventId = event.getId();
- if (eventId == "chatinput")
- {
- std::string message = mChatInput->getText();
-
- if (!message.empty())
- {
- // If message different from previous, put it in the history
- if (mHistory.empty() || message != mHistory.back())
- mHistory.push_back(message);
-
- // Reset history iterator
- mCurHist = mHistory.end();
-
- // Send the message to the server
- chatInput(addColors(message));
-
- // Clear the text from the chat input
- mChatInput->setText("");
- }
-
- if (message.empty() || !mReturnToggles)
- {
- // Remove focus and hide input
- mChatInput->unprotectFocus();
- if (mFocusHandler != nullptr)
- mFocusHandler->focusNone();
-
- // If the chatWindow is shown up because you want to send a message
- // It should hide now
- if (mTmpVisible)
- setVisible(Visible_false);
- }
- }
- else if (eventId == "emote")
- {
- if (emoteWindow != nullptr)
- {
- const std::string str = emoteWindow->getSelectedEmote();
- if (!str.empty())
- {
- addInputText(str, false);
- emoteWindow->clearEmote();
- }
- }
- }
- else if (eventId == "openemote")
- {
- if (emoteWindow != nullptr)
- {
- if (emoteWindow->mVisible == Visible_true)
- emoteWindow->hide();
- else
- emoteWindow->show();
- }
- }
- else if (eventId == "color")
- {
- if (emoteWindow != nullptr)
- {
- const std::string str = emoteWindow->getSelectedColor();
- if (!str.empty())
- {
- addInputText(str, false);
- emoteWindow->clearColor();
- }
- }
- }
- else if (eventId == "font")
- {
- if (emoteWindow != nullptr)
- {
- const std::string str = emoteWindow->getSelectedFont();
- if (!str.empty())
- {
- addInputText(str, false);
- emoteWindow->clearFont();
- }
- }
- }
- else if (eventId == "text")
- {
- if ((emoteWindow != nullptr) && (reverseDictionary != nullptr))
- {
- const int idx = emoteWindow->getSelectedTextIndex();
- if (idx >= 0)
- {
- const std::string str = TextDb::getByIndex(idx);
- const std::string enStr = reverseDictionary->getStr(str);
- addInputText(enStr, false);
- }
- emoteWindow->clearText();
- }
- }
- else if (eventId == ACTION_COLOR_PICKER)
- {
- if (mColorPicker != nullptr)
- {
- mChatColor = mColorPicker->getSelected();
- config.setValue("chatColor", mChatColor);
- }
- }
-
- if (mColorPicker != nullptr)
- {
- const Visible vis = fromBool(config.getBoolValue(
- "showChatColorsList"), Visible);
- if (mColorPicker->mVisible != vis)
- mColorPicker->setVisible(vis);
- }
-}
-
-bool ChatWindow::requestChatFocus()
-{
- // Make sure chatWindow is visible
- if (!isWindowVisible())
- {
- setVisible(Visible_true);
-
- /*
- * This is used to hide chatWindow after sending the message. There is
- * a trick here, because setVisible will set mTmpVisible to false, you
- * have to put this sentence *after* setVisible, not before it
- */
- mTmpVisible = true;
- }
-
- // Don't do anything else if the input is already visible and has focus
- if (mChatInput->isVisible() && mChatInput->isFocused())
- return false;
-
- // Give focus to the chat input
- mChatInput->processVisible(Visible_true);
- unHideWindow();
- mChatInput->requestFocus();
- return true;
-}
-
-bool ChatWindow::isInputFocused() const
-{
- return mChatInput->isFocused();
-}
-
-void ChatWindow::removeTab(ChatTab *const tab)
-{
- mChatTabs->removeTab(tab);
-}
-
-void ChatWindow::addTab(ChatTab *const tab)
-{
- if (tab == nullptr)
- return;
-
- mChatTabs->addTab(tab, tab->mScrollArea);
- logic();
-}
-
-void ChatWindow::removeWhisper(const std::string &nick)
-{
- std::string tempNick = nick;
- toLower(tempNick);
- mWhispers.erase(tempNick);
-}
-
-void ChatWindow::removeChannel(const std::string &name)
-{
- std::string tempName = name;
- toLower(tempName);
- mChannels.erase(tempName);
- chatHandler->partChannel(name);
-}
-
-void ChatWindow::removeAllWhispers()
-{
- std::list<ChatTab*> tabs;
-
- FOR_EACH (TabMap::iterator, iter, mWhispers)
- tabs.push_back(iter->second);
-
- for (std::list<ChatTab*>::iterator it = tabs.begin();
- it != tabs.end(); ++it)
- {
- delete *it;
- }
-
- mWhispers.clear();
-}
-
-void ChatWindow::removeAllChannels()
-{
- std::list<ChatTab*> tabs;
-
- FOR_EACH (ChannelMap::iterator, iter, mChannels)
- tabs.push_back(iter->second);
-
- for (std::list<ChatTab*>::iterator it = tabs.begin();
- it != tabs.end(); ++it)
- {
- delete *it;
- }
-
- mChannels.clear();
-}
-
-void ChatWindow::ignoreAllWhispers()
-{
- for (TabMap::iterator iter = mWhispers.begin();
- iter != mWhispers.end();
- ++ iter)
- {
- WhisperTab *const tab = iter->second;
- if (tab != nullptr)
- {
- if (playerRelations.getRelation(tab->getNick())
- != Relation::IGNORED)
- {
- playerRelations.setRelation(tab->getNick(),
- Relation::IGNORED);
- }
- tab->handleCommand("close", "");
- }
- }
-}
-
-void ChatWindow::chatInput(const std::string &message) const
-{
- ChatTab *tab = nullptr;
- std::string msg = message;
- trim(msg);
-
- if (config.getBoolValue("allowCommandsInChatTabs")
- && msg.length() > 1
- && ((msg.at(0) == '#' && msg.at(1) != '#') || msg.at(0) == '@')
- && (localChatTab != nullptr))
- {
- tab = localChatTab;
- }
- else
- {
- tab = getFocused();
- if (tab == nullptr)
- tab = localChatTab;
- }
- if (tab != nullptr)
- tab->chatInput(msg);
- Game *const game = Game::instance();
- if (game != nullptr)
- game->setValidSpeed();
-}
-
-void ChatWindow::localChatInput(const std::string &msg) const
-{
- if (localChatTab != nullptr)
- localChatTab->chatInput(msg);
- else
- chatInput(msg);
-}
-
-void ChatWindow::doPresent() const
-{
- if (actorManager == nullptr)
- return;
-
- const ActorSprites &actors = actorManager->getAll();
- std::string response;
- int playercount = 0;
-
- FOR_EACH (ActorSpritesIterator, it, actors)
- {
- if ((*it)->getType() == ActorType::Player)
- {
- if (!response.empty())
- response.append(", ");
- response.append(static_cast<Being*>(*it)->getName());
- playercount ++;
- }
- }
-
- ChatTab *const tab = getFocused();
- if (tab != nullptr)
- {
- const std::string log = strprintf(
- // TRANSLATORS: chat message
- _("Present: %s; %d players are present."),
- response.c_str(), playercount);
- tab->chatLog(log, ChatMsgType::BY_SERVER);
- }
-}
-
-void ChatWindow::scroll(const int amount) const
-{
- if (!isWindowVisible())
- return;
-
- ChatTab *const tab = getFocused();
- if (tab != nullptr)
- tab->scroll(amount);
-}
-
-void ChatWindow::mousePressed(MouseEvent &event)
-{
- if (event.isConsumed())
- return;
-
- if (event.getButton() == MouseButton::RIGHT)
- {
- if (popupMenu != nullptr)
- {
- ChatTab *const cTab = dynamic_cast<ChatTab*>(
- mChatTabs->getSelectedTab());
- if (cTab != nullptr)
- {
- event.consume();
- if (inputManager.isActionActive(InputAction::CHAT_MOD))
- {
- inputManager.executeChatCommand(
- InputAction::CLOSE_CHAT_TAB,
- std::string(), cTab);
- }
- else
- {
- popupMenu->showChatPopup(viewport->mMouseX,
- viewport->mMouseY,
- cTab);
- }
- }
- }
- }
-
- Window::mousePressed(event);
-
- if (event.isConsumed())
- return;
-
- if (event.getButton() == MouseButton::LEFT)
- {
- const int clicks = event.getClickCount();
- if (clicks == 2)
- {
- toggleChatFocus();
- if (gui != nullptr)
- gui->resetClickCount();
- }
- else if (clicks == 1)
- {
- const ChatTab *const tab = getFocused();
- if (tab != nullptr)
- mMoved = !isResizeAllowed(event);
- }
- }
-
- mDragOffsetX = event.getX();
- mDragOffsetY = event.getY();
-}
-
-void ChatWindow::mouseDragged(MouseEvent &event)
-{
- Window::mouseDragged(event);
-
- if (event.isConsumed())
- return;
-
- if (canMove() && isMovable() && mMoved)
- {
- int newX = std::max(0, getX() + event.getX() - mDragOffsetX);
- int newY = std::max(0, getY() + event.getY() - mDragOffsetY);
- newX = std::min(mainGraphics->mWidth - getWidth(), newX);
- newY = std::min(mainGraphics->mHeight - getHeight(), newY);
- setPosition(newX, newY);
- }
-}
-
-#define ifKey(key, str) \
- else if (actionId == key) \
- { \
- temp = str; \
- }
-
-void ChatWindow::keyPressed(KeyEvent &event)
-{
- const InputActionT actionId = event.getActionId();
- std::string temp;
- if (actionId == InputAction::GUI_DOWN)
- {
- if (mCurHist != mHistory.end())
- {
- // Move forward through the history
- const HistoryIterator prevHist = mCurHist++;
- addCurrentToHistory();
-
- if (mCurHist != mHistory.end())
- {
- mChatInput->setText(*mCurHist);
- mChatInput->setCaretPosition(CAST_U32(
- mChatInput->getText().length()));
- }
- else
- {
- mChatInput->setText("");
- mCurHist = prevHist;
- }
- }
- else if (!mChatInput->getText().empty())
- {
- if (addCurrentToHistory())
- mCurHist = mHistory.end();
- mChatInput->setText("");
- }
- }
- else if (actionId == InputAction::GUI_UP &&
- mCurHist != mHistory.begin() &&
- !mHistory.empty())
- {
- // Move backward through the history
- --mCurHist;
- addCurrentToHistory();
- mChatInput->setText(*mCurHist);
- mChatInput->setCaretPosition(CAST_U32(
- mChatInput->getText().length()));
- }
- else if (actionId == InputAction::GUI_INSERT &&
- !mChatInput->getText().empty())
- {
- const std::string str = mChatInput->getText();
- // Add the current message to the history and clear the text
- if (mHistory.empty() || str != mHistory.back())
- mHistory.push_back(str);
- mCurHist = mHistory.end();
- mChatInput->setText(std::string());
- }
- else if (actionId == InputAction::GUI_TAB &&
- !mChatInput->getText().empty())
- {
- autoComplete();
- return;
- }
- else if (actionId == InputAction::GUI_CANCEL &&
- mChatInput->mVisible == Visible_true)
- {
- mChatInput->processVisible(Visible_false);
- }
- else if (actionId == InputAction::CHAT_PREV_HISTORY &&
- mChatInput->mVisible == Visible_true)
- {
- const ChatTab *const tab = getFocused();
- if ((tab != nullptr) && tab->hasRows())
- {
- if (mChatHistoryIndex == 0u)
- {
- mChatHistoryIndex = CAST_U32(
- tab->getRows().size());
-
- mChatInput->setText("");
- mChatInput->setCaretPosition(0);
- return;
- }
-
- mChatHistoryIndex --;
-
- unsigned int f = 0;
- const std::list<std::string> &rows = tab->getRows();
- for (std::list<std::string>::const_iterator it = rows.begin(),
- it_end = rows.end(); it != it_end; ++ it, f ++)
- {
- if (f == mChatHistoryIndex)
- mChatInput->setText(*it);
- }
- mChatInput->setCaretPosition(CAST_U32(
- mChatInput->getText().length()));
- }
- }
- else if (actionId == InputAction::CHAT_NEXT_HISTORY &&
- mChatInput->mVisible == Visible_true)
- {
- const ChatTab *const tab = getFocused();
- if ((tab != nullptr) && tab->hasRows())
- {
- const std::list<std::string> &rows = tab->getRows();
- const size_t &tabSize = rows.size();
- if (CAST_SIZE(mChatHistoryIndex) + 1 < tabSize)
- {
- mChatHistoryIndex ++;
- }
- else if (CAST_SIZE(mChatHistoryIndex) < tabSize)
- {
- mChatHistoryIndex ++;
- mChatInput->setText("");
- mChatInput->setCaretPosition(0);
- return;
- }
- else
- {
- mChatHistoryIndex = 0;
- }
-
- unsigned int f = 0;
- for (std::list<std::string>::const_iterator
- it = rows.begin(), it_end = rows.end();
- it != it_end; ++it, f++)
- {
- if (f == mChatHistoryIndex)
- mChatInput->setText(*it);
- }
- mChatInput->setCaretPosition(CAST_U32(
- mChatInput->getText().length()));
- }
- }
- else if (actionId == InputAction::GUI_F1)
- {
- if (emoteWindow != nullptr)
- {
- if (emoteWindow->mVisible == Visible_true)
- emoteWindow->hide();
- else
- emoteWindow->show();
- }
- }
- ifKey(InputAction::GUI_F2, "\u2318")
- ifKey(InputAction::GUI_F3, "\u263A")
- ifKey(InputAction::GUI_F4, "\u2665")
- ifKey(InputAction::GUI_F5, "\u266A")
- ifKey(InputAction::GUI_F6, "\u266B")
- ifKey(InputAction::GUI_F7, "\u26A0")
- ifKey(InputAction::GUI_F8, "\u2622")
- ifKey(InputAction::GUI_F9, "\u262E")
- ifKey(InputAction::GUI_F10, "\u2605")
- ifKey(InputAction::GUI_F11, "\u2618")
- ifKey(InputAction::GUI_F12, "\u2592")
-
- if (inputManager.isActionActive(InputAction::GUI_CTRL))
- {
- if (actionId == InputAction::GUI_B)
- {
- std::string inputText = mChatInput->getTextBeforeCaret();
- toLower(inputText);
- const size_t idx = inputText.rfind("##b");
- if (idx == std::string::npos
- || mChatInput->getTextBeforeCaret().substr(idx, 3) == "##b")
- {
- temp = "##B";
- }
- else
- {
- temp = "##b";
- }
- }
- }
-
- if (!temp.empty())
- addInputText(temp, false);
-}
-
-#undef ifKey
-
-bool ChatWindow::addCurrentToHistory()
-{
- const std::string &str = mChatInput->getText();
- if (str.empty())
- return false;
- FOR_EACH (HistoryIterator, it, mHistory)
- {
- if (*it == str)
- return false;
- }
- mHistory.push_back(str);
- return true;
-}
-
-void ChatWindow::attributeChanged(const AttributesT id,
- const int64_t oldVal,
- const int64_t newVal)
-{
- if (!mShowBattleEvents)
- return;
- PRAGMA45(GCC diagnostic push)
- PRAGMA45(GCC diagnostic ignored "-Wswitch-enum")
- switch (id)
- {
- case Attributes::PLAYER_EXP:
- {
- if (oldVal > newVal)
- break;
- const int64_t change = newVal - oldVal;
- if (change != 0)
- {
- battleChatLog(std::string("+").append(toString(
- CAST_U64(change))).append(" xp"),
- ChatMsgType::BY_SERVER);
- }
- break;
- }
- case Attributes::PLAYER_BASE_LEVEL:
- battleChatLog(std::string(
- "Level: ").append(toString(CAST_S32(
- newVal))),
- ChatMsgType::BY_SERVER);
- break;
- case Attributes::PLAYER_JOB_EXP:
- {
- if (!config.getBoolValue("showJobExp"))
- return;
- if (oldVal > newVal ||
- PlayerInfo::getAttribute(
- Attributes::PLAYER_JOB_EXP_NEEDED) == 0)
- {
- return;
- }
- const int64_t change = newVal - oldVal;
- if (change != 0)
- {
- battleChatLog(std::string("+").append(toString(CAST_U64(
- change))).append(" job"),
- ChatMsgType::BY_SERVER);
- }
- break;
- }
- default:
- break;
- };
- PRAGMA45(GCC diagnostic pop)
-}
-
-void ChatWindow::addInputText(const std::string &text, const bool space)
-{
- const int caretPos = mChatInput->getCaretPosition();
- const std::string &inputText = mChatInput->getText();
-
- std::ostringstream ss;
- ss << inputText.substr(0, caretPos) << text;
- if (space)
- ss << " ";
-
- ss << inputText.substr(caretPos);
- mChatInput->setText(ss.str());
- mChatInput->setCaretPosition(caretPos + CAST_S32(
- text.length()) + CAST_S32(space));
- requestChatFocus();
-}
-
-void ChatWindow::addItemText(const std::string &item)
-{
- std::ostringstream text;
- text << "[" << item << "]";
- addInputText(text.str());
-}
-
-void ChatWindow::setVisible(Visible visible)
-{
- Window::setVisible(visible);
-
- /*
- * For whatever reason, if setVisible is called, the mTmpVisible effect
- * should be disabled.
- */
- mTmpVisible = false;
-}
-
-void ChatWindow::addWhisper(const std::string &restrict nick,
- const std::string &restrict mes,
- const ChatMsgTypeT own)
-{
- if (mes.empty() || (localPlayer == nullptr))
- return;
-
- std::string playerName = localPlayer->getName();
- std::string tempNick = nick;
-
- toLower(playerName);
- toLower(tempNick);
-
- if (tempNick == playerName)
- return;
-
- WhisperTab *tab = nullptr;
- const TabMap::const_iterator i = mWhispers.find(tempNick);
-
- if (i != mWhispers.end())
- {
- tab = i->second;
- }
- else if (config.getBoolValue("whispertab"))
- {
- tab = addWhisperTab(nick, nick);
- if (tab != nullptr)
- saveState();
- }
-
- if (tab != nullptr)
- {
- if (own == ChatMsgType::BY_PLAYER)
- {
- tab->chatInput(mes);
- }
- else if (own == ChatMsgType::BY_SERVER)
- {
- tab->chatLog(mes, ChatMsgType::BY_SERVER);
- }
- else
- {
- if (tab->getRemoveNames())
- {
- std::string msg = mes;
- const size_t idx = mes.find(':');
- if (idx != std::string::npos && idx > 0)
- {
- std::string nick2 = msg.substr(0, idx);
- msg = msg.substr(idx + 1);
- nick2 = removeColors(nick2);
- nick2 = trim(nick2);
- if (config.getBoolValue("removeColors"))
- msg = removeColors(msg);
- msg = trim(msg);
- tab->chatLog(nick2, msg);
- }
- else
- {
- if (config.getBoolValue("removeColors"))
- msg = removeColors(msg);
- tab->chatLog(msg, ChatMsgType::BY_SERVER);
- }
- }
- else
- {
- tab->chatLog(nick, mes);
- }
- localPlayer->afkRespond(tab, nick);
- }
- }
- else if (localChatTab != nullptr)
- {
- if (own == ChatMsgType::BY_PLAYER)
- {
- chatHandler->privateMessage(nick, mes);
-
- // TRANSLATORS: chat message
- localChatTab->chatLog(strprintf(_("Whispering to %s: %s"),
- nick.c_str(), mes.c_str()),
- ChatMsgType::BY_PLAYER);
- }
- else
- {
- localChatTab->chatLog(std::string(nick).append(
- " : ").append(mes),
- ChatMsgType::ACT_WHISPER,
- IgnoreRecord_false);
- if (localPlayer != nullptr)
- localPlayer->afkRespond(nullptr, nick);
- }
- }
-}
-
-WhisperTab *ChatWindow::addWhisperTab(const std::string &caption,
- const std::string &nick,
- const bool switchTo)
-{
- if (localPlayer == nullptr)
- return nullptr;
-
- std::string playerName = localPlayer->getName();
- std::string tempNick = nick;
-
- toLower(playerName);
- toLower(tempNick);
-
- const TabMap::const_iterator i = mWhispers.find(tempNick);
- WhisperTab *ret = nullptr;
-
- if (tempNick == playerName)
- return nullptr;
-
- if (i != mWhispers.end())
- {
- ret = i->second;
- }
- else
- {
- ret = new WhisperTab(this, caption, nick);
- if ((gui != nullptr) && !playerRelations.isGoodName(nick))
- ret->setLabelFont(gui->getSecureFont());
- mWhispers[tempNick] = ret;
- if (config.getBoolValue("showChatHistory"))
- ret->loadFromLogFile(nick);
- }
-
- if (switchTo)
- mChatTabs->setSelectedTab(ret);
-
- return ret;
-}
-
-WhisperTab *ChatWindow::getWhisperTab(const std::string &nick) const
-{
- if (localPlayer == nullptr)
- return nullptr;
-
- std::string playerName = localPlayer->getName();
- std::string tempNick = nick;
-
- toLower(playerName);
- toLower(tempNick);
-
- const TabMap::const_iterator i = mWhispers.find(tempNick);
- WhisperTab *ret = nullptr;
-
- if (tempNick == playerName)
- return nullptr;
-
- if (i != mWhispers.end())
- ret = i->second;
-
- return ret;
-}
-
-ChatTab *ChatWindow::addSpecialChannelTab(const std::string &name,
- const bool switchTo)
-{
- ChatTab *ret = nullptr;
- if (name == TRADE_CHANNEL)
- {
- if (tradeChatTab == nullptr)
- {
- tradeChatTab = new TradeTab(chatWindow);
- tradeChatTab->setAllowHighlight(false);
- chatHandler->joinChannel(tradeChatTab->getChannelName());
- }
- ret = tradeChatTab;
- }
- else if (name == GM_CHANNEL)
- {
- if (gmChatTab == nullptr)
- {
- gmChatTab = new GmTab(chatWindow);
- chatHandler->joinChannel(gmChatTab->getChannelName());
- }
- ret = gmChatTab;
- }
- if (switchTo)
- mChatTabs->setSelectedTab(ret);
-
- return ret;
-}
-
-ChatTab *ChatWindow::addChannelTab(const std::string &name,
- const bool switchTo)
-{
- std::string tempName = name;
- toLower(tempName);
-
- ChatTab *const tab = addSpecialChannelTab(name, switchTo);
- if (tab != nullptr)
- return tab;
-
- const ChannelMap::const_iterator i = mChannels.find(tempName);
- ChannelTab *ret = nullptr;
-
- if (i != mChannels.end())
- {
- ret = i->second;
- }
- else
- {
- ret = new ChannelTab(this, name);
- mChannels[tempName] = ret;
- ret->setAllowHighlight(false);
- if (config.getBoolValue("showChatHistory"))
- ret->loadFromLogFile(name);
- }
-
- if (switchTo)
- mChatTabs->setSelectedTab(ret);
-
- return ret;
-}
-
-ChatTab *ChatWindow::addChatTab(const std::string &name,
- const bool switchTo,
- const bool join)
-{
- if (Net::getNetworkType() != ServerType::TMWATHENA &&
- name.size() > 1 &&
- name[0] == '#')
- {
- ChatTab *const tab = addChannelTab(name, switchTo);
- if ((tab != nullptr) && join)
- chatHandler->joinChannel(name);
- return tab;
- }
- return addWhisperTab(name, name, switchTo);
-}
-
-void ChatWindow::postConnection()
-{
- FOR_EACH (ChannelMap::const_iterator, iter, mChannels)
- {
- ChatTab *const tab = iter->second;
- if (tab == nullptr)
- return;
- chatHandler->joinChannel(tab->getChannelName());
- }
- if (langChatTab != nullptr)
- chatHandler->joinChannel(langChatTab->getChannelName());
-}
-
-#define changeColor(fun) \
- { \
- msg = removeColors(msg); \
- int skip = 0; \
- const size_t sz = msg.length(); \
- for (size_t f = 0; f < sz; f ++) \
- { \
- if (skip > 0) \
- { \
- newMsg += msg.at(f); \
- skip --; \
- continue; \
- } \
- const unsigned char ch = CAST_U8(msg.at(f)); \
- if (f + 2 < sz && msg.substr(f, 2) == "%%") \
- { \
- newMsg += msg.at(f); \
- skip = 2; \
- } \
- else if (ch > 0xc0 || ch < 0x80) \
- { \
- newMsg += "##" + toString(fun) + msg.at(f); \
- if (mRainbowColor > 9U) \
- mRainbowColor = 0U; \
- } \
- else \
- { \
- newMsg += msg.at(f); \
- } \
- } \
- }
-
-std::string ChatWindow::addColors(std::string &msg)
-{
- // default color or chat command
- if (mChatColor == 0 || msg.length() == 0 || msg.at(0) == '#'
- || msg.at(0) == '/' || msg.at(0) == '@' || msg.at(0) == '!')
- {
- return msg;
- }
-
- std::string newMsg;
- const int cMap[] = {1, 4, 5, 2, 3, 6, 7, 9, 0, 8};
-
- // rainbow
- switch (mChatColor)
- {
- case 11:
- changeColor(mRainbowColor++)
- return newMsg;
- case 12:
- changeColor(cMap[mRainbowColor++])
- return newMsg;
- case 13:
- changeColor(cMap[9-mRainbowColor++])
- return newMsg;
- default:
- break;
- }
-
- // simple colors
- return std::string("##").append(toString(mChatColor - 1)).append(msg);
-}
-
-#undef changeColor
-
-void ChatWindow::autoComplete()
-{
- const int caretPos = mChatInput->getCaretPosition();
- int startName = 0;
- const std::string &inputText = mChatInput->getText();
- std::string name = inputText.substr(0, caretPos);
-
- for (int f = caretPos - 1; f > -1; f --)
- {
- if (isWordSeparator(inputText[f]))
- {
- startName = f + 1;
- name = inputText.substr(f + 1, caretPos - f);
- break;
- }
- }
-
- if (caretPos - 1 + 1 == startName)
- return;
-
- const ChatTab *const cTab = static_cast<ChatTab*>(
- mChatTabs->getSelectedTab());
- StringVect nameList;
-
- if (cTab != nullptr)
- cTab->getAutoCompleteList(nameList);
- std::string newName = autoComplete(nameList, name);
- if (!newName.empty() && (startName == 0))
- secureChatCommand(newName);
-
- if ((cTab != nullptr) && newName.empty())
- {
- cTab->getAutoCompleteCommands(nameList);
- newName = autoComplete(nameList, name);
- }
-
- if (newName.empty() && (actorManager != nullptr))
- {
- actorManager->getPlayerNames(nameList, NpcNames_true);
- newName = autoComplete(nameList, name);
- if (!newName.empty() && (startName == 0))
- secureChatCommand(newName);
- }
- if (newName.empty())
- newName = autoCompleteHistory(name);
- if (newName.empty() && (spellManager != nullptr))
- newName = spellManager->autoComplete(name);
- if (newName.empty())
- newName = autoComplete(name, &mCommands);
- if (newName.empty() && (actorManager != nullptr))
- {
- actorManager->getMobNames(nameList);
- newName = autoComplete(nameList, name);
- }
- if (newName.empty())
- newName = autoComplete(name, &mCustomWords);
- if (newName.empty())
- {
- whoIsOnline->getPlayerNames(nameList);
- newName = autoComplete(nameList, name);
- }
-
- if (!newName.empty())
- {
- mChatInput->setText(inputText.substr(0, startName).append(newName)
- .append(inputText.substr(caretPos,
- inputText.length() - caretPos)));
-
- const int len = caretPos - CAST_S32(name.length())
- + CAST_S32(newName.length());
-
- if (startName > 0)
- mChatInput->setCaretPosition(len + 1);
- else
- mChatInput->setCaretPosition(len);
- }
-}
-
-std::string ChatWindow::autoComplete(const StringVect &names,
- std::string partName)
-{
- StringVectCIter i = names.begin();
- const StringVectCIter i_end = names.end();
- toLower(partName);
- std::string newName;
-
- while (i != i_end)
- {
- if (!i->empty())
- {
- std::string name = *i;
- toLower(name);
-
- const size_t pos = name.find(partName, 0);
- if (pos == 0)
- {
- if (!newName.empty())
- newName = findSameSubstringI(*i, newName);
- else
- newName = *i;
- }
- }
- ++i;
- }
-
- return newName;
-}
-
-std::string ChatWindow::autoComplete(const std::string &partName,
- const History *const words) const
-{
- if (words == nullptr)
- return "";
-
- ChatCommands::const_iterator i = words->begin();
- const ChatCommands::const_iterator i_end = words->end();
- StringVect nameList;
-
- while (i != i_end)
- {
- const std::string line = *i;
- if (line.find(partName, 0) == 0)
- nameList.push_back(line);
- ++i;
- }
- return autoComplete(nameList, partName);
-}
-
-/*
-void ChatWindow::moveTabLeft(ChatTab *tab)
-{
- mChatTabs->moveLeft(tab);
-}
-
-void ChatWindow::moveTabRight(ChatTab *tab)
-{
- mChatTabs->moveRight(tab);
-}
-*/
-
-std::string ChatWindow::autoCompleteHistory(const std::string &partName) const
-{
- History::const_iterator i = mHistory.begin();
- const History::const_iterator i_end = mHistory.end();
- StringVect nameList;
-
- while (i != i_end)
- {
- std::string line = *i;
- unsigned int f = 0;
- while (f < line.length() && !isWordSeparator(line.at(f)))
- f++;
-
- line = line.substr(0, f);
- if (!line.empty())
- nameList.push_back(line);
-
- ++i;
- }
- return autoComplete(nameList, partName);
-}
-
-bool ChatWindow::resortChatLog(std::string line,
- ChatMsgTypeT own,
- const std::string &channel,
- const IgnoreRecord ignoreRecord,
- const TryRemoveColors tryRemoveColors)
-{
- if (own == ChatMsgType::BY_UNKNOWN)
- {
- const size_t pos = line.find(" : ");
- if (pos != std::string::npos)
- {
- if (line.length() <= pos + 3)
- own = ChatMsgType::BY_SERVER;
- else if (line.substr(0, pos) == localPlayer->getName())
- own = ChatMsgType::BY_PLAYER;
- else
- own = ChatMsgType::BY_OTHER;
- }
- else
- {
- own = ChatMsgType::BY_SERVER;
- }
- }
-
- std::string prefix;
- if (!channel.empty())
- {
- prefix = std::string("##3").append(channel).append("##0");
- }
- else if (mEnableTradeFilter &&
- (tradeChatTab != nullptr) &&
- findI(line, mTradeFilter) != std::string::npos)
- {
- // TRANSLATORS: prefix for moved message to trade tab.
- tradeChatTab->chatLog(std::string("##S") + _("Moved: ") + line,
- own,
- ignoreRecord,
- tryRemoveColors);
- if (own == ChatMsgType::BY_PLAYER)
- {
- own = ChatMsgType::BY_SERVER;
- // TRANSLATORS: moved message to trade tab warning.
- line = _("Your message was moved to trade tab");
- }
- else
- {
- return false;
- }
- }
-
- size_t idx2 = line.find(": ");
- if (idx2 != std::string::npos)
- {
- std::string tmpNick = line.substr(0, idx2);
- if (tmpNick.find('#') != std::string::npos ||
- tmpNick.find(':') != std::string::npos ||
- tmpNick.find('%') != std::string::npos ||
- tmpNick.find('@') != std::string::npos ||
- tmpNick.size() < 5 ||
- tmpNick[0] == '@' ||
- tmpNick[0] == '/' ||
- tmpNick[0] == '!'
- )
- {
- replaceAll(tmpNick, "#", "_");
- replaceAll(tmpNick, "%", "_");
- // TRANSLATORS: error message
- line = _("Broken nick detected: ") + line;
- own = ChatMsgType::BY_SERVER;
- }
- const size_t idx = line.find(": \302\202");
- if (idx == idx2)
- {
- if (line.find(": \302\202\302") != std::string::npos)
- {
- if (line.find(": \302\202\302e") != std::string::npos)
- {
- // Do nothing. Before was local pet emote
- }
- else if (line.find(": \302\202\302m") != std::string::npos)
- {
- // Do nothing. Before was local pet move
- }
- else if (line.find(": \302\202\302d") != std::string::npos)
- {
- // Do nothing. Before was local pet direction
- }
- else if (line.find(": \302\202\302a") != std::string::npos)
- {
- // Do nothing. Before was local pet ai enable/disable
- }
- // ignore other special message formats.
- return false;
- }
-
- // pet talk message detected
- if (line.find(": \302\202\303 ") != std::string::npos)
- {
- // Do nothing. Before was local pet talk
- return false;
- }
- if (line.find(": \302\202\304") != std::string::npos)
- {
- replaceAll(line, ": \302\202\304", ": ");
- }
-
- if (tradeChatTab != nullptr)
- {
- line = line.erase(idx + 2, 2);
- tradeChatTab->chatLog(prefix + line,
- own,
- ignoreRecord,
- tryRemoveColors);
- }
- else if (localChatTab != nullptr)
- {
- line = line.erase(idx + 2, 2);
- localChatTab->chatLog(prefix + line,
- own,
- ignoreRecord,
- tryRemoveColors);
- }
- return false;
- }
- }
-
- if (!channel.empty())
- {
- if (langChatTab != nullptr)
- {
- if (langChatTab->getChannelName() == channel)
- {
- langChatTab->chatLog(line, own, ignoreRecord, tryRemoveColors);
- }
- else if (mShowAllLang)
- {
- langChatTab->chatLog(prefix + line,
- own,
- ignoreRecord,
- tryRemoveColors);
- }
- }
- else if (Net::getNetworkType() != ServerType::TMWATHENA)
- {
- channelChatLog(channel, line, own, ignoreRecord, tryRemoveColors);
- return false;
- }
- else if (mShowAllLang)
- {
- localChatTab->chatLog(prefix + line,
- own,
- ignoreRecord,
- tryRemoveColors);
- }
- }
- else if ((localChatTab != nullptr) && channel.empty())
- {
- localChatTab->chatLog(line, own, ignoreRecord, tryRemoveColors);
- }
- return true;
-}
-
-void ChatWindow::battleChatLog(const std::string &line, ChatMsgTypeT own,
- const IgnoreRecord ignoreRecord,
- const TryRemoveColors tryRemoveColors)
-{
- if (own == ChatMsgType::BY_UNKNOWN)
- own = ChatMsgType::BY_SERVER;
- if (battleChatTab != nullptr)
- battleChatTab->chatLog(line, own, ignoreRecord, tryRemoveColors);
- else if (debugChatTab != nullptr)
- debugChatTab->chatLog(line, own, ignoreRecord, tryRemoveColors);
-}
-
-void ChatWindow::channelChatLog(const std::string &channel,
- const std::string &line,
- ChatMsgTypeT own,
- const IgnoreRecord ignoreRecord,
- const TryRemoveColors tryRemoveColors)
-{
- std::string tempChannel = channel;
- toLower(tempChannel);
-
- ChatTab *tab = nullptr;
- const ChannelMap::const_iterator i = mChannels.find(tempChannel);
-
- if (i != mChannels.end())
- {
- tab = i->second;
- }
- else
- {
- tab = addChannelTab(channel, false);
- if (tab != nullptr)
- saveState();
- }
-
- if (tab != nullptr)
- tab->chatLog(line, own, ignoreRecord, tryRemoveColors);
-}
-
-void ChatWindow::initTradeFilter()
-{
- const std::string tradeListName = settings.serverConfigDir
- + "/tradefilter.txt";
-
- std::ifstream tradeFile;
- struct stat statbuf;
-
- if (stat(tradeListName.c_str(), &statbuf) == 0 &&
- S_ISREG(statbuf.st_mode))
- {
- tradeFile.open(tradeListName.c_str(), std::ios::in);
- if (tradeFile.is_open())
- {
- char line[100];
- while (tradeFile.getline(line, 100))
- {
- const std::string str = line;
- if (!str.empty())
- mTradeFilter.push_back(str);
- }
- }
- tradeFile.close();
- }
-}
-
-void ChatWindow::updateOnline(const std::set<std::string> &onlinePlayers) const
-{
- const Party *party = nullptr;
- const Guild *guild = nullptr;
- if (localPlayer != nullptr)
- {
- party = localPlayer->getParty();
- guild = localPlayer->getGuild();
- }
- FOR_EACH (TabMap::const_iterator, iter, mWhispers)
- {
- if (iter->second == nullptr)
- return;
-
- WhisperTab *const tab = static_cast<WhisperTab*>(iter->second);
- if (tab == nullptr)
- continue;
-
- if (onlinePlayers.find(tab->getNick()) != onlinePlayers.end())
- {
- tab->setWhisperTabColors();
- }
- else
- {
- const std::string &nick = tab->getNick();
- if (actorManager != nullptr)
- {
- const Being *const being = actorManager->findBeingByName(
- nick, ActorType::Player);
- if (being != nullptr)
- {
- tab->setWhisperTabColors();
- continue;
- }
- }
- if (party != nullptr)
- {
- const PartyMember *const pm = party->getMember(nick);
- if ((pm != nullptr) && pm->getOnline())
- {
- tab->setWhisperTabColors();
- continue;
- }
- }
- if (guild != nullptr)
- {
- const GuildMember *const gm = guild->getMember(nick);
- if ((gm != nullptr) && gm->getOnline())
- {
- tab->setWhisperTabColors();
- continue;
- }
- }
- tab->setWhisperTabOfflineColors();
- }
- }
-}
-
-void ChatWindow::loadState()
-{
- int num = 0;
- while (num < 50)
- {
- const std::string nick = serverConfig.getValue(
- "chatWhisper" + toString(num), "");
-
- if (nick.empty())
- break;
-
- const int flags = serverConfig.getValue(
- "chatWhisperFlags" + toString(num), 1);
-
- ChatTab *const tab = addChatTab(nick, false, false);
- if (tab != nullptr)
- {
- tab->setAllowHighlight((flags & 1) != 0);
- tab->setRemoveNames(((flags & 2) / 2) != 0);
- tab->setNoAway(((flags & 4) / 4) != 0);
- }
- num ++;
- }
-}
-
-void ChatWindow::saveState() const
-{
- int num = 0;
- for (ChannelMap::const_iterator iter = mChannels.begin(),
- iter_end = mChannels.end(); iter != iter_end && num < 50; ++iter)
- {
- if (iter->second == nullptr)
- return;
- if (!saveTab(num, iter->second))
- continue;
- num ++;
- }
-
- for (TabMap::const_iterator iter = mWhispers.begin(),
- iter_end = mWhispers.end(); iter != iter_end && num < 50; ++iter)
- {
- if (iter->second == nullptr)
- return;
- if (!saveTab(num, iter->second))
- continue;
- num ++;
- }
-
- while (num < 50)
- {
- serverConfig.deleteKey("chatWhisper" + toString(num));
- serverConfig.deleteKey("chatWhisperFlags" + toString(num));
- num ++;
- }
-}
-
-bool ChatWindow::saveTab(const int num,
- const ChatTab *const tab) const
-{
- if (tab == nullptr)
- return false;
-
- serverConfig.setValue("chatWhisper" + toString(num),
- tab->getChannelName());
-
- serverConfig.setValue("chatWhisperFlags" + toString(num),
- CAST_S32(tab->getAllowHighlight())
- + (2 * CAST_S32(tab->getRemoveNames()))
- + (4 * CAST_S32(tab->getNoAway())));
-
- return true;
-}
-
-std::string ChatWindow::doReplace(const std::string &msg)
-{
- std::string str = msg;
- replaceSpecialChars(str);
- return str;
-}
-
-void ChatWindow::loadCustomList()
-{
- std::ifstream listFile;
- struct stat statbuf;
-
- std::string listName = settings.serverConfigDir
- + "/customwords.txt";
-
- if ((stat(listName.c_str(), &statbuf) == 0) && S_ISREG(statbuf.st_mode))
- {
- listFile.open(listName.c_str(), std::ios::in);
- if (listFile.is_open())
- {
- char line[101];
- while (listFile.getline(line, 100))
- {
- std::string str = line;
- if (!str.empty())
- mCustomWords.push_back(str);
- }
- }
- listFile.close();
- }
-}
-
-void ChatWindow::addToAwayLog(const std::string &line)
-{
- if (!settings.awayMode)
- return;
-
- if (mAwayLog.size() > 20)
- mAwayLog.pop_front();
-
- if (findI(line, mHighlights) != std::string::npos)
- mAwayLog.push_back("##aaway:" + line);
-}
-
-void ChatWindow::displayAwayLog() const
-{
- if (localChatTab == nullptr)
- return;
-
- std::list<std::string>::const_iterator i = mAwayLog.begin();
- const std::list<std::string>::const_iterator i_end = mAwayLog.end();
-
- while (i != i_end)
- {
- std::string str = *i;
- localChatTab->addNewRow(str);
- ++i;
- }
-}
-
-void ChatWindow::parseHighlights()
-{
- mHighlights.clear();
- if (localPlayer == nullptr)
- return;
-
- splitToStringVector(mHighlights, config.getStringValue(
- "highlightWords"), ',');
-
- mHighlights.push_back(localPlayer->getName());
-}
-
-void ChatWindow::parseGlobalsFilter()
-{
- mGlobalsFilter.clear();
- if (localPlayer == nullptr)
- return;
-
- splitToStringVector(mGlobalsFilter, config.getStringValue(
- "globalsFilter"), ',');
-
- mHighlights.push_back(localPlayer->getName());
-}
-
-bool ChatWindow::findHighlight(const std::string &str)
-{
- return findI(str, mHighlights) != std::string::npos;
-}
-
-void ChatWindow::copyToClipboard(const int x, const int y) const
-{
- const ChatTab *const tab = getFocused();
- if (tab == nullptr)
- return;
-
- const BrowserBox *const text = tab->mTextOutput;
- if (text == nullptr)
- return;
-
- std::string str = text->getTextAtPos(x, y);
- sendBuffer(str);
-}
-
-void ChatWindow::optionChanged(const std::string &name)
-{
- if (name == "autohideChat")
- mAutoHide = config.getBoolValue("autohideChat");
- else if (name == "showBattleEvents")
- mShowBattleEvents = config.getBoolValue("showBattleEvents");
- else if (name == "globalsFilter")
- parseGlobalsFilter();
- else if (name == "enableTradeFilter")
- mEnableTradeFilter = config.getBoolValue("enableTradeFilter");
-}
-
-void ChatWindow::mouseMoved(MouseEvent &event)
-{
- mHaveMouse = true;
- Window::mouseMoved(event);
-}
-
-void ChatWindow::mouseEntered(MouseEvent& event)
-{
- mHaveMouse = true;
- Window::mouseEntered(event);
-}
-
-void ChatWindow::mouseExited(MouseEvent& event)
-{
- updateVisibility();
- Window::mouseExited(event);
-}
-
-void ChatWindow::draw(Graphics *const graphics)
-{
- BLOCK_START("ChatWindow::draw")
- if (!mAutoHide || mHaveMouse)
- {
- GLDEBUG_START("ChatWindow::draw");
- Window::draw(graphics);
- GLDEBUG_END();
- }
- BLOCK_END("ChatWindow::draw")
-}
-
-void ChatWindow::safeDraw(Graphics *const graphics)
-{
- BLOCK_START("ChatWindow::draw")
- if (!mAutoHide || mHaveMouse)
- {
- GLDEBUG_START("ChatWindow::draw");
- Window::safeDraw(graphics);
- GLDEBUG_END();
- }
- BLOCK_END("ChatWindow::draw")
-}
-
-void ChatWindow::updateVisibility()
-{
- if (gui == nullptr)
- return;
-
- int mouseX = 0;
- int mouseY = 0;
- int x = 0;
- int y = 0;
- Gui::getMouseState(mouseX, mouseY);
- getAbsolutePosition(x, y);
- if (mChatInput->isVisible())
- {
- mHaveMouse = true;
- }
- else
- {
- mHaveMouse = mouseX >= x && mouseX <= x + getWidth()
- && mouseY >= y && mouseY <= y + getHeight();
- }
-}
-
-void ChatWindow::unHideWindow()
-{
- mHaveMouse = true;
-}
-
-#ifdef USE_PROFILER
-void ChatWindow::logicChildren()
-{
- BLOCK_START("ChatWindow::logicChildren")
- BasicContainer::logicChildren();
- BLOCK_END("ChatWindow::logicChildren")
-}
-#endif // USE_PROFILER
-
-void ChatWindow::addGlobalMessage(const std::string &line)
-{
- if (debugChatTab != nullptr &&
- findI(line, mGlobalsFilter) != std::string::npos)
- {
- debugChatTab->chatLog(line, ChatMsgType::BY_OTHER);
- }
- else
- {
- localChatTab->chatLog(line, ChatMsgType::BY_GM);
- }
-}
-
-bool ChatWindow::isTabPresent(const ChatTab *const tab) const
-{
- return mChatTabs->isTabPresent(tab);
-}
-
-void ChatWindow::debugMessage(const std::string &msg)
-{
- if (debugChatTab != nullptr)
- debugChatTab->chatLog(msg, ChatMsgType::BY_SERVER);
-}
-
-void ChatWindow::showGMTab()
-{
- if ((gmChatTab == nullptr) &&
- config.getBoolValue("enableGmTab") &&
- localPlayer->getGroupId() >= paths.getIntValue("gmTabMinimalLevel"))
- {
- addSpecialChannelTab(GM_CHANNEL, false);
- }
-}
-
-void ChatWindow::toggleChatFocus()
-{
- if (mChatInput->isVisible() && mChatInput->isFocused())
- mChatInput->processVisible(Visible_false);
- else
- requestChatFocus();
-}
-
-void ChatWindow::joinRoom(const bool isJoin)
-{
- Tab *const tab = mChatTabs->getTabByIndex(0);
- if (tab != nullptr)
- {
- std::string name;
- if (isJoin)
- {
- name = PlayerInfo::getRoomName();
- }
- else
- {
- // TRANSLATORS: chat tab name
- name = _("General");
- }
- tab->setCaption(name);
- }
-}
-
-void ChatWindow::scheduleDelete()
-{
- DebugMessageListener::removeListener(this);
- Window::scheduleDelete();
-}
diff --git a/src/gui/windows/chatwindow.h b/src/gui/windows/chatwindow.h
deleted file mode 100644
index 7d02e0fd3..000000000
--- a/src/gui/windows/chatwindow.h
+++ /dev/null
@@ -1,406 +0,0 @@
-/*
- * The ManaPlus Client
- * Copyright (C) 2004-2009 The Mana World Development Team
- * Copyright (C) 2009-2010 The Mana Developers
- * Copyright (C) 2011-2017 The ManaPlus Developers
- *
- * This file is part of The ManaPlus Client.
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-#ifndef GUI_WINDOWS_CHATWINDOW_H
-#define GUI_WINDOWS_CHATWINDOW_H
-
-#include "enums/gui/chatmsgtype.h"
-#include "enums/gui/chattabtype.h"
-
-#include "enums/simpletypes/ignorerecord.h"
-#include "enums/simpletypes/tryremovecolors.h"
-
-#include "gui/widgets/window.h"
-
-#include "listeners/actionlistener.h"
-#include "listeners/attributelistener.h"
-#include "listeners/debugmessagelistener.h"
-#include "listeners/keylistener.h"
-
-class Button;
-class ChannelTab;
-class ChatTab;
-class ChatInput;
-class ColorListModel;
-class DropDown;
-class TabbedArea;
-class ItemLinkHandler;
-class WhisperTab;
-
-/**
- * The chat window.
- *
- * \ingroup Interface
- */
-class ChatWindow final : public Window,
- public ActionListener,
- public KeyListener,
- public ConfigListener,
- public AttributeListener,
- public DebugMessageListener
-{
- public:
- /**
- * Constructor.
- */
- explicit ChatWindow(const std::string &name);
-
- A_DELETE_COPY(ChatWindow)
-
- /**
- * Destructor: used to write back values to the config file
- */
- ~ChatWindow();
-
- /**
- * Gets the focused tab.
- */
- ChatTab *getFocused() const A_WARN_UNUSED;
-
- /**
- * Clear the given tab.
- */
- static void clearTab(ChatTab *const tab);
-
- /**
- * Clear the current tab.
- */
- void clearTab() const;
-
- /**
- * Switch to the previous tab in order
- */
- void prevTab();
-
- /**
- * Switch to the next tab in order
- */
- void nextTab();
-
- /**
- * Close current chat tab
- */
- void closeTab() const;
-
- /**
- * Switch to the default tab
- */
- void defaultTab();
-
- /**
- * Performs action.
- */
- void action(const ActionEvent &event) override final;
-
- /**
- * Request focus for typing chat message.
- *
- * \returns true if the input was shown
- * false otherwise
- */
- bool requestChatFocus();
-
- /**
- * Checks whether ChatWindow is Focused or not.
- */
- bool isInputFocused() const A_WARN_UNUSED;
-
- /**
- * Passes the text to the current tab as input
- *
- * @param msg The message text which is to be sent.
- */
- void chatInput(const std::string &msg) const;
-
- /**
- * Passes the text to the local chat tab as input
- *
- * @param msg The message text which is to be sent.
- */
- void localChatInput(const std::string &msg) const;
-
- /** Called when key is pressed */
- void keyPressed(KeyEvent &event) override final;
-
- /** Set the chat input as the given text. */
- void setInputText(const std::string &text);
-
- /** Add the given text to the chat input. */
- void addInputText(const std::string &text, const bool space = true);
-
- /** Called to add item to chat */
- void addItemText(const std::string &item);
-
- /** Override to reset mTmpVisible */
- void setVisible(Visible visible) override final;
-
- /**
- * Handles mouse when dragged.
- */
- void mouseDragged(MouseEvent &event) override final;
-
- /**
- * Handles mouse when pressed.
- */
- void mousePressed(MouseEvent &event) override final;
-
- /**
- * Scrolls the chat window
- *
- * @param amount direction and amount to scroll. Negative numbers scroll
- * up, positive numbers scroll down. The absolute amount indicates the
- * amount of 1/8ths of chat window real estate that should be scrolled.
- */
- void scroll(const int amount) const;
-
- /**
- * Sets the file being recorded to
- *
- * @param msg The file to write out to. If null, then stop recording.
- */
- void setRecordingFile(const std::string &msg);
-
- bool getReturnTogglesChat() const noexcept2 A_WARN_UNUSED
- { return mReturnToggles; }
-
- void setReturnTogglesChat(const bool toggles)
- { mReturnToggles = toggles; }
-
- void doPresent() const;
-
- void addWhisper(const std::string &restrict nick,
- const std::string &restrict mes,
- const ChatMsgTypeT own = ChatMsgType::BY_OTHER);
-
- WhisperTab *addWhisperTab(const std::string &caption,
- const std::string &nick,
- const bool switchTo = false) A_WARN_UNUSED;
-
- WhisperTab *getWhisperTab(const std::string &nick) const A_WARN_UNUSED;
-
- ChatTab *addChannelTab(const std::string &name,
- const bool switchTo = false);
-
- ChatTab *addSpecialChannelTab(const std::string &name,
- const bool switchTo = false);
-
- ChatTab *addChatTab(const std::string &name,
- const bool switchTo,
- const bool join) A_WARN_UNUSED;
-
- void joinRoom(const bool isJoin);
-
- void removeAllWhispers();
-
- void removeAllChannels();
-
- void ignoreAllWhispers();
-
- bool resortChatLog(std::string line, ChatMsgTypeT own,
- const std::string &channel,
- const IgnoreRecord ignoreRecord,
- const TryRemoveColors tryRemoveColors);
-
- static void battleChatLog(const std::string &line,
- ChatMsgTypeT own
- = ChatMsgType::BY_UNKNOWN,
- const IgnoreRecord ignoreRecord
- = IgnoreRecord_false,
- const TryRemoveColors tryRemoveColors
- = TryRemoveColors_true);
-
- void channelChatLog(const std::string &channel,
- const std::string &line,
- ChatMsgTypeT own,
- const IgnoreRecord ignoreRecord,
- const TryRemoveColors tryRemoveColors);
-
- void updateOnline(const std::set<std::string> &onlinePlayers) const;
-
- void loadState();
-
- void saveState() const;
-
- bool saveTab(const int num,
- const ChatTab *const tab) const;
-
- void loadCustomList();
-
- void loadGMCommands();
-
- static std::string doReplace(const std::string &msg) A_WARN_UNUSED;
-
- void adjustTabSize();
-
- void addToAwayLog(const std::string &line);
-
- void displayAwayLog() const;
-
- void clearAwayLog()
- { mAwayLog.clear(); }
-
- void parseHighlights();
-
- void parseGlobalsFilter();
-
- bool findHighlight(const std::string &str) A_WARN_UNUSED;
-
- void copyToClipboard(const int x, const int y) const;
-
- void optionChanged(const std::string &name) override final;
-
- void mouseEntered(MouseEvent& event) override final;
-
- void mouseMoved(MouseEvent &event) override final;
-
- void mouseExited(MouseEvent& event A_UNUSED) override final;
-
- void draw(Graphics *const graphics) override final A_NONNULL(2);
-
- void safeDraw(Graphics *const graphics) override final A_NONNULL(2);
-
- void updateVisibility();
-
- void unHideWindow();
-
- void widgetResized(const Event &event) override final;
-
- void addGlobalMessage(const std::string &line);
-
- void postInit() override final;
-
- bool isTabPresent(const ChatTab *const tab) const A_WARN_UNUSED;
-
- void selectTabByType(const ChatTabTypeT &type);
-
- void attributeChanged(const AttributesT id,
- const int64_t oldVal,
- const int64_t newVal) override final;
-
- void postConnection();
-
- void showGMTab();
-
- void debugMessage(const std::string &msg) override final;
-
- void scheduleDelete() override final;
-
-#ifdef USE_PROFILER
- void logicChildren();
-#endif // USE_PROFILER
-
- protected:
- friend class ChannelTab;
- friend class ChatTab;
- friend class WhisperTab;
- friend class PopupMenu;
-
- typedef std::list<std::string> History;
-
- /** Remove the given tab from the window */
- void removeTab(ChatTab *const tab);
-
- /** Add the tab to the window */
- void addTab(ChatTab *const tab);
-
- void removeWhisper(const std::string &nick);
-
- void removeChannel(const std::string &nick);
-
- void autoComplete();
-
- std::string addColors(std::string &msg);
-
- std::string autoCompleteHistory(const std::string &partName) const;
-
- std::string autoComplete(const std::string &partName,
- const History *const words) const;
-
- static std::string autoComplete(const StringVect &names,
- std::string partName);
-
- /** Used for showing item popup on clicking links **/
- ItemLinkHandler *mItemLinkHandler A_NONNULLPOINTER;
-
- /** Tabbed area for holding each channel. */
- TabbedArea *mChatTabs A_NONNULLPOINTER;
-
- /** Input box for typing chat messages. */
- ChatInput *mChatInput A_NONNULLPOINTER;
-
- void initTradeFilter();
-
- void toggleChatFocus();
-
- unsigned int mRainbowColor;
-
- private:
- void fillCommands();
-
- void loadCommandsFile(const std::string &name);
-
- void updateTabsMargin();
-
- bool addCurrentToHistory();
-
- typedef std::map<const std::string, WhisperTab*> TabMap;
- typedef std::map<const std::string, ChannelTab*> ChannelMap;
-
- /** Manage whisper tabs */
- TabMap mWhispers;
- ChannelMap mChannels;
-
- typedef History::iterator HistoryIterator;
- History mHistory; /**< Command history. */
- HistoryIterator mCurHist; /**< History iterator. */
-
- typedef std::list<std::string> ChatCommands;
- typedef ChatCommands::iterator ChatCommandsIterator;
- History mCommands; /**< Command list. */
- History mCustomWords;
-
- StringVect mTradeFilter;
-
- ColorListModel *mColorListModel A_NONNULLPOINTER;
- DropDown *mColorPicker A_NONNULLPOINTER;
- Button *mChatButton A_NONNULLPOINTER;
- std::list<std::string> mAwayLog;
- StringVect mHighlights;
- StringVect mGlobalsFilter;
- int mChatColor;
- int mEmoteButtonSpacing;
- int mEmoteButtonY;
- unsigned int mChatHistoryIndex;
- bool mReturnToggles; // Marks whether <Return> toggles the chat log
- // or not
- bool mGMLoaded;
- bool mHaveMouse;
- bool mAutoHide;
- bool mShowBattleEvents;
- bool mShowAllLang;
- bool mEnableTradeFilter;
- bool mTmpVisible;
-};
-
-extern ChatWindow *chatWindow;
-
-#endif // GUI_WINDOWS_CHATWINDOW_H
diff --git a/src/gui/windows/confirmdialog.cpp b/src/gui/windows/confirmdialog.cpp
deleted file mode 100644
index 913fb7c41..000000000
--- a/src/gui/windows/confirmdialog.cpp
+++ /dev/null
@@ -1,120 +0,0 @@
-/*
- * The ManaPlus Client
- * Copyright (C) 2004-2009 The Mana World Development Team
- * Copyright (C) 2009-2010 The Mana Developers
- * Copyright (C) 2011-2017 The ManaPlus Developers
- *
- * This file is part of The ManaPlus Client.
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-#include "gui/windows/confirmdialog.h"
-
-#include "soundmanager.h"
-
-#include "gui/fonts/font.h"
-
-#include "gui/widgets/button.h"
-#include "gui/widgets/textbox.h"
-
-#include "utils/gettext.h"
-
-#include "debug.h"
-
-ConfirmDialog::ConfirmDialog(const std::string &restrict title,
- const std::string &restrict msg,
- const std::string &restrict soundEvent,
- const bool ignore,
- const Modal modal,
- Window *const parent) :
- Window(title, modal, parent, "confirm.xml"),
- ActionListener(),
- mTextBox(new TextBox(this)),
- mIgnore(ignore)
-{
- mTextBox->setEditable(false);
- mTextBox->setOpaque(Opaque_false);
- mTextBox->setTextWrapped(msg, 260);
- soundManager.playGuiSound(soundEvent);
-}
-
-void ConfirmDialog::postInit()
-{
- Window::postInit();
- // TRANSLATORS: confirm dialog button
- Button *const yesButton = new Button(this, _("Yes"), "yes", this);
- // TRANSLATORS: confirm dialog button
- Button *const noButton = new Button(this, _("No"), "no", this);
- Button *const ignoreButton = mIgnore ? new Button(
- // TRANSLATORS: confirm dialog button
- this, _("Ignore"), "ignore", this) : nullptr;
-
- const int numRows = mTextBox->getNumberOfRows();
- int inWidth = yesButton->getWidth() + noButton->getWidth() +
- (2 * mPadding);
-
- if (ignoreButton != nullptr)
- inWidth += ignoreButton->getWidth();
-
- const int fontHeight = getFont()->getHeight();
- const int height = numRows * fontHeight;
- int width = getFont()->getWidth(getCaption()) + mCaptionOffsetX;
-
- if (width < mTextBox->getMinWidth())
- width = mTextBox->getMinWidth();
- if (width < inWidth)
- width = inWidth;
-
- int windowWidth = width;
- if (windowWidth < mTextBox->getMinWidth() + fontHeight)
- {
- windowWidth = mTextBox->getMinWidth() + fontHeight;
- }
- setContentSize(windowWidth,
- height + fontHeight + noButton->getHeight());
- mTextBox->setPosition(mPadding, mPadding);
-
- const int buttonPadding = getOption("buttonPadding", 8);
- yesButton->setPosition((width - inWidth) / 2, height + buttonPadding);
- noButton->setPosition(yesButton->getX() + yesButton->getWidth()
- + (2 * mPadding), height + buttonPadding);
- if (ignoreButton != nullptr)
- {
- ignoreButton->setPosition(noButton->getX() + noButton->getWidth()
- + (2 * mPadding), height + buttonPadding);
- }
-
- add(mTextBox);
- add(yesButton);
- add(noButton);
-
- if (mIgnore && (ignoreButton != nullptr))
- add(ignoreButton);
-
- if (getParent() != nullptr)
- {
- center();
- getParent()->moveToTop(this);
- }
- setVisible(Visible_true);
- yesButton->requestFocus();
-}
-
-void ConfirmDialog::action(const ActionEvent &event)
-{
- setActionEventId(event.getId());
- distributeActionEvent();
- scheduleDelete();
-}
diff --git a/src/gui/windows/confirmdialog.h b/src/gui/windows/confirmdialog.h
deleted file mode 100644
index 5d828eafb..000000000
--- a/src/gui/windows/confirmdialog.h
+++ /dev/null
@@ -1,71 +0,0 @@
-/*
- * The ManaPlus Client
- * Copyright (C) 2004-2009 The Mana World Development Team
- * Copyright (C) 2009-2010 The Mana Developers
- * Copyright (C) 2011-2017 The ManaPlus Developers
- *
- * This file is part of The ManaPlus Client.
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-#ifndef GUI_WINDOWS_CONFIRMDIALOG_H
-#define GUI_WINDOWS_CONFIRMDIALOG_H
-
-#include "localconsts.h"
-
-#include "const/sound.h"
-
-#include "gui/widgets/window.h"
-
-#include "listeners/actionlistener.h"
-
-class TextBox;
-
-/**
- * An option dialog.
- *
- * \ingroup GUI
- */
-class ConfirmDialog notfinal : public Window,
- public ActionListener
-{
- public:
- /**
- * Constructor.
- *
- * @see Window::Window
- */
- ConfirmDialog(const std::string &restrict title,
- const std::string &restrict msg,
- const std::string &restrict soundEvent = SOUND_REQUEST,
- const bool ignore = false,
- const Modal modal = Modal_false,
- Window *const parent = nullptr);
-
- A_DELETE_COPY(ConfirmDialog)
-
- /**
- * Called when receiving actions from the widgets.
- */
- void action(const ActionEvent &event) override;
-
- void postInit() override final;
-
- private:
- TextBox *mTextBox A_NONNULLPOINTER;
- bool mIgnore;
-};
-
-#endif // GUI_WINDOWS_CONFIRMDIALOG_H
diff --git a/src/gui/windows/connectiondialog.cpp b/src/gui/windows/connectiondialog.cpp
deleted file mode 100644
index ec23ab646..000000000
--- a/src/gui/windows/connectiondialog.cpp
+++ /dev/null
@@ -1,90 +0,0 @@
-/*
- * The ManaPlus Client
- * Copyright (C) 2004-2009 The Mana World Development Team
- * Copyright (C) 2009-2010 The Mana Developers
- * Copyright (C) 2011-2017 The ManaPlus Developers
- *
- * This file is part of The ManaPlus Client.
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-#include "gui/windows/connectiondialog.h"
-
-#include "gui/widgets/button.h"
-#include "gui/widgets/label.h"
-#include "gui/widgets/layoutcell.h"
-#include "gui/widgets/progressindicator.h"
-
-#include "utils/gettext.h"
-
-#include "client.h"
-
-#include "debug.h"
-
-extern bool mStatsReUpdated;
-
-ConnectionDialog::ConnectionDialog(const std::string &text,
- const StateT cancelState) :
- Window("", Modal_false, nullptr, "connection.xml"),
- ActionListener(),
- mCancelState(cancelState)
-{
- mTitleBarHeight = 0;
- setMovable(Move_false);
- setMinWidth(0);
-
- ProgressIndicator *const progressIndicator = new ProgressIndicator(this);
- Label *const label = new Label(this, text);
- Button *const cancelButton = new Button(
- // TRANSLATORS: connection dialog button
- this, _("Cancel"), "cancelButton", this);
-
- place(0, 0, progressIndicator);
- place(0, 1, label);
- place(0, 2, cancelButton).setHAlign(LayoutCell::CENTER);
- reflowLayout();
-
- center();
- if ((mSearchHash ^ 0x202020U) == 0x70E9296C)
- mStatsReUpdated = true;
-}
-
-void ConnectionDialog::postInit()
-{
- Window::postInit();
- setVisible(Visible_true);
-}
-
-void ConnectionDialog::action(const ActionEvent &event A_UNUSED)
-{
- logger->log1("Cancel pressed");
- client->setState(mCancelState);
-}
-
-void ConnectionDialog::draw(Graphics *const graphics)
-{
- BLOCK_START("ConnectionDialog::draw")
- // Don't draw the window background, only draw the children
- drawChildren(graphics);
- BLOCK_END("ConnectionDialog::draw")
-}
-
-void ConnectionDialog::safeDraw(Graphics *const graphics)
-{
- BLOCK_START("ConnectionDialog::draw")
- // Don't draw the window background, only draw the children
- safeDrawChildren(graphics);
- BLOCK_END("ConnectionDialog::draw")
-}
diff --git a/src/gui/windows/connectiondialog.h b/src/gui/windows/connectiondialog.h
deleted file mode 100644
index ca403c477..000000000
--- a/src/gui/windows/connectiondialog.h
+++ /dev/null
@@ -1,69 +0,0 @@
-/*
- * The ManaPlus Client
- * Copyright (C) 2004-2009 The Mana World Development Team
- * Copyright (C) 2009-2010 The Mana Developers
- * Copyright (C) 2011-2017 The ManaPlus Developers
- *
- * This file is part of The ManaPlus Client.
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-#ifndef GUI_WINDOWS_CONNECTIONDIALOG_H
-#define GUI_WINDOWS_CONNECTIONDIALOG_H
-
-#include "enums/state.h"
-
-#include "gui/widgets/window.h"
-
-#include "listeners/actionlistener.h"
-
-/**
- * The connection dialog.
- *
- * \ingroup Interface
- */
-class ConnectionDialog final : public Window,
- private ActionListener
-{
- public:
- /**
- * Constructor.
- *
- * @param text The text to display
- * @param cancelState The state to enter when Cancel is pressed
- *
- * @see Window::Window
- */
- ConnectionDialog(const std::string &text, const StateT cancelState);
-
- A_DELETE_COPY(ConnectionDialog)
-
- void postInit() override final;
-
- /**
- * Called when the user presses Cancel. Restores the global state to
- * the previous one.
- */
- void action(const ActionEvent &event) override final;
-
- void draw(Graphics *const graphics) override final A_NONNULL(2);
-
- void safeDraw(Graphics *const graphics) override final A_NONNULL(2);
-
- private:
- StateT mCancelState;
-};
-
-#endif // GUI_WINDOWS_CONNECTIONDIALOG_H
diff --git a/src/gui/windows/cutinwindow.cpp b/src/gui/windows/cutinwindow.cpp
deleted file mode 100644
index 2713dfdfc..000000000
--- a/src/gui/windows/cutinwindow.cpp
+++ /dev/null
@@ -1,153 +0,0 @@
-/*
- * The ManaPlus Client
- * Copyright (C) 2004-2009 The Mana World Development Team
- * Copyright (C) 2009-2010 The Mana Developers
- * Copyright (C) 2011-2017 The ManaPlus Developers
- *
- * This file is part of The ManaPlus Client.
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-#include "gui/windows/cutinwindow.h"
-
-#include "configuration.h"
-
-#include "const/utils/timer.h"
-
-#include "resources/sprite/animatedsprite.h"
-
-#include "utils/delete2.h"
-#include "utils/timer.h"
-
-#include "debug.h"
-
-CutInWindow *cutInWindow = nullptr;
-
-CutInWindow::CutInWindow() :
- Window("", Modal_false, nullptr, "cutin.xml"),
- mImage(nullptr),
- mOldTitleBarHeight(mTitleBarHeight)
-{
- setWindowName("CutIn");
-
- setShowTitle(false);
- setResizable(false);
- setDefaultVisible(false);
- setSaveVisible(false);
- setVisible(Visible_false);
- enableVisibleSound(false);
-}
-
-CutInWindow::~CutInWindow()
-{
- delete2(mImage);
-}
-
-void CutInWindow::draw(Graphics *const graphics)
-{
- Window::draw(graphics);
- draw2(graphics);
-}
-
-void CutInWindow::safeDraw(Graphics *const graphics)
-{
- Window::safeDraw(graphics);
- draw2(graphics);
-}
-
-void CutInWindow::draw2(Graphics *const graphics)
-{
- if (mImage != nullptr)
- mImage->drawRaw(graphics, mPadding, mTitleBarHeight);
-}
-
-void CutInWindow::show(const std::string &name,
- const CutInT cutin)
-{
- delete2(mImage);
- if (name.empty())
- {
- setVisible(Visible_false);
- }
- else
- {
- mImage = AnimatedSprite::load(
- pathJoin(paths.getStringValue("cutInsDir"),
- name).append(
- ".xml"));
- if (mImage != nullptr)
- {
- mImage->update(1);
- const bool showTitle = (cutin == CutIn::MovableClose);
- if (showTitle)
- mTitleBarHeight = mOldTitleBarHeight;
- else
- mTitleBarHeight = mPadding;
- const int width = mImage->getWidth() + 2 * mPadding;
- const int height = mImage->getHeight() + mTitleBarHeight
- + mPadding;
-
- const int screenWidth = mainGraphics->mWidth;
- const int screenHeight = mainGraphics->mHeight;
-
- if (width * 2 > screenWidth ||
- height * 2 > screenHeight)
- {
- return;
- }
- const int padding = 100;
- int x = 0;
- const int y = screenHeight - height - padding;
- switch (cutin)
- {
- case CutIn::BottomRight:
- x = screenWidth - width - padding;
- break;
- case CutIn::BottomCenter:
- case CutIn::Movable:
- case CutIn::MovableClose:
- x = (screenWidth - width) / 2;
- break;
- case CutIn::BottomLeft:
- default:
- x = padding;
- break;
- }
- setCloseButton(false);
- setVisible(Visible_true);
- setPosition(x, y);
- setCloseButton(showTitle);
- setShowTitle(showTitle);
- setSize(width, height);
- setVisible(Visible_true);
- requestMoveToTop();
- }
- }
-}
-
-void CutInWindow::hide()
-{
- delete2(mImage);
- setVisible(Visible_false);
-}
-
-void CutInWindow::logic()
-{
- if (mImage != nullptr)
- {
- const int time = tick_time * MILLISECONDS_IN_A_TICK;
- mImage->update(time);
- }
-}
diff --git a/src/gui/windows/cutinwindow.h b/src/gui/windows/cutinwindow.h
deleted file mode 100644
index c0aa81577..000000000
--- a/src/gui/windows/cutinwindow.h
+++ /dev/null
@@ -1,61 +0,0 @@
-/*
- * The ManaPlus Client
- * Copyright (C) 2004-2009 The Mana World Development Team
- * Copyright (C) 2009-2010 The Mana Developers
- * Copyright (C) 2011-2017 The ManaPlus Developers
- *
- * This file is part of The ManaPlus Client.
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-#ifndef GUI_WINDOWS_CUTINWINDOW_H
-#define GUI_WINDOWS_CUTINWINDOW_H
-
-#include "gui/widgets/window.h"
-
-#include "enums/cutin.h"
-
-class AnimatedSprite;
-
-class CutInWindow final : public Window
-{
- public:
- CutInWindow();
-
- A_DELETE_COPY(CutInWindow)
-
- ~CutInWindow();
-
- void draw(Graphics *const graphics) override final A_NONNULL(2);
-
- void safeDraw(Graphics *const graphics) override final A_NONNULL(2);
-
- void draw2(Graphics *const graphics) A_NONNULL(2);
-
- void show(const std::string &name,
- const CutInT cutin);
-
- void hide();
-
- void logic() override final;
-
- private:
- AnimatedSprite *mImage;
- int mOldTitleBarHeight;
-};
-
-extern CutInWindow *cutInWindow;
-
-#endif // GUI_WINDOWS_CUTINWINDOW_H
diff --git a/src/gui/windows/debugwindow.cpp b/src/gui/windows/debugwindow.cpp
deleted file mode 100644
index e10ad1b2c..000000000
--- a/src/gui/windows/debugwindow.cpp
+++ /dev/null
@@ -1,173 +0,0 @@
-/*
- * The ManaPlus Client
- * Copyright (C) 2004-2009 The Mana World Development Team
- * Copyright (C) 2009-2010 The Mana Developers
- * Copyright (C) 2011-2017 The ManaPlus Developers
- *
- * This file is part of The ManaPlus Client.
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-#include "gui/windows/debugwindow.h"
-
-#include "being/localplayer.h"
-
-#include "gui/windows/setupwindow.h"
-
-#include "gui/widgets/createwidget.h"
-#include "gui/widgets/tabbedarea.h"
-
-#include "gui/widgets/tabs/debugwindowtabs.h"
-
-#include "utils/delete2.h"
-#include "utils/gettext.h"
-
-#include "debug.h"
-
-DebugWindow *debugWindow = nullptr;
-
-DebugWindow::DebugWindow(const std::string &name) :
- // TRANSLATORS: debug window name
- Window(_("Debug"), Modal_false, nullptr, "debug.xml"),
- mTabs(CREATEWIDGETR(TabbedArea, this)),
- mMapWidget(new MapDebugTab(this)),
- mTargetWidget(new TargetDebugTab(this)),
- mNetWidget(new NetDebugTab(this))
-{
- setWindowName(name);
- if (setupWindow != nullptr)
- setupWindow->registerWindowForReset(this);
-
- setResizable(true);
- setCloseButton(true);
- setSaveVisible(true);
- setStickyButtonLock(true);
-
- setDefaultSize(400, 300, ImagePosition::CENTER);
-
- mTabs->setSelectable(false);
- mTabs->getWidgetContainer()->setSelectable(false);
- mTabs->getTabContainer()->setSelectable(false);
- // TRANSLATORS: debug window tab
- mTabs->addTab(std::string(_("Map")), mMapWidget);
- // TRANSLATORS: debug window tab
- mTabs->addTab(std::string(_("Target")), mTargetWidget);
- // TRANSLATORS: debug window tab
- mTabs->addTab(std::string(_("Net")), mNetWidget);
-
- mTabs->setDimension(Rect(0, 0, 600, 300));
-
- const int w = mDimension.width;
- const int h = mDimension.height;
- mMapWidget->resize(w, h);
- mTargetWidget->resize(w, h);
- mNetWidget->resize(w, h);
- loadWindowState();
- enableVisibleSound(true);
-}
-
-DebugWindow::~DebugWindow()
-{
- delete2(mMapWidget);
- delete2(mTargetWidget);
- delete2(mNetWidget);
-}
-
-void DebugWindow::postInit()
-{
- Window::postInit();
- add(mTabs);
-}
-
-void DebugWindow::slowLogic()
-{
- BLOCK_START("DebugWindow::slowLogic")
- if (!isWindowVisible() || (mTabs == nullptr))
- {
- BLOCK_END("DebugWindow::slowLogic")
- return;
- }
-
- switch (mTabs->getSelectedTabIndex())
- {
- default:
- case 0:
- mMapWidget->logic();
- break;
- case 1:
- mTargetWidget->logic();
- break;
- case 2:
- mNetWidget->logic();
- break;
- }
-
- if (localPlayer != nullptr)
- localPlayer->tryPingRequest();
- BLOCK_END("DebugWindow::slowLogic")
-}
-
-void DebugWindow::draw(Graphics *const g)
-{
- BLOCK_START("DebugWindow::draw")
- Window::draw(g);
-
- if (localPlayer != nullptr)
- {
- const Being *const target = localPlayer->getTarget();
- if (target != nullptr)
- {
- target->draw(g, -target->getPixelX() + mapTileSize / 2
- + mDimension.width / 2, -target->getPixelY() + mapTileSize
- + mDimension.height / 2);
- }
- }
- BLOCK_END("DebugWindow::draw")
-}
-
-void DebugWindow::safeDraw(Graphics *const g)
-{
- BLOCK_START("DebugWindow::draw")
- Window::safeDraw(g);
-
- if (localPlayer != nullptr)
- {
- const Being *const target = localPlayer->getTarget();
- if (target != nullptr)
- {
- target->draw(g, -target->getPixelX() + mapTileSize / 2
- + mDimension.width / 2, -target->getPixelY() + mapTileSize
- + mDimension.height / 2);
- }
- }
- BLOCK_END("DebugWindow::draw")
-}
-
-void DebugWindow::widgetResized(const Event &event)
-{
- Window::widgetResized(event);
-
- mTabs->setDimension(Rect(0, 0,
- mDimension.width, mDimension.height));
-}
-
-#ifdef USE_PROFILER
-void DebugWindow::logicChildren()
-{
- BLOCK_START("DebugWindow::logicChildren")
- BasicContainer::logicChildren();
- BLOCK_END("DebugWindow::logicChildren")
-}
-#endif // USE_PROFILER
diff --git a/src/gui/windows/debugwindow.h b/src/gui/windows/debugwindow.h
deleted file mode 100644
index 6350b8820..000000000
--- a/src/gui/windows/debugwindow.h
+++ /dev/null
@@ -1,78 +0,0 @@
-/*
- * The ManaPlus Client
- * Copyright (C) 2004-2009 The Mana World Development Team
- * Copyright (C) 2009-2010 The Mana Developers
- * Copyright (C) 2011-2017 The ManaPlus Developers
- *
- * This file is part of The ManaPlus Client.
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-#ifndef GUI_WINDOWS_DEBUGWINDOW_H
-#define GUI_WINDOWS_DEBUGWINDOW_H
-
-#include "gui/widgets/window.h"
-
-class MapDebugTab;
-class NetDebugTab;
-class TabbedArea;
-class TargetDebugTab;
-
-/**
- * The debug window.
- *
- * \ingroup Interface
- */
-class DebugWindow final : public Window
-{
- public:
- /**
- * Constructor.
- */
- explicit DebugWindow(const std::string &name);
-
- A_DELETE_COPY(DebugWindow)
-
- ~DebugWindow();
-
- void postInit() override final;
-
- /**
- * Logic (updates components' size and infos)
- */
- void slowLogic();
-
- void draw(Graphics *const g) override final A_NONNULL(2);
-
- void safeDraw(Graphics *const g) override final A_NONNULL(2);
-
- void setPing(int pingTime);
-
- void widgetResized(const Event &event) override final;
-
-#ifdef USE_PROFILER
- void logicChildren();
-#endif // USE_PROFILER
-
- private:
- TabbedArea *mTabs A_NONNULLPOINTER;
- MapDebugTab *mMapWidget A_NONNULLPOINTER;
- TargetDebugTab *mTargetWidget A_NONNULLPOINTER;
- NetDebugTab *mNetWidget A_NONNULLPOINTER;
-};
-
-extern DebugWindow *debugWindow;
-
-#endif // GUI_WINDOWS_DEBUGWINDOW_H
diff --git a/src/gui/windows/didyouknowwindow.cpp b/src/gui/windows/didyouknowwindow.cpp
deleted file mode 100644
index adaf6fe2f..000000000
--- a/src/gui/windows/didyouknowwindow.cpp
+++ /dev/null
@@ -1,188 +0,0 @@
-/*
- * The ManaPlus Client
- * Copyright (C) 2004-2009 The Mana World Development Team
- * Copyright (C) 2009-2010 The Mana Developers
- * Copyright (C) 2011-2017 The ManaPlus Developers
- *
- * This file is part of The ManaPlus Client.
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-#include "gui/windows/didyouknowwindow.h"
-
-#include "configuration.h"
-
-#include "enums/gui/layouttype.h"
-
-#include "gui/gui.h"
-
-#include "gui/windows/setupwindow.h"
-
-#include "gui/widgets/button.h"
-#include "gui/widgets/checkbox.h"
-#include "gui/widgets/itemlinkhandler.h"
-#include "gui/widgets/layout.h"
-#include "gui/widgets/scrollarea.h"
-#include "gui/widgets/staticbrowserbox.h"
-
-#include "utils/delete2.h"
-#include "utils/gettext.h"
-
-#include "utils/translation/podict.h"
-#include "utils/translation/translationmanager.h"
-
-#include "debug.h"
-
-DidYouKnowWindow *didYouKnowWindow = nullptr;
-
-static const int minTip = 1;
-static const int maxTip = 18;
-
-DidYouKnowWindow::DidYouKnowWindow() :
- // TRANSLATORS: did you know window name
- Window(_("Did You Know?"), Modal_false, nullptr, "didyouknow.xml"),
- ActionListener(),
- mItemLinkHandler(new ItemLinkHandler),
- mBrowserBox(new StaticBrowserBox(this, Opaque_true,
- "browserbox.xml")),
- mScrollArea(new ScrollArea(this, mBrowserBox,
- Opaque_true, "didyouknow_background.xml")),
- // TRANSLATORS: did you know window button
- mButtonPrev(new Button(this, _("< Previous"), "prev", this)),
- // TRANSLATORS: did you know window button
- mButtonNext(new Button(this, _("Next >"), "next", this)),
- // TRANSLATORS: did you know window checkbox
- mOpenAgainCheckBox(new CheckBox(this, _("Auto open this window"),
- config.getBoolValue("showDidYouKnow"), this, "openagain"))
-{
- setMinWidth(300);
- setMinHeight(220);
- setContentSize(455, 350);
- setWindowName("DidYouKnow");
- setCloseButton(true);
- setResizable(true);
- setStickyButtonLock(true);
-
- if (setupWindow != nullptr)
- setupWindow->registerWindowForReset(this);
- setDefaultSize(500, 400, ImagePosition::CENTER);
-
- mBrowserBox->setOpaque(Opaque_false);
- // TRANSLATORS: did you know window button
- Button *const okButton = new Button(this, _("Close"), "close", this);
-
- mBrowserBox->setLinkHandler(mItemLinkHandler);
- if (gui != nullptr)
- mBrowserBox->setFont(gui->getHelpFont());
- mBrowserBox->setProcessVars(true);
- mBrowserBox->setEnableImages(true);
- mBrowserBox->setEnableKeys(true);
- mBrowserBox->setEnableTabs(true);
-
- place(0, 0, mScrollArea, 5, 3).setPadding(3);
- place(0, 3, mOpenAgainCheckBox, 5);
- place(1, 4, mButtonPrev, 1);
- place(2, 4, mButtonNext, 1);
- place(4, 4, okButton);
-
- Layout &layout = getLayout();
- layout.setRowHeight(0, LayoutType::SET);
-
- loadWindowState();
- enableVisibleSound(true);
-}
-
-void DidYouKnowWindow::postInit()
-{
- Window::postInit();
- widgetResized(Event(nullptr));
-}
-
-DidYouKnowWindow::~DidYouKnowWindow()
-{
- delete2(mItemLinkHandler);
-}
-
-void DidYouKnowWindow::action(const ActionEvent &event)
-{
- const std::string &eventId = event.getId();
- if (eventId == "close")
- {
- setVisible(Visible_false);
- }
- else
- {
- const unsigned num = config.getIntValue("currentTip");
- if (eventId == "prev")
- {
- loadData(num - 1);
- }
- else if (eventId == "next")
- {
- loadData(num + 1);
- }
- else if (eventId == "openagain")
- {
- config.setValue("showDidYouKnow",
- mOpenAgainCheckBox->isSelected());
- }
- }
-}
-
-void DidYouKnowWindow::loadData(int num)
-{
- mBrowserBox->clearRows();
- if (num == 0)
- {
- const int curTip = config.getIntValue("currentTip");
- if (curTip == 1)
- num = maxTip;
- else
- num = curTip + 1;
- }
-
- if (num < minTip || num > maxTip)
- num = minTip;
-
- config.setValue("currentTip", num);
-
- loadFile(num);
-
- mBrowserBox->updateHeight();
- mScrollArea->setVerticalScrollAmount(0);
-}
-
-void DidYouKnowWindow::loadFile(const int num)
-{
- const std::string file = strprintf("tips/%d", num);
- std::string helpPath = branding.getStringValue("helpPath");
- if (helpPath.empty())
- helpPath = paths.getStringValue("help");
-
- StringVect lines;
- TranslationManager::translateFile(pathJoin(helpPath, file).append(".txt"),
- translator, lines);
-
- for (size_t i = 0, sz = lines.size(); i < sz; ++i)
- mBrowserBox->addRow(lines[i]);
-}
-
-void DidYouKnowWindow::setVisible(Visible visible)
-{
- Window::setVisible(visible);
-
- if (visible == Visible_true || isWindowVisible())
- loadData();
-}
diff --git a/src/gui/windows/didyouknowwindow.h b/src/gui/windows/didyouknowwindow.h
deleted file mode 100644
index 6d5fdf1ae..000000000
--- a/src/gui/windows/didyouknowwindow.h
+++ /dev/null
@@ -1,76 +0,0 @@
-/*
- * The ManaPlus Client
- * Copyright (C) 2004-2009 The Mana World Development Team
- * Copyright (C) 2009-2010 The Mana Developers
- * Copyright (C) 2011-2017 The ManaPlus Developers
- *
- * This file is part of The ManaPlus Client.
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-#ifndef GUI_WINDOWS_DIDYOUKNOWWINDOW_H
-#define GUI_WINDOWS_DIDYOUKNOWWINDOW_H
-
-#include "gui/widgets/window.h"
-
-#include "listeners/actionlistener.h"
-
-class Button;
-class CheckBox;
-class ItemLinkHandler;
-class ScrollArea;
-class StaticBrowserBox;
-
-/**
- * The help dialog.
- */
-class DidYouKnowWindow final : public Window,
- public ActionListener
-{
- public:
- /**
- * Constructor.
- */
- DidYouKnowWindow();
-
- ~DidYouKnowWindow();
-
- A_DELETE_COPY(DidYouKnowWindow)
-
- void postInit() override final;
-
- /**
- * Called when receiving actions from the widgets.
- */
- void action(const ActionEvent &event) override final;
-
- void loadData(int num = 0);
-
- void setVisible(Visible visible) override final;
-
- private:
- void loadFile(const int num);
-
- ItemLinkHandler *mItemLinkHandler A_NONNULLPOINTER;
- StaticBrowserBox *mBrowserBox A_NONNULLPOINTER;
- ScrollArea *mScrollArea A_NONNULLPOINTER;
- Button *mButtonPrev A_NONNULLPOINTER;
- Button *mButtonNext A_NONNULLPOINTER;
- CheckBox *mOpenAgainCheckBox A_NONNULLPOINTER;
-};
-
-extern DidYouKnowWindow *didYouKnowWindow;
-
-#endif // GUI_WINDOWS_DIDYOUKNOWWINDOW_H
diff --git a/src/gui/windows/editdialog.cpp b/src/gui/windows/editdialog.cpp
deleted file mode 100644
index e14b96191..000000000
--- a/src/gui/windows/editdialog.cpp
+++ /dev/null
@@ -1,80 +0,0 @@
-/*
- * The ManaPlus Client
- * Copyright (C) 2009 The Mana World Development Team
- * Copyright (C) 2009-2010 Andrei Karas
- * Copyright (C) 2011-2017 The ManaPlus Developers
- *
- * This file is part of The ManaPlus Client.
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-#include "gui/windows/editdialog.h"
-
-#include "gui/widgets/button.h"
-
-#include "utils/foreach.h"
-#include "utils/gettext.h"
-
-#include "debug.h"
-
-EditDialog::EditDialog(const std::string &restrict title,
- const std::string &restrict msg,
- const std::string &restrict eventOk,
- const int width,
- Window *const parent,
- const Modal modal) :
- Window(title, modal, parent, "edit.xml"),
- ActionListener(),
- mEventOk(eventOk),
- mTextField(new TextField(this))
-{
- mDefaultWidth = width;
- mTextField->setText(msg);
-}
-
-void EditDialog::postInit()
-{
- Window::postInit();
- // TRANSLATORS: edit dialog label
- Button *const okButton = new Button(this, _("OK"), mEventOk, this);
-
- const int pad = getPadding();
- const int pad2 = pad * 2;
- mTextField->setPosition(pad, pad);
- mTextField->setWidth(mDefaultWidth - pad2);
- const int buttonPadding = getOption("buttonPadding", 8)
- + mTextField->getHeight();
- setContentSize(mDefaultWidth, okButton->getHeight()
- + buttonPadding + pad2);
- okButton->setPosition((mDefaultWidth - okButton->getWidth()) / 2,
- buttonPadding + pad);
-
- add(mTextField);
- add(okButton);
-
- center();
- setVisible(Visible_true);
- okButton->requestFocus();
-}
-
-void EditDialog::action(const ActionEvent &event)
-{
- // Proxy button events to our listeners
- FOR_EACH (ActionListenerIterator, i, mActionListeners)
- (*i)->action(event);
-
- if (event.getId() == mEventOk)
- scheduleDelete();
-}
diff --git a/src/gui/windows/editdialog.h b/src/gui/windows/editdialog.h
deleted file mode 100644
index cea7d6f78..000000000
--- a/src/gui/windows/editdialog.h
+++ /dev/null
@@ -1,72 +0,0 @@
-/*
- * The ManaPlus Client
- * Copyright (C) 2009 The Mana World Development Team
- * Copyright (C) 2009-2010 Andrei Karas
- * Copyright (C) 2011-2017 The ManaPlus Developers
- *
- * This file is part of The ManaPlus Client.
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-#ifndef GUI_WINDOWS_EDITDIALOG_H
-#define GUI_WINDOWS_EDITDIALOG_H
-
-#include "localconsts.h"
-
-#include "gui/widgets/window.h"
-#include "gui/widgets/textfield.h"
-
-#include "listeners/actionlistener.h"
-
-#define ACTION_EDIT_OK "edit ok"
-
-/**
- * An 'Ok' button dialog.
- *
- * \ingroup GUI
- */
-class EditDialog final : public Window,
- public ActionListener
-{
- public:
- /**
- * Constructor.
- *
- * @see Window::Window
- */
- EditDialog(const std::string &restrict title,
- const std::string &restrict msg,
- const std::string &restrict eventOk = ACTION_EDIT_OK,
- const int width = 300, Window *const parent = nullptr,
- const Modal modal = Modal_true);
-
- A_DELETE_COPY(EditDialog)
-
- void postInit() override final;
-
- /**
- * Called when receiving actions from the widgets.
- */
- void action(const ActionEvent &event) override final;
-
- std::string getMsg() const A_WARN_UNUSED
- { return mTextField->getText(); }
-
- private:
- std::string mEventOk;
- TextField *mTextField A_NONNULLPOINTER;
-};
-
-#endif // GUI_WINDOWS_EDITDIALOG_H
diff --git a/src/gui/windows/editserverdialog.cpp b/src/gui/windows/editserverdialog.cpp
deleted file mode 100644
index 37683caf5..000000000
--- a/src/gui/windows/editserverdialog.cpp
+++ /dev/null
@@ -1,297 +0,0 @@
-/*
- * The ManaPlus Client
- * Copyright (C) 2011-2012 The Mana Developers
- * Copyright (C) 2012-2017 The ManaPlus Developers
- *
- * This file is part of The ManaPlus Client.
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-#include "gui/windows/editserverdialog.h"
-
-#include "const/net/maxpacketversion.h"
-
-#include "gui/models/typelistmodel.h"
-
-#include "gui/windows/okdialog.h"
-#include "gui/windows/serverdialog.h"
-
-#include "gui/widgets/button.h"
-#include "gui/widgets/checkbox.h"
-#include "gui/widgets/createwidget.h"
-#include "gui/widgets/dropdown.h"
-#include "gui/widgets/inttextfield.h"
-#include "gui/widgets/label.h"
-#include "gui/widgets/layout.h"
-
-#include "utils/gettext.h"
-
-#include "debug.h"
-
-EditServerDialog::EditServerDialog(ServerDialog *const parent,
- const ServerInfo &server,
- const int index) :
- // TRANSLATORS: edit server dialog name
- Window(_("Edit Server"), Modal_true, parent),
- ActionListener(),
- KeyListener(),
- mServerAddressField(new TextField(this, std::string())),
- mPortField(new TextField(this, std::string())),
- mNameField(new TextField(this, std::string())),
- mDescriptionField(new TextField(this, std::string())),
- mOnlineListUrlField(new TextField(this, std::string())),
- mPacketVersionField(new IntTextField(this, 0, 0, maxPacketVersion)),
- // TRANSLATORS: edit server dialog button
- mConnectButton(new Button(this, _("Connect"), "connect", this)),
- // TRANSLATORS: edit server dialog button
- mOkButton(new Button(this, _("OK"), "addServer", this)),
- // TRANSLATORS: edit server dialog button
- mCancelButton(new Button(this, _("Cancel"), "cancel", this)),
- // TRANSLATORS: edit server dialog label
- mPersistentIp(new CheckBox(this, _("Use same ip"),
- true, this, "persistentIp")),
- mTypeListModel(new TypeListModel),
- mTypeField(new DropDown(this, mTypeListModel, false, Modal_true)),
- mServerDialog(parent),
- mServer(server),
- mIndex(index)
-{
- setWindowName("EditServerDialog");
-
- // TRANSLATORS: edit server dialog label
- Label *const nameLabel = new Label(this, _("Name:"));
- // TRANSLATORS: edit server dialog label
- Label *const serverAdressLabel = new Label(this, _("Address:"));
- // TRANSLATORS: edit server dialog label
- Label *const portLabel = new Label(this, _("Port:"));
- // TRANSLATORS: edit server dialog label
- Label *const typeLabel = new Label(this, _("Server type:"));
- // TRANSLATORS: edit server dialog label
- Label *const descriptionLabel = new Label(this, _("Description:"));
- // TRANSLATORS: edit server dialog label
- Label *const onlineListUrlLabel = new Label(this, _("Online list url:"));
- // TRANSLATORS: edit server dialog label
- Label *const packetVersionLabel = new Label(this, _("Packet version:"));
- mPortField->setNumeric(true);
- mPortField->setRange(1, 65535);
-
- mTypeField->setSelected(0); // TmwAthena by default
-
- mServerAddressField->addActionListener(this);
- mPortField->addActionListener(this);
-
- place(0, 0, nameLabel);
- place(1, 0, mNameField, 4).setPadding(3);
- place(0, 1, serverAdressLabel);
- place(1, 1, mServerAddressField, 4).setPadding(3);
- place(0, 2, portLabel);
- place(1, 2, mPortField, 4).setPadding(3);
- place(0, 3, typeLabel);
- place(1, 3, mTypeField).setPadding(3);
- place(0, 4, descriptionLabel);
- place(1, 4, mDescriptionField, 4).setPadding(3);
- place(0, 5, onlineListUrlLabel);
- place(1, 5, mOnlineListUrlField, 4).setPadding(3);
- place(0, 6, packetVersionLabel);
- place(1, 6, mPacketVersionField, 4).setPadding(3);
- place(0, 7, mPersistentIp, 4).setPadding(3);
- place(0, 8, mConnectButton);
- place(4, 8, mOkButton);
- place(3, 8, mCancelButton);
-
- // Do this manually instead of calling reflowLayout so we can enforce a
- // minimum width.
- int width = 0;
- int height = 0;
- getLayout().reflow(width, height);
- if (width < 300)
- {
- width = 300;
- getLayout().reflow(width, height);
- }
- if (height < 120)
- {
- height = 120;
- getLayout().reflow(width, height);
- }
-
- setContentSize(width, height);
-
- setMinWidth(getWidth());
- setMinHeight(getHeight());
- setDefaultSize(getWidth(), getHeight(), ImagePosition::CENTER);
-
- setResizable(false);
- addKeyListener(this);
-
- loadWindowState();
-
- mNameField->setText(mServer.name);
- mDescriptionField->setText(mServer.description);
- mOnlineListUrlField->setText(mServer.onlineListUrl);
- mServerAddressField->setText(mServer.hostname);
- mPacketVersionField->setValue(mServer.packetVersion);
- mPortField->setText(toString(mServer.port));
- mPersistentIp->setSelected(mServer.persistentIp);
-
- switch (mServer.type)
- {
- case ServerType::EATHENA:
-#ifdef TMWA_SUPPORT
- mTypeField->setSelected(1);
-#else // TMWA_SUPPORT
- mTypeField->setSelected(0);
-#endif // TMWA_SUPPORT
- break;
- default:
- case ServerType::UNKNOWN:
- case ServerType::TMWATHENA:
- mTypeField->setSelected(0);
- break;
- case ServerType::EVOL2:
-#ifdef TMWA_SUPPORT
- mTypeField->setSelected(2);
-#else // TMWA_SUPPORT
- mTypeField->setSelected(1);
-#endif // TMWA_SUPPORT
- break;
- }
-
- setLocationRelativeTo(getParentWindow());
-}
-
-EditServerDialog::~EditServerDialog()
-{
- delete mTypeListModel;
-}
-
-void EditServerDialog::postInit()
-{
- Window::postInit();
- setVisible(Visible_true);
- mNameField->requestFocus();
-}
-
-void EditServerDialog::action(const ActionEvent &event)
-{
- const std::string &eventId = event.getId();
-
- if (eventId == "ok")
- {
- // Give focus back to the server dialog.
- mServerAddressField->requestFocus();
- }
- if (eventId == "addServer" || eventId == "connect")
- {
- // Check the given information
- if (mServerAddressField->getText().empty()
- || mPortField->getText().empty())
- {
- OkDialog *const dlg = CREATEWIDGETR(OkDialog,
- // TRANSLATORS: edit server dialog error header
- _("Error"),
- // TRANSLATORS: edit server dialog error message
- _("Please at least type both the address and the port "
- "of the server."),
- // TRANSLATORS: ok dialog button
- _("OK"),
- DialogType::ERROR,
- Modal_true,
- ShowCenter_true,
- nullptr,
- 260);
- dlg->addActionListener(this);
- }
- else
- {
- mCancelButton->setEnabled(false);
- mOkButton->setEnabled(false);
-
- mServer.name = mNameField->getText();
- mServer.description = mDescriptionField->getText();
- mServer.onlineListUrl = mOnlineListUrlField->getText();
- mServer.hostname = mServerAddressField->getText();
- mServer.packetVersion = mPacketVersionField->getValue();
- mServer.port = CAST_S16(atoi(
- mPortField->getText().c_str()));
- mServer.persistentIp = mPersistentIp->isSelected();
-
- if (mTypeField != nullptr)
- {
- switch (mTypeField->getSelected())
- {
-#ifdef TMWA_SUPPORT
- case 0:
- mServer.type = ServerType::TMWATHENA;
- break;
- case 1:
- mServer.type = ServerType::EATHENA;
- break;
- case 2:
- mServer.type = ServerType::EVOL2;
- break;
-#else // TMWA_SUPPORT
-
- case 0:
- mServer.type = ServerType::EATHENA;
- break;
- case 1:
- mServer.type = ServerType::EVOL2;
- break;
-#endif // TMWA_SUPPORT
-
- default:
- mServer.type = ServerType::UNKNOWN;
- break;
- }
- }
- else
- {
- mServer.type = ServerType::TMWATHENA;
- }
-
- // Tell the server has to be saved
- mServer.save = true;
-
- // Add server
- mServerDialog->updateServer(mServer, mIndex);
- if (eventId == "connect")
- mServerDialog->connectToSelectedServer();
- scheduleDelete();
- }
- }
- else if (eventId == "cancel")
- {
- scheduleDelete();
- }
-}
-
-void EditServerDialog::keyPressed(KeyEvent &event)
-{
- if (event.isConsumed())
- return;
-
- const InputActionT actionId = event.getActionId();
-
- if (actionId == InputAction::GUI_CANCEL)
- {
- scheduleDelete();
- }
- else if (actionId == InputAction::GUI_SELECT ||
- actionId == InputAction::GUI_SELECT2)
- {
- action(ActionEvent(nullptr, mOkButton->getActionEventId()));
- }
-}
diff --git a/src/gui/windows/editserverdialog.h b/src/gui/windows/editserverdialog.h
deleted file mode 100644
index e53632c00..000000000
--- a/src/gui/windows/editserverdialog.h
+++ /dev/null
@@ -1,86 +0,0 @@
-/*
- * The ManaPlus Client
- * Copyright (C) 2011-2012 The Mana Developers
- * Copyright (C) 2012-2017 The ManaPlus Developers
- *
- * This file is part of The ManaPlus Client.
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-#ifndef GUI_WINDOWS_EDITSERVERDIALOG_H
-#define GUI_WINDOWS_EDITSERVERDIALOG_H
-
-class Button;
-class CheckBox;
-class DropDown;
-class IntTextField;
-class ServerDialog;
-class TextField;
-class TypeListModel;
-
-#include "gui/widgets/window.h"
-
-#include "net/serverinfo.h"
-
-#include "listeners/actionlistener.h"
-#include "listeners/keylistener.h"
-
-/**
- * The custom server addition dialog.
- *
- * \ingroup Interface
- */
-class EditServerDialog final : public Window,
- public ActionListener,
- public KeyListener
-{
- public:
- EditServerDialog(ServerDialog *const parent,
- const ServerInfo &server,
- const int index);
-
- A_DELETE_COPY(EditServerDialog)
-
- ~EditServerDialog();
-
- void postInit() override final;
-
- /**
- * Called when receiving actions from the widgets.
- */
- void action(const ActionEvent &event) override final;
-
- void keyPressed(KeyEvent &event) override final;
-
- private:
- TextField *mServerAddressField A_NONNULLPOINTER;
- TextField *mPortField A_NONNULLPOINTER;
- TextField *mNameField A_NONNULLPOINTER;
- TextField *mDescriptionField A_NONNULLPOINTER;
- TextField *mOnlineListUrlField A_NONNULLPOINTER;
- IntTextField *mPacketVersionField A_NONNULLPOINTER;
- Button *mConnectButton A_NONNULLPOINTER;
- Button *mOkButton A_NONNULLPOINTER;
- Button *mCancelButton A_NONNULLPOINTER;
- CheckBox *mPersistentIp A_NONNULLPOINTER;
- TypeListModel *mTypeListModel A_NONNULLPOINTER;
- DropDown *mTypeField A_NONNULLPOINTER;
-
- ServerDialog *mServerDialog;
- ServerInfo mServer;
- int mIndex;
-};
-
-#endif // GUI_WINDOWS_EDITSERVERDIALOG_H
diff --git a/src/gui/windows/eggselectiondialog.cpp b/src/gui/windows/eggselectiondialog.cpp
deleted file mode 100644
index 5e77d8ec1..000000000
--- a/src/gui/windows/eggselectiondialog.cpp
+++ /dev/null
@@ -1,67 +0,0 @@
-/*
- * The ManaPlus Client
- * Copyright (C) 2004-2009 The Mana World Development Team
- * Copyright (C) 2009-2010 The Mana Developers
- * Copyright (C) 2011-2017 The ManaPlus Developers
- *
- * This file is part of The ManaPlus Client.
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-#include "gui/windows/eggselectiondialog.h"
-
-#include "gui/models/shopitems.h"
-
-#include "gui/widgets/button.h"
-#include "gui/widgets/shoplistbox.h"
-
-#include "net/inventoryhandler.h"
-
-#include "utils/gettext.h"
-
-#include "resources/item/shopitem.h"
-
-#include "debug.h"
-
-EggSelectionDialog::EggSelectionDialog() :
- SellDialog(IsSell_false, Advanced_false)
-{
- // TRANSLATORS: egg selection dialog name
- setWindowName(_("Select egg"));
- // TRANSLATORS: egg selection dialog name
- setCaption(_("Select egg"));
-}
-
-void EggSelectionDialog::initButtons()
-{
- logger->log("EggSelectionDialog::initButtons");
- // TRANSLATORS: egg selection dialog button
- mSellButton->setCaption(_("Select"));
- mSellButton->adjustSize();
- mShopItems->setMergeDuplicates(false);
-}
-
-void EggSelectionDialog::sellAction(const ActionEvent &event A_UNUSED)
-{
- if (mAmountItems <= 0 || mAmountItems > mMaxItems)
- return;
-
- const int selectedItem = mShopItemList->getSelected();
- const ShopItem *const item = mShopItems->at(selectedItem);
- if (item == nullptr)
- return;
- inventoryHandler->selectEgg(item);
- scheduleDelete();
-}
diff --git a/src/gui/windows/eggselectiondialog.h b/src/gui/windows/eggselectiondialog.h
deleted file mode 100644
index 14d91a699..000000000
--- a/src/gui/windows/eggselectiondialog.h
+++ /dev/null
@@ -1,45 +0,0 @@
-/*
- * The ManaPlus Client
- * Copyright (C) 2004-2009 The Mana World Development Team
- * Copyright (C) 2009-2010 The Mana Developers
- * Copyright (C) 2011-2017 The ManaPlus Developers
- *
- * This file is part of The ManaPlus Client.
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-#ifndef GUI_WINDOWS_EGGSELECTIONDIALOG_H
-#define GUI_WINDOWS_EGGSELECTIONDIALOG_H
-
-#include "gui/widgets/selldialog.h"
-
-class EggSelectionDialog final : public SellDialog
-{
- public:
- /**
- * Constructor.
- *
- * @see Window::Window
- */
- EggSelectionDialog();
-
- A_DELETE_COPY(EggSelectionDialog)
-
- protected:
- void initButtons() override final;
- void sellAction(const ActionEvent &event) override final;
-};
-
-#endif // GUI_WINDOWS_EGGSELECTIONDIALOG_H
diff --git a/src/gui/windows/emotewindow.cpp b/src/gui/windows/emotewindow.cpp
deleted file mode 100644
index f4f720535..000000000
--- a/src/gui/windows/emotewindow.cpp
+++ /dev/null
@@ -1,278 +0,0 @@
-/*
- * The ManaPlus Client
- * Copyright (C) 2013-2017 The ManaPlus Developers
- *
- * This file is part of The ManaPlus Client.
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-#include "gui/windows/emotewindow.h"
-
-#include "gui/models/colormodel.h"
-#include "gui/models/namesmodel.h"
-
-#include "gui/windows/setupwindow.h"
-
-#include "gui/widgets/colorpage.h"
-#include "gui/widgets/createwidget.h"
-#include "gui/widgets/emotepage.h"
-#include "gui/widgets/scrollarea.h"
-#include "gui/widgets/tabbedarea.h"
-
-#include "utils/delete2.h"
-#include "utils/foreach.h"
-#include "utils/gettext.h"
-
-#include "utils/translation/podict.h"
-
-#include "resources/imageset.h"
-
-#include "resources/db/textdb.h"
-
-#include "resources/image/image.h"
-
-#include "debug.h"
-
-EmoteWindow *emoteWindow = nullptr;
-static const int fontSizeListSize = 2;
-
-static const char *const fontSizeList[] =
-{
- // TRANSLATORS: font size
- N_("Normal font"),
- // TRANSLATORS: font size
- N_("Bold font"),
-};
-
-EmoteWindow::EmoteWindow() :
- // TRANSLATORS: emotes window name
- Window(_("Emotes"), Modal_false, nullptr, "emotes.xml"),
- mTabs(CREATEWIDGETR(TabbedArea, this)),
- mEmotePage(new EmotePage(this)),
- mColorModel(ColorModel::createDefault(this)),
- mColorPage(CREATEWIDGETR(ColorPage, this, mColorModel, "colorpage.xml")),
- mScrollColorPage(new ScrollArea(this, mColorPage, Opaque_false,
- "emotepage.xml")),
- mFontModel(new NamesModel),
- mFontPage(CREATEWIDGETR(ListBox, this, mFontModel, "")),
- mScrollFontPage(new ScrollArea(this, mFontPage, Opaque_false,
- "fontpage.xml")),
- mTextModel(new NamesModel),
- mTextPage(CREATEWIDGETR(ListBox, this, mTextModel, "")),
- mScrollTextPage(new ScrollArea(this, mTextPage, Opaque_false,
- "textpage.xml")),
- mImageSet(Theme::getImageSetFromThemeXml("emotetabs.xml", "", 17, 16))
-{
- setShowTitle(false);
- setResizable(true);
-
- if (setupWindow != nullptr)
- setupWindow->registerWindowForReset(this);
-
- addMouseListener(this);
-}
-
-void EmoteWindow::postInit()
-{
- Window::postInit();
- const int pad2 = mPadding * 2;
- const int width = 200;
- const int height = 150;
- setWidth(width + pad2);
- setHeight(height + pad2);
- add(mTabs);
- mTabs->setPosition(mPadding, mPadding);
- mTabs->setWidth(width);
- mTabs->setHeight(height);
- center();
-
- setTitleBarHeight(getPadding() + getTitlePadding());
- mScrollColorPage->setVerticalScrollPolicy(ScrollArea::SHOW_ALWAYS);
- mScrollColorPage->setHorizontalScrollPolicy(ScrollArea::SHOW_NEVER);
- mScrollFontPage->setVerticalScrollPolicy(ScrollArea::SHOW_NEVER);
- mScrollFontPage->setHorizontalScrollPolicy(ScrollArea::SHOW_NEVER);
- mScrollTextPage->setVerticalScrollPolicy(ScrollArea::SHOW_NEVER);
- mScrollTextPage->setHorizontalScrollPolicy(ScrollArea::SHOW_NEVER);
-
- mFontModel->fillFromArray(&fontSizeList[0], fontSizeListSize);
-
- mFontPage->setCenter(true);
- mTextPage->setCenter(true);
-
- if ((mImageSet != nullptr) && mImageSet->size() >= 3)
- {
- for (int f = 0; f < 3; f ++)
- {
- Image *const image = mImageSet->get(f);
- if (image != nullptr)
- image->incRef();
- }
-
- mTabs->addTab(mImageSet->get(0), mEmotePage);
- mTabs->addTab(mImageSet->get(2), mScrollColorPage);
- mTabs->addTab(mImageSet->get(1), mScrollFontPage);
- }
- else
- {
- // TRANSLATORS: emotes tab name
- mTabs->addTab(_("Emotes"), mEmotePage);
- // TRANSLATORS: emotes tab name
- mTabs->addTab(_("Colors"), mScrollColorPage);
- // TRANSLATORS: emotes tab name
- mTabs->addTab(_("Fonts"), mScrollFontPage);
- }
- // TRANSLATORS: emotes tab name
- mTabs->addTab(_("T"), mScrollTextPage);
-
- mEmotePage->setActionEventId("emote");
- mColorPage->setActionEventId("color");
- mFontPage->setActionEventId("font");
- mTextPage->setActionEventId("text");
-}
-
-EmoteWindow::~EmoteWindow()
-{
- mTabs->removeAll(false);
- mTabs->removeTab(mTabs->getTabByIndex(0));
- delete2(mEmotePage);
- delete2(mColorPage);
- delete2(mColorModel);
- delete2(mScrollColorPage);
- delete2(mFontPage);
- delete2(mFontModel);
- delete2(mScrollFontPage);
- delete2(mTextPage);
- delete2(mTextModel);
- delete2(mScrollTextPage);
- if (mImageSet != nullptr)
- {
- mImageSet->decRef();
- mImageSet = nullptr;
- }
-}
-
-void EmoteWindow::show()
-{
- setVisible(Visible_true);
- if (dictionary != nullptr)
- {
- mTextModel->clear();
- const STD_VECTOR<std::string> &texts = TextDb::getTexts();
- FOR_EACH (StringVectCIter, it, texts)
- {
- mTextModel->add(dictionary->getStr(*it));
- }
- }
-}
-
-void EmoteWindow::hide()
-{
- setVisible(Visible_false);
-}
-
-std::string EmoteWindow::getSelectedEmote() const
-{
- const int index = mEmotePage->getSelectedIndex();
- if (index < 0)
- return std::string();
-
- char chr[2];
- chr[0] = CAST_8('0' + index);
- chr[1] = 0;
- return std::string("%%").append(&chr[0]);
-}
-
-void EmoteWindow::clearEmote()
-{
- const int index = mEmotePage->getSelectedIndex();
- mEmotePage->resetAction();
- if (index >= 0)
- setVisible(Visible_false);
-}
-
-std::string EmoteWindow::getSelectedColor() const
-{
- const int index = mColorPage->getSelected();
- if (index < 0)
- return std::string();
-
- char chr[2];
- chr[0] = CAST_8('0' + index);
- chr[1] = 0;
- return std::string("##").append(&chr[0]);
-}
-
-int EmoteWindow::getSelectedTextIndex() const
-{
- return mTextPage->getSelected();
-}
-
-void EmoteWindow::clearColor()
-{
- mColorPage->resetAction();
- setVisible(Visible_false);
-}
-
-std::string EmoteWindow::getSelectedFont() const
-{
- const int index = mFontPage->getSelected();
- if (index < 0)
- return std::string();
-
- if (index == 0)
- return "##b";
- return "##B";
-}
-
-void EmoteWindow::clearFont()
-{
- mFontPage->setSelected(-1);
- setVisible(Visible_false);
-}
-
-void EmoteWindow::clearText()
-{
- mTextPage->setSelected(-1);
- setVisible(Visible_false);
-}
-
-void EmoteWindow::addListeners(ActionListener *const listener)
-{
- mEmotePage->addActionListener(listener);
- mColorPage->addActionListener(listener);
- mFontPage->addActionListener(listener);
- mTextPage->addActionListener(listener);
-}
-
-void EmoteWindow::widgetResized(const Event &event)
-{
- Window::widgetResized(event);
- const int pad2 = mPadding * 2;
- const int width = mDimension.width;
- const int height = mDimension.height;
-
- mTabs->setSize(width - pad2, height - pad2);
- mTabs->adjustWidget(mEmotePage);
- mTabs->adjustWidget(mScrollColorPage);
- mColorPage->setSize(mScrollColorPage->getWidth(),
- mScrollColorPage->getHeight());
- mEmotePage->widgetResized(event);
-}
-
-void EmoteWindow::widgetMoved(const Event &event)
-{
- Window::widgetMoved(event);
- mEmotePage->widgetResized(event);
-}
diff --git a/src/gui/windows/emotewindow.h b/src/gui/windows/emotewindow.h
deleted file mode 100644
index 66fb0c83c..000000000
--- a/src/gui/windows/emotewindow.h
+++ /dev/null
@@ -1,89 +0,0 @@
-/*
- * The ManaPlus Client
- * Copyright (C) 2013-2017 The ManaPlus Developers
- *
- * This file is part of The ManaPlus Client.
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-#ifndef GUI_WINDOWS_EMOTEWINDOW_H
-#define GUI_WINDOWS_EMOTEWINDOW_H
-
-#include "gui/widgets/window.h"
-
-class ColorModel;
-class ColorPage;
-class EmotePage;
-class ImageSet;
-class ListBox;
-class NamesModel;
-class ScrollArea;
-class TabbedArea;
-
-class EmoteWindow final : public Window
-{
- public:
- EmoteWindow();
-
- A_DELETE_COPY(EmoteWindow)
-
- ~EmoteWindow();
-
- void postInit() override final;
-
- void show();
-
- void hide();
-
- std::string getSelectedEmote() const;
-
- void clearEmote();
-
- std::string getSelectedColor() const;
-
- void clearColor();
-
- std::string getSelectedFont() const;
-
- int getSelectedTextIndex() const;
-
- void clearFont();
-
- void clearText();
-
- void addListeners(ActionListener *const listener);
-
- void widgetResized(const Event &event) override final;
-
- void widgetMoved(const Event &event) override final;
-
- private:
- TabbedArea *mTabs A_NONNULLPOINTER;
- EmotePage *mEmotePage A_NONNULLPOINTER;
- ColorModel *mColorModel A_NONNULLPOINTER;
- ColorPage *mColorPage A_NONNULLPOINTER;
- ScrollArea *mScrollColorPage A_NONNULLPOINTER;
- NamesModel *mFontModel A_NONNULLPOINTER;
- ListBox *mFontPage A_NONNULLPOINTER;
- ScrollArea *mScrollFontPage A_NONNULLPOINTER;
- NamesModel *mTextModel A_NONNULLPOINTER;
- ListBox *mTextPage A_NONNULLPOINTER;
- ScrollArea *mScrollTextPage A_NONNULLPOINTER;
- ImageSet *mImageSet;
-};
-
-extern EmoteWindow *emoteWindow;
-
-#endif // GUI_WINDOWS_EMOTEWINDOW_H
diff --git a/src/gui/windows/equipmentwindow.cpp b/src/gui/windows/equipmentwindow.cpp
deleted file mode 100644
index a859ef02b..000000000
--- a/src/gui/windows/equipmentwindow.cpp
+++ /dev/null
@@ -1,848 +0,0 @@
-/*
- * The ManaPlus Client
- * Copyright (C) 2004-2009 The Mana World Development Team
- * Copyright (C) 2009-2010 The Mana Developers
- * Copyright (C) 2011-2017 The ManaPlus Developers
- *
- * This file is part of The ManaPlus Client.
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-#include "gui/windows/equipmentwindow.h"
-
-#include "configuration.h"
-#include "dragdrop.h"
-
-#include "being/localplayer.h"
-#include "being/playerinfo.h"
-
-#include "gui/fonts/font.h"
-
-#include "gui/popups/popupmenu.h"
-#include "gui/popups/itempopup.h"
-
-#include "gui/windows/setupwindow.h"
-
-#include "gui/widgets/button.h"
-#include "gui/widgets/equipmentbox.h"
-#include "gui/widgets/equipmentpage.h"
-#include "gui/widgets/playerbox.h"
-#include "gui/widgets/tabstrip.h"
-
-#include "render/vertexes/imagecollection.h"
-
-#include "resources/imageset.h"
-
-#include "utils/checkutils.h"
-#include "utils/delete2.h"
-#include "utils/dtor.h"
-#include "utils/foreach.h"
-#include "utils/gettext.h"
-
-#include "net/inventoryhandler.h"
-
-#include "debug.h"
-
-EquipmentWindow *equipmentWindow = nullptr;
-EquipmentWindow *beingEquipmentWindow = nullptr;
-static const int BOX_COUNT = 27;
-StringIntMap EquipmentWindow::mSlotNames;
-
-EquipmentWindow::EquipmentWindow(Equipment *const equipment,
- Being *const being,
- const bool foring) :
- // TRANSLATORS: equipment window name
- Window(_("Equipment"), Modal_false, nullptr, "equipment.xml"),
- ActionListener(),
- mEquipment(equipment),
- mPlayerBox(new PlayerBox(this,
- "equipment_playerbox.xml",
- "equipment_selectedplayerbox.xml")),
- // TRANSLATORS: equipment window button
- mUnequip(new Button(this, _("Unequip"), "unequip", this)),
- mImageSet(nullptr),
- mBeing(being),
- mSlotBackground(),
- mSlotHighlightedBackground(),
- mVertexes(new ImageCollection),
- mPages(),
- mTabs(nullptr),
- mHighlightColor(getThemeColor(ThemeColorId::HIGHLIGHT)),
- mBorderColor(getThemeColor(ThemeColorId::BORDER)),
- mLabelsColor(getThemeColor(ThemeColorId::LABEL)),
- mLabelsColor2(getThemeColor(ThemeColorId::LABEL_OUTLINE)),
- mSelected(-1),
- mItemPadding(getOption("itemPadding")),
- mBoxSize(getOption("boxSize")),
- mButtonPadding(getOption("buttonPadding", 5)),
- mMinX(180),
- mMinY(345),
- mMaxX(0),
- mMaxY(0),
- mYPadding(0),
- mSelectedTab(0),
- mForing(foring),
- mHaveDefaultPage(false)
-{
- const int size = config.getIntValue("fontSize")
- + getOption("tabHeightAdjust", 16);
- mTabs = new TabStrip(this, "equipment", size);
- mTabs->addActionListener(this);
- mTabs->setActionEventId("tab_");
- mTabs->setSelectable(false);
-
- mYPadding = mTabs->getHeight() + getOption("tabPadding", 2);
-
- if (setupWindow != nullptr)
- setupWindow->registerWindowForReset(this);
-
- if (mBoxSize == 0)
- mBoxSize = 36;
-
- // Control that shows the Player
- mPlayerBox->setDimension(Rect(50, 80 + mYPadding, 74, 168));
- mPlayerBox->setPlayer(being);
- mPlayerBox->setSelectable(false);
-
- if (foring)
- setWindowName("Being equipment");
- else
- setWindowName("Equipment");
-
- setCloseButton(true);
- setSaveVisible(true);
- setStickyButtonLock(true);
-
- fillBoxes();
- recalcSize();
- updatePage();
- loadWindowState();
-}
-
-void EquipmentWindow::postInit()
-{
- Window::postInit();
- const Rect &area = getChildrenArea();
- mUnequip->setPosition(area.width - mUnequip->getWidth() - mButtonPadding,
- area.height - mUnequip->getHeight() - mButtonPadding);
- mUnequip->setEnabled(false);
-
- ImageRect rect;
- theme->loadRect(rect, "equipment_background.xml", "", 0, 1);
- mSlotBackground = rect.grid[0];
- mSlotHighlightedBackground = rect.grid[1];
- add(mTabs);
- add(mPlayerBox);
- add(mUnequip);
- enableVisibleSound(true);
- mPlayerBox->setActionEventId("playerbox");
- mPlayerBox->addActionListener(this);
-}
-
-EquipmentWindow::~EquipmentWindow()
-{
- if (this == beingEquipmentWindow)
- {
- if (mEquipment != nullptr)
- delete mEquipment->getBackend();
- delete2(mEquipment)
- }
- FOR_EACH (STD_VECTOR<EquipmentPage*>::iterator, it, mPages)
- {
- STD_VECTOR<EquipmentBox*> &boxes = (*it)->boxes;
- delete_all(boxes);
- boxes.clear();
- delete *it;
- }
- if (mImageSet != nullptr)
- {
- mImageSet->decRef();
- mImageSet = nullptr;
- }
- if (mSlotBackground != nullptr)
- mSlotBackground->decRef();
- if (mSlotHighlightedBackground != nullptr)
- mSlotHighlightedBackground->decRef();
- delete2(mVertexes);
-}
-
-void EquipmentWindow::draw(Graphics *const graphics)
-{
- BLOCK_START("EquipmentWindow::draw")
- // Draw window graphics
- Window::draw(graphics);
-
- int i = 0;
- Font *const font = getFont();
- const int fontHeight = font->getHeight();
- const STD_VECTOR<EquipmentBox*> &boxes = mPages[mSelectedTab]->boxes;
-
- if (mLastRedraw)
- {
- mVertexes->clear();
- FOR_EACH (STD_VECTOR<EquipmentBox*>::const_iterator, it, boxes)
- {
- const EquipmentBox *const box = *it;
- if (box == nullptr)
- {
- i ++;
- continue;
- }
- if (i == mSelected)
- {
- graphics->calcTileCollection(mVertexes,
- mSlotHighlightedBackground,
- box->x, box->y);
- }
- else
- {
- graphics->calcTileCollection(mVertexes,
- mSlotBackground,
- box->x, box->y);
- }
- i ++;
- }
- graphics->finalize(mVertexes);
- }
- graphics->drawTileCollection(mVertexes);
-
- if (mEquipment == nullptr)
- {
- BLOCK_END("EquipmentWindow::draw")
- return;
- }
-
- i = 0;
- const int projSlot = inventoryHandler->getProjectileSlot();
- for (STD_VECTOR<EquipmentBox*>::const_iterator it = boxes.begin(),
- it_end = boxes.end(); it != it_end; ++ it, ++ i)
- {
- const EquipmentBox *const box = *it;
- if (box == nullptr)
- continue;
- const Item *const item = mEquipment->getEquipment(i);
- if (item != nullptr)
- {
- // Draw Item.
- Image *const image = item->getImage();
- if (image != nullptr)
- {
- image->setAlpha(1.0F); // Ensure the image is drawn
- // with maximum opacity
- graphics->drawImage(image, box->x + mItemPadding,
- box->y + mItemPadding);
- if (i == projSlot)
- {
- const std::string str = toString(item->getQuantity());
- font->drawString(graphics,
- mLabelsColor,
- mLabelsColor2,
- str,
- box->x + (mBoxSize - font->getWidth(str)) / 2,
- box->y - fontHeight);
- }
- }
- }
- else if (box->image != nullptr)
- {
- graphics->drawImage(box->image,
- box->x + mItemPadding,
- box->y + mItemPadding);
- }
- }
- BLOCK_END("EquipmentWindow::draw")
-}
-
-void EquipmentWindow::safeDraw(Graphics *const graphics)
-{
- BLOCK_START("EquipmentWindow::draw")
- // Draw window graphics
- Window::safeDraw(graphics);
-
- int i = 0;
- Font *const font = getFont();
- const int fontHeight = font->getHeight();
- const STD_VECTOR<EquipmentBox*> &boxes = mPages[mSelectedTab]->boxes;
-
- for (STD_VECTOR<EquipmentBox*>::const_iterator it = boxes.begin(),
- it_end = boxes.end(); it != it_end; ++ it, ++ i)
- {
- const EquipmentBox *const box = *it;
- if (box == nullptr)
- continue;
- if (i == mSelected)
- {
- graphics->drawImage(mSlotHighlightedBackground,
- box->x, box->y);
- }
- else
- {
- graphics->drawImage(mSlotBackground, box->x, box->y);
- }
- }
-
- if (mEquipment == nullptr)
- {
- BLOCK_END("EquipmentWindow::draw")
- return;
- }
-
- i = 0;
- const int projSlot = inventoryHandler->getProjectileSlot();
- for (STD_VECTOR<EquipmentBox*>::const_iterator it = boxes.begin(),
- it_end = boxes.end(); it != it_end; ++ it, ++ i)
- {
- const EquipmentBox *const box = *it;
- if (box == nullptr)
- continue;
- const Item *const item = mEquipment->getEquipment(i);
- if (item != nullptr)
- {
- // Draw Item.
- Image *const image = item->getImage();
- if (image != nullptr)
- {
- image->setAlpha(1.0F); // Ensure the image is drawn
- // with maximum opacity
- graphics->drawImage(image, box->x + mItemPadding,
- box->y + mItemPadding);
- if (i == projSlot)
- {
- const std::string str = toString(item->getQuantity());
- font->drawString(graphics,
- mLabelsColor,
- mLabelsColor2,
- str,
- box->x + (mBoxSize - font->getWidth(str)) / 2,
- box->y - fontHeight);
- }
- }
- }
- else if (box->image != nullptr)
- {
- graphics->drawImage(box->image,
- box->x + mItemPadding,
- box->y + mItemPadding);
- }
- }
- BLOCK_END("EquipmentWindow::draw")
-}
-
-void EquipmentWindow::action(const ActionEvent &event)
-{
- const std::string &eventId = event.getId();
- if (eventId == "unequip")
- {
- if ((mEquipment == nullptr) || mSelected == -1)
- return;
-
- const Item *const item = mEquipment->getEquipment(mSelected);
- PlayerInfo::unequipItem(item, Sfx_true);
- setSelected(-1);
- }
- else if (eventId.find("tab_") == 0u)
- {
- Button *const button = dynamic_cast<Button*>(event.getSource());
- if (button == nullptr)
- return;
- mSelectedTab = button->getTag();
- updatePage();
- }
- else if (eventId == "playerbox")
- {
- const DragDropSourceT src = dragDrop.getSource();
- if (dragDrop.isEmpty() || (src != DragDropSource::Inventory
- && src != DragDropSource::Equipment))
- {
- return;
- }
- Inventory *const inventory = localPlayer != nullptr
- ? PlayerInfo::getInventory() : nullptr;
- if (inventory == nullptr)
- return;
- Item *const item = inventory->findItem(dragDrop.getItem(),
- dragDrop.getItemColor());
- if (item == nullptr)
- return;
-
- if (dragDrop.getSource() == DragDropSource::Inventory)
- {
- if (item->isEquipment() == Equipm_true)
- {
- if (item->isEquipped() == Equipped_false)
- PlayerInfo::equipItem(item, Sfx_true);
- }
- }
- }
-}
-
-void EquipmentWindow::updatePage()
-{
- EquipmentPage *const page = mPages[mSelectedTab];
- const Visible visible = fromBool(page->showPlayerBox, Visible);
- mPlayerBox->setVisible(visible);
- if (visible == Visible_true)
- {
- mPlayerBox->setDimension(Rect(page->x, page->y,
- page->width, page->height));
- }
- mRedraw = true;
-}
-
-const Item *EquipmentWindow::getItem(const int x, const int y) const
-{
- if (mEquipment == nullptr)
- return nullptr;
-
- int i = 0;
-
- STD_VECTOR<EquipmentBox*> &boxes = mPages[mSelectedTab]->boxes;
- for (STD_VECTOR<EquipmentBox*>::const_iterator it = boxes.begin(),
- it_end = boxes.end(); it != it_end; ++ it, ++ i)
- {
- const EquipmentBox *const box = *it;
- if (box == nullptr)
- continue;
- const Rect tRect(box->x, box->y, mBoxSize, mBoxSize);
-
- if (tRect.isPointInRect(x, y))
- return mEquipment->getEquipment(i);
- }
- return nullptr;
-}
-
-void EquipmentWindow::mousePressed(MouseEvent& event)
-{
- if (mEquipment == nullptr)
- {
- Window::mousePressed(event);
- return;
- }
-
- const int x = event.getX();
- const int y = event.getY();
-
- if (event.getButton() == MouseButton::LEFT)
- {
- if (mForing)
- {
- Window::mousePressed(event);
- return;
- }
- // Checks if any of the presses were in the equip boxes.
- int i = 0;
-
- bool inBox(false);
-
- STD_VECTOR<EquipmentBox*> &boxes = mPages[mSelectedTab]->boxes;
- for (STD_VECTOR<EquipmentBox*>::const_iterator it = boxes.begin(),
- it_end = boxes.end(); it != it_end; ++ it, ++ i)
- {
- const EquipmentBox *const box = *it;
- if (box == nullptr)
- continue;
- const Item *const item = mEquipment->getEquipment(i);
- const Rect tRect(box->x, box->y, mBoxSize, mBoxSize);
-
- if (tRect.isPointInRect(x, y))
- {
- inBox = true;
- if (item != nullptr)
- {
- event.consume();
- setSelected(i);
- dragDrop.dragItem(item, DragDropSource::Equipment);
- return;
- }
- }
- if (inBox)
- return;
- }
- }
- else if (event.getButton() == MouseButton::RIGHT)
- {
- if (const Item *const item = getItem(x, y))
- {
- if (itemPopup != nullptr)
- itemPopup->setVisible(Visible_false);
-
- /* Convert relative to the window coordinates to absolute screen
- * coordinates.
- */
- const int mx = x + getX();
- const int my = y + getY();
- if (popupMenu != nullptr)
- {
- event.consume();
- if (mForing)
- {
- popupMenu->showUndressPopup(mx, my, mBeing, item);
- }
- else
- {
- popupMenu->showPopup(this, mx, my, item,
- InventoryType::Inventory);
- }
- return;
- }
- }
- }
- Window::mousePressed(event);
-}
-
-void EquipmentWindow::mouseReleased(MouseEvent &event)
-{
- Window::mouseReleased(event);
- const DragDropSourceT src = dragDrop.getSource();
- if (dragDrop.isEmpty() || (src != DragDropSource::Inventory
- && src != DragDropSource::Equipment))
- {
- return;
- }
- Inventory *const inventory = localPlayer != nullptr
- ? PlayerInfo::getInventory() : nullptr;
- if (inventory == nullptr)
- return;
-
- Item *const item = inventory->findItem(dragDrop.getItem(),
- dragDrop.getItemColor());
- if (item == nullptr)
- return;
-
- if (dragDrop.getSource() == DragDropSource::Inventory)
- {
- if (item->isEquipment() == Equipm_true)
- {
- if (item->isEquipped() == Equipped_false)
- PlayerInfo::equipItem(item, Sfx_true);
- }
- }
- else if (dragDrop.getSource() == DragDropSource::Equipment)
- {
- if (item->isEquipment() == Equipm_true)
- {
- const int x = event.getX();
- const int y = event.getY();
- STD_VECTOR<EquipmentBox*> &boxes = mPages[mSelectedTab]->boxes;
- for (STD_VECTOR<EquipmentBox*>::const_iterator
- it = boxes.begin(), it_end = boxes.end();
- it != it_end; ++ it)
- {
- const EquipmentBox *const box = *it;
- if (box == nullptr)
- continue;
- const Rect tRect(box->x, box->y, mBoxSize, mBoxSize);
-
- if (tRect.isPointInRect(x, y))
- return;
- }
-
- if (item->isEquipped() == Equipped_true)
- PlayerInfo::unequipItem(item, Sfx_true);
- }
- }
- dragDrop.clear();
- dragDrop.deselect();
-}
-
-// Show ItemTooltip
-void EquipmentWindow::mouseMoved(MouseEvent &event)
-{
- Window::mouseMoved(event);
-
- if (itemPopup == nullptr)
- return;
-
- const int x = event.getX();
- const int y = event.getY();
-
- const Item *const item = getItem(x, y);
-
- if (item != nullptr)
- {
- itemPopup->setItem(item, false);
- itemPopup->position(x + getX(), y + getY());
- }
- else
- {
- itemPopup->setVisible(Visible_false);
- }
-}
-
-// Hide ItemTooltip
-void EquipmentWindow::mouseExited(MouseEvent &event A_UNUSED)
-{
- if (itemPopup != nullptr)
- itemPopup->setVisible(Visible_false);
-}
-
-void EquipmentWindow::setSelected(const int index)
-{
- mSelected = index;
- mRedraw = true;
- if (mUnequip != nullptr)
- mUnequip->setEnabled(mSelected != -1);
- if (itemPopup != nullptr)
- itemPopup->setVisible(Visible_false);
-}
-
-void EquipmentWindow::setBeing(Being *const being)
-{
- mPlayerBox->setPlayer(being);
- mBeing = being;
- if (mEquipment != nullptr)
- delete mEquipment->getBackend();
- delete mEquipment;
- if (being == nullptr)
- {
- mEquipment = nullptr;
- return;
- }
- mEquipment = being->getEquipment();
-}
-
-void EquipmentWindow::updateBeing(Being *const being)
-{
- if (being == mBeing)
- setBeing(being);
-}
-
-void EquipmentWindow::resetBeing(const Being *const being)
-{
- if (being == mBeing)
- setBeing(nullptr);
-}
-
-void EquipmentWindow::fillBoxes()
-{
- XML::Document *const doc = new XML::Document(
- paths.getStringValue("equipmentWindowFile"),
- UseVirtFs_true,
- SkipError_false);
- XmlNodeConstPtr root = doc->rootNode();
- if (root == nullptr)
- {
- delete doc;
- fillDefault();
- return;
- }
-
- if (mImageSet != nullptr)
- mImageSet->decRef();
-
- mImageSet = Theme::getImageSetFromTheme(XML::getProperty(
- root, "image", "equipmentbox.png"), 32, 32);
-
- for_each_xml_child_node(node, root)
- {
- if (xmlNameEqual(node, "page"))
- {
- loadPage(node);
- }
- }
- delete doc;
- if (reportTrue(mPages.empty()))
- fillDefault();
-}
-
-void EquipmentWindow::addDefaultPage()
-{
- if (!mHaveDefaultPage)
- {
- mHaveDefaultPage = true;
- // TRANSLATORS: equipment window tab
- addPage(_("default"));
- }
-}
-
-void EquipmentWindow::loadPage(XmlNodeConstPtr node)
-{
- if (node == nullptr)
- return;
- // TRANSLATORS: unknown equipment page name
- const std::string &name = XML::langProperty(node, "name", _("Unknown"));
- const int page = addPage(name);
- for_each_xml_child_node(childNode, node)
- {
- if (xmlNameEqual(childNode, "playerbox"))
- loadPlayerBox(childNode, page);
- else if (xmlNameEqual(childNode, "slot"))
- loadSlot(childNode, mImageSet, page);
- }
-}
-
-void EquipmentWindow::loadPlayerBox(XmlNodeConstPtr playerBoxNode,
- const int page)
-{
- EquipmentPage *const data = mPages[page];
- data->x = XML::getProperty(playerBoxNode, "x", 50);
- data->y = XML::getProperty(playerBoxNode, "y", 80) + mYPadding;
- data->width = XML::getProperty(playerBoxNode, "width", 74);
- data->height = XML::getProperty(playerBoxNode, "height", 168);
-}
-
-void EquipmentWindow::loadSlot(XmlNodeConstPtr slotNode,
- const ImageSet *const imageset,
- const int page)
-{
- if (imageset == nullptr)
- return;
- const int slot = parseSlotName(XML::getProperty(slotNode, "name", ""));
- if (slot < 0)
- return;
-
- const int x = XML::getProperty(slotNode, "x", 0) + getPadding();
- const int y = XML::getProperty(slotNode, "y", 0)
- + getTitleBarHeight() + mYPadding;
- const int imageIndex = XML::getProperty(slotNode, "image", -1);
- Image *image = nullptr;
-
- if (imageIndex >= 0 && imageIndex < CAST_S32(imageset->size()))
- image = imageset->get(imageIndex);
-
- STD_VECTOR<EquipmentBox*> &boxes = mPages[page]->boxes;
- if (boxes[slot] != nullptr)
- {
- EquipmentBox *const box = boxes[slot];
- box->x = x;
- box->y = y;
- box->image = image;
- }
- else
- {
- boxes[slot] = new EquipmentBox(x, y, image);
- }
- if (x < mMinX)
- mMinX = x;
- if (y < mMinY)
- mMinY = y;
- if (x + mBoxSize > mMaxX)
- mMaxX = x + mBoxSize;
- if (y + mBoxSize > mMaxY)
- mMaxY = y + mBoxSize;
-}
-
-void EquipmentWindow::prepareSlotNames()
-{
- mSlotNames.clear();
- XML::Document doc(paths.getStringValue("equipmentSlotsFile"),
- UseVirtFs_true,
- SkipError_false);
- XmlNodeConstPtrConst root = doc.rootNode();
- if (root == nullptr)
- return;
-
- for_each_xml_child_node(slotNode, root)
- {
- if (!xmlNameEqual(slotNode, "slot"))
- continue;
- const std::string name = XML::getProperty(slotNode, "name", "");
- if (name.empty())
- {
- reportAlways("Empty slot name detected.");
- continue;
- }
-
- const int slot = XML::getProperty(slotNode, "slot", -1);
- if (slot < 0 || slot >= BOX_COUNT)
- {
- reportAlways("Wrong slot id '%d' for slot with name '%s'",
- slot,
- name.c_str());
- continue;
- }
- mSlotNames[name] = slot;
- }
-}
-
-int EquipmentWindow::parseSlotName(const std::string &name)
-{
- StringIntMapCIter it = mSlotNames.find(name);
- if (it != mSlotNames.end())
- return (*it).second;
- return -1;
-}
-
-void EquipmentWindow::fillDefault()
-{
- if (mImageSet != nullptr)
- mImageSet->decRef();
-
- addDefaultPage();
- mImageSet = Theme::getImageSetFromTheme(
- "equipmentbox.png", 32, 32);
-
- addBox(0, 90, 40, 0); // torso
- addBox(1, 8, 78, 1); // gloves
- addBox(2, 70, 0, 2); // hat
- addBox(3, 50, 253, 3); // pants
- addBox(4, 90, 253, 4); // boots
- addBox(5, 8, 213, 5); // FREE
- addBox(6, 129, 213, 6); // wings
- addBox(7, 50, 40, 5); // scarf
- addBox(8, 8, 168, 7); // weapon
- addBox(9, 129, 168, 8); // shield
- addBox(10, 129, 78, 9); // ammo
- addBox(11, 8, 123, 5); // amulet
- addBox(12, 129, 123, 5); // ring
-}
-
-void EquipmentWindow::addBox(const int idx, int x, int y, const int imageIndex)
-{
- Image *image = nullptr;
-
- if ((mImageSet != nullptr) && imageIndex >= 0 && imageIndex
- < CAST_S32(mImageSet->size()))
- {
- image = mImageSet->get(imageIndex);
- }
-
- x += getPadding();
- y += getTitleBarHeight() + mYPadding;
- STD_VECTOR<EquipmentBox*> &boxes = mPages[0]->boxes;
- boxes[idx] = new EquipmentBox(x, y, image);
-
- if (x < mMinX)
- mMinX = x;
- if (y < mMinY)
- mMinY = y;
- if (x + mBoxSize > mMaxX)
- mMaxX = x + mBoxSize;
- if (y + mBoxSize > mMaxY)
- mMaxY = y + mBoxSize;
-}
-
-void EquipmentWindow::recalcSize()
-{
- mMaxX += mMinX;
- mMaxY += mMinY;
- mTabs->setWidth(mMaxX);
- mMaxY += mUnequip->getHeight() - mYPadding;
- setDefaultSize(mMaxX, mMaxY, ImagePosition::CENTER);
-}
-
-int EquipmentWindow::addPage(const std::string &name)
-{
- EquipmentPage *const page = new EquipmentPage;
- mPages.push_back(page);
- STD_VECTOR<EquipmentBox*> &boxes = page->boxes;
-
- boxes.reserve(BOX_COUNT);
- for (int f = 0; f < BOX_COUNT; f ++)
- boxes.push_back(nullptr);
-
- mTabs->addButton(name, name, false);
- return CAST_S32(mPages.size()) - 1;
-}
diff --git a/src/gui/windows/equipmentwindow.h b/src/gui/windows/equipmentwindow.h
deleted file mode 100644
index b36174095..000000000
--- a/src/gui/windows/equipmentwindow.h
+++ /dev/null
@@ -1,167 +0,0 @@
-/*
- * The ManaPlus Client
- * Copyright (C) 2004-2009 The Mana World Development Team
- * Copyright (C) 2009-2010 The Mana Developers
- * Copyright (C) 2011-2017 The ManaPlus Developers
- *
- * This file is part of The ManaPlus Client.
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-#ifndef GUI_WINDOWS_EQUIPMENTWINDOW_H
-#define GUI_WINDOWS_EQUIPMENTWINDOW_H
-
-#include "equipment.h"
-#include "localconsts.h"
-
-#include "gui/widgets/window.h"
-
-#include "utils/stringmap.h"
-#include "utils/xml.h"
-
-#include "listeners/actionlistener.h"
-
-class Being;
-class Button;
-class Image;
-class ImageSet;
-class Item;
-class PlayerBox;
-class TabStrip;
-
-struct EquipmentPage;
-
-/**
- * Equipment dialog.
- *
- * \ingroup Interface
- */
-class EquipmentWindow final : public Window,
- public ActionListener
-{
- public:
- /**
- * Constructor.
- */
- EquipmentWindow(Equipment *const equipment, Being *const being,
- const bool foring = false);
-
- A_DELETE_COPY(EquipmentWindow)
-
- /**
- * Destructor.
- */
- ~EquipmentWindow();
-
- void postInit() override final;
-
- /**
- * Draws the equipment window.
- */
- void draw(Graphics *const graphics) override final A_NONNULL(2);
-
- void safeDraw(Graphics *const graphics) override final A_NONNULL(2);
-
- void action(const ActionEvent &event) override final;
-
- void mousePressed(MouseEvent& event) override final;
-
- const Item* getEquipment(const int i) const A_WARN_UNUSED
- {
- return mEquipment != nullptr ?
- mEquipment->getEquipment(i) : nullptr;
- }
-
- void setBeing(Being *const being);
-
- void updateBeing(Being *const being);
-
- void resetBeing(const Being *const being);
-
- void mouseExited(MouseEvent &event) override final;
-
- void mouseMoved(MouseEvent &event) override final;
-
- void mouseReleased(MouseEvent &event) override final;
-
- void recalcSize();
-
- static void prepareSlotNames();
-
- private:
- const Item *getItem(const int x, const int y) const A_WARN_UNUSED;
-
- void setSelected(const int index);
-
- void fillBoxes();
-
- void fillDefault();
-
- void updatePage();
-
- int addPage(const std::string &name);
-
- void addDefaultPage();
-
- void addBox(const int idx, int x, int y, const int imageIndex);
-
- void loadWindow(XmlNodeConstPtrConst windowNode);
-
- void loadPage(XmlNodeConstPtr node);
-
- void loadPlayerBox(XmlNodeConstPtr playerBoxNode, const int page);
-
- void loadSlot(XmlNodeConstPtr slotNode,
- const ImageSet *const imageset,
- const int page);
-
- static int parseSlotName(const std::string &name) A_WARN_UNUSED;
-
- static StringIntMap mSlotNames;
-
- Equipment *mEquipment;
-
- PlayerBox *mPlayerBox A_NONNULLPOINTER;
- Button *mUnequip A_NONNULLPOINTER;
-
- ImageSet *mImageSet;
- Being *mBeing;
- Image *mSlotBackground;
- Image *mSlotHighlightedBackground;
- ImageCollection *mVertexes A_NONNULLPOINTER;
- STD_VECTOR<EquipmentPage*> mPages;
- TabStrip *mTabs;
- Color mHighlightColor;
- Color mBorderColor;
- Color mLabelsColor;
- Color mLabelsColor2;
- int mSelected; /**< Index of selected item. */
- int mItemPadding;
- int mBoxSize;
- int mButtonPadding;
- int mMinX;
- int mMinY;
- int mMaxX;
- int mMaxY;
- int mYPadding;
- int mSelectedTab;
- bool mForing;
- bool mHaveDefaultPage;
-};
-
-extern EquipmentWindow *equipmentWindow;
-extern EquipmentWindow *beingEquipmentWindow;
-
-#endif // GUI_WINDOWS_EQUIPMENTWINDOW_H
diff --git a/src/gui/windows/helpwindow.cpp b/src/gui/windows/helpwindow.cpp
deleted file mode 100644
index 1cfb30e2b..000000000
--- a/src/gui/windows/helpwindow.cpp
+++ /dev/null
@@ -1,220 +0,0 @@
-/*
- * The ManaPlus Client
- * Copyright (C) 2004-2009 The Mana World Development Team
- * Copyright (C) 2009-2010 The Mana Developers
- * Copyright (C) 2011-2017 The ManaPlus Developers
- *
- * This file is part of The ManaPlus Client.
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-#include "gui/windows/helpwindow.h"
-
-#include "configuration.h"
-
-#include "enums/gui/layouttype.h"
-
-#include "fs/paths.h"
-
-#include "fs/virtfs/tools.h"
-
-#include "gui/gui.h"
-
-#include "gui/windows/setupwindow.h"
-
-#include "gui/widgets/button.h"
-#include "gui/widgets/staticbrowserbox.h"
-#include "gui/widgets/layout.h"
-#include "gui/widgets/scrollarea.h"
-
-#include "input/inputmanager.h"
-
-#include "utils/foreach.h"
-#include "utils/gettext.h"
-#include "utils/process.h"
-
-#include "utils/translation/podict.h"
-#include "utils/translation/translationmanager.h"
-
-#include "debug.h"
-
-HelpWindow *helpWindow = nullptr;
-
-HelpWindow::HelpWindow() :
- // TRANSLATORS: help window name
- Window(_("Help"), Modal_false, nullptr, "help.xml"),
- LinkHandler(),
- ActionListener(),
- // TRANSLATORS: help window. button.
- mDYKButton(new Button(this, _("Did you know..."), "DYK", this)),
- mBrowserBox(new StaticBrowserBox(this, Opaque_true,
- "browserbox.xml")),
- mScrollArea(new ScrollArea(this, mBrowserBox,
- Opaque_true, "help_background.xml")),
- mTagFileMap()
-{
- setMinWidth(300);
- setMinHeight(220);
- setContentSize(455, 350);
- setWindowName("Help");
- setCloseButton(true);
- setResizable(true);
- setStickyButtonLock(true);
-
- if (setupWindow != nullptr)
- setupWindow->registerWindowForReset(this);
-
- setDefaultSize(500, 400, ImagePosition::CENTER);
-
- mBrowserBox->setOpaque(Opaque_false);
-
- mBrowserBox->setLinkHandler(this);
- if (gui != nullptr)
- mBrowserBox->setFont(gui->getHelpFont());
- mBrowserBox->setProcessVars(true);
- mBrowserBox->setEnableImages(true);
- mBrowserBox->setEnableKeys(true);
- mBrowserBox->setEnableTabs(true);
-
- place(4, 3, mDYKButton);
- place(0, 0, mScrollArea, 5, 3).setPadding(3);
-
- Layout &layout = getLayout();
- layout.setRowHeight(0, LayoutType::SET);
-
- loadWindowState();
- loadTags();
- enableVisibleSound(true);
- widgetResized(Event(nullptr));
-}
-
-void HelpWindow::action(const ActionEvent &event)
-{
- if (event.getId() == "DYK")
- inputManager.executeAction(InputAction::WINDOW_DIDYOUKNOW);
-}
-
-void HelpWindow::handleLink(const std::string &link,
- MouseEvent *const event A_UNUSED)
-{
- if (!strStartWith(link, "http://") && !strStartWith(link, "https://"))
- {
- // need use separate variable
- const std::string helpFile = link;
- loadHelp(helpFile);
- }
- else
- {
- openBrowser(link);
- }
-}
-
-void HelpWindow::loadHelp(const std::string &helpFile)
-{
- if (!checkPath(helpFile))
- return;
- mBrowserBox->clearRows();
- loadFile("header");
- loadFile(helpFile);
- loadFile("footer");
- mScrollArea->setVerticalScrollAmount(0);
- mBrowserBox->updateHeight();
- setVisible(Visible_true);
-}
-
-void HelpWindow::loadHelpSimple(const std::string &helpFile)
-{
- if (!checkPath(helpFile))
- return;
- mBrowserBox->clearRows();
- loadFile(helpFile);
- mScrollArea->setVerticalScrollAmount(0);
- mBrowserBox->updateHeight();
- setVisible(Visible_true);
-}
-
-void HelpWindow::loadFile(std::string file)
-{
- trim(file);
- std::string helpPath = branding.getStringValue("helpPath");
- if (helpPath.empty())
- helpPath = paths.getStringValue("help");
-
- StringVect lines;
- TranslationManager::translateFile(pathJoin(helpPath, file).append(".txt"),
- translator, lines);
-
- for (size_t i = 0, sz = lines.size(); i < sz; ++i)
- mBrowserBox->addRow(lines[i]);
-}
-
-void HelpWindow::loadTags()
-{
- std::string helpPath = branding.getStringValue("tagsPath");
- if (helpPath.empty())
- helpPath = paths.getStringValue("tags");
-
- StringVect filesVect;
- VirtFs::getFilesInDir(helpPath, filesVect, ".idx");
- FOR_EACH (StringVectCIter, itVect, filesVect)
- {
- StringVect lines;
- VirtFs::loadTextFile(*itVect, lines);
- FOR_EACH (StringVectCIter, it, lines)
- {
- const std::string &str = *it;
- const size_t idx = str.find('|');
- if (idx != std::string::npos)
- mTagFileMap[str.substr(idx + 1)].insert(str.substr(0, idx));
- }
- }
-}
-
-void HelpWindow::search(const std::string &text0)
-{
- std::string text = text0;
- trim(text);
- toLower(text);
- if (mTagFileMap.find(text) == mTagFileMap.end())
- {
- loadHelp("searchnotfound");
- }
- else
- {
- const HelpNames &names = mTagFileMap[text];
- if (names.size() == 1)
- {
- loadHelp(*names.begin());
- }
- else
- {
- if (translator == nullptr)
- return;
- mBrowserBox->clearRows();
- loadFile("header");
- loadFile("searchmany");
- FOR_EACH (HelpNamesCIter, it, names)
- {
- const char *const str = (*it).c_str();
- mBrowserBox->addRow(strprintf(" -> @@%s|%s@@", str,
- translator->getChar(str)));
- }
- loadFile("footer");
- mScrollArea->setVerticalScrollAmount(0);
- mBrowserBox->updateHeight();
- setVisible(Visible_true);
- }
- }
-}
diff --git a/src/gui/windows/helpwindow.h b/src/gui/windows/helpwindow.h
deleted file mode 100644
index 2fb2407d9..000000000
--- a/src/gui/windows/helpwindow.h
+++ /dev/null
@@ -1,92 +0,0 @@
-/*
- * The ManaPlus Client
- * Copyright (C) 2004-2009 The Mana World Development Team
- * Copyright (C) 2009-2010 The Mana Developers
- * Copyright (C) 2011-2017 The ManaPlus Developers
- *
- * This file is part of The ManaPlus Client.
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-#ifndef GUI_WINDOWS_HELPWINDOW_H
-#define GUI_WINDOWS_HELPWINDOW_H
-
-#include "gui/widgets/linkhandler.h"
-#include "gui/widgets/window.h"
-
-#include "listeners/actionlistener.h"
-
-#include "localconsts.h"
-
-class Button;
-class ScrollArea;
-class StaticBrowserBox;
-
-typedef std::set<std::string> HelpNames;
-typedef HelpNames::const_iterator HelpNamesCIter;
-typedef std::map<std::string, HelpNames> HelpTagsMap;
-
-/**
- * The help window.
- */
-class HelpWindow final : public Window,
- public LinkHandler,
- public ActionListener
-{
- public:
- /**
- * Constructor.
- */
- HelpWindow();
-
- A_DELETE_COPY(HelpWindow)
-
- /**
- * Called when receiving actions from the widgets.
- */
- void action(const ActionEvent &event) override final;
-
- /**
- * Handles link action.
- */
- void handleLink(const std::string &link,
- MouseEvent *const event A_UNUSED) override final;
-
- /**
- * Loads help in the dialog.
- */
- void loadHelp(const std::string &helpFile);
-
- void loadHelpSimple(const std::string &helpFile);
-
- /**
- * Seach for given text in tags.
- */
- void search(const std::string &text);
-
- private:
- void loadTags();
-
- void loadFile(std::string file);
-
- Button *mDYKButton A_NONNULLPOINTER;
- StaticBrowserBox *mBrowserBox A_NONNULLPOINTER;
- ScrollArea *mScrollArea A_NONNULLPOINTER;
- HelpTagsMap mTagFileMap;
-};
-
-extern HelpWindow *helpWindow;
-
-#endif // GUI_WINDOWS_HELPWINDOW_H
diff --git a/src/gui/windows/insertcarddialog.cpp b/src/gui/windows/insertcarddialog.cpp
deleted file mode 100644
index 590df6aba..000000000
--- a/src/gui/windows/insertcarddialog.cpp
+++ /dev/null
@@ -1,79 +0,0 @@
-/*
- * The ManaPlus Client
- * Copyright (C) 2004-2009 The Mana World Development Team
- * Copyright (C) 2009-2010 The Mana Developers
- * Copyright (C) 2011-2017 The ManaPlus Developers
- *
- * This file is part of The ManaPlus Client.
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-#include "gui/windows/insertcarddialog.h"
-
-#include "gui/models/shopitems.h"
-
-#include "gui/widgets/button.h"
-#include "gui/widgets/shoplistbox.h"
-
-#include "net/inventoryhandler.h"
-
-#include "utils/gettext.h"
-#include "utils/stringutils.h"
-
-#include "resources/item/shopitem.h"
-
-#include "debug.h"
-
-InsertCardDialog::InsertCardDialog(const int itemIndex,
- const Item *const item) :
- SellDialog(IsSell_false, Advanced_false),
- mItemIndex(itemIndex)
-{
- // TRANSLATORS: insert card dialog name
- setWindowName(_("Insert card"));
- if (item != nullptr)
- {
- // TRANSLATORS: insert card dialog name
- setCaption(strprintf(_("Insert card %s"),
- item->getName().c_str()));
- }
- else
- {
- // TRANSLATORS: insert card dialog name
- setCaption(strprintf(_("Insert card %s"),
- ""));
- }
-}
-
-void InsertCardDialog::initButtons()
-{
- // TRANSLATORS: insert card dialog button
- mSellButton->setCaption(_("Insert"));
- mSellButton->adjustSize();
- mShopItems->setMergeDuplicates(false);
-}
-
-void InsertCardDialog::sellAction(const ActionEvent &event A_UNUSED)
-{
- if (mAmountItems <= 0 || mAmountItems > mMaxItems)
- return;
-
- const int selectedItem = mShopItemList->getSelected();
- const ShopItem *const item = mShopItems->at(selectedItem);
- if (item == nullptr)
- return;
- inventoryHandler->insertCard(mItemIndex, item->getInvIndex());
- scheduleDelete();
-}
diff --git a/src/gui/windows/insertcarddialog.h b/src/gui/windows/insertcarddialog.h
deleted file mode 100644
index ba46022a2..000000000
--- a/src/gui/windows/insertcarddialog.h
+++ /dev/null
@@ -1,49 +0,0 @@
-/*
- * The ManaPlus Client
- * Copyright (C) 2004-2009 The Mana World Development Team
- * Copyright (C) 2009-2010 The Mana Developers
- * Copyright (C) 2011-2017 The ManaPlus Developers
- *
- * This file is part of The ManaPlus Client.
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-#ifndef GUI_WINDOWS_INSERTCARDDIALOG_H
-#define GUI_WINDOWS_INSERTCARDDIALOG_H
-
-#include "gui/widgets/selldialog.h"
-
-class InsertCardDialog final : public SellDialog
-{
- public:
- /**
- * Constructor.
- *
- * @see Window::Window
- */
- InsertCardDialog(const int itemIndex,
- const Item *const item);
-
- A_DELETE_COPY(InsertCardDialog)
-
- protected:
- void initButtons() override final;
- void sellAction(const ActionEvent &event) override final;
-
- private:
- int mItemIndex;
-};
-
-#endif // GUI_WINDOWS_INSERTCARDDIALOG_H
diff --git a/src/gui/windows/inventorywindow.cpp b/src/gui/windows/inventorywindow.cpp
deleted file mode 100644
index f973f250f..000000000
--- a/src/gui/windows/inventorywindow.cpp
+++ /dev/null
@@ -1,1083 +0,0 @@
-/*
- * The ManaPlus Client
- * Copyright (C) 2004-2009 The Mana World Development Team
- * Copyright (C) 2009-2010 The Mana Developers
- * Copyright (C) 2011-2017 The ManaPlus Developers
- *
- * This file is part of The ManaPlus Client.
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-#include "gui/windows/inventorywindow.h"
-
-#include "configuration.h"
-
-#include "being/playerinfo.h"
-
-#include "enums/gui/layouttype.h"
-
-#include "input/inputmanager.h"
-
-#include "gui/gui.h"
-
-#include "gui/fonts/font.h"
-
-#include "gui/models/sortlistmodelinv.h"
-
-#include "gui/popups/itempopup.h"
-#include "gui/popups/popupmenu.h"
-#include "gui/popups/textpopup.h"
-
-#include "gui/windows/confirmdialog.h"
-#include "gui/windows/itemamountwindow.h"
-#include "gui/windows/npcdialog.h"
-#include "gui/windows/setupwindow.h"
-#include "gui/windows/tradewindow.h"
-
-#include "gui/widgets/button.h"
-#include "gui/widgets/createwidget.h"
-#include "gui/widgets/containerplacer.h"
-#include "gui/widgets/dropdown.h"
-#include "gui/widgets/itemcontainer.h"
-#include "gui/widgets/layout.h"
-#include "gui/widgets/progressbar.h"
-#include "gui/widgets/scrollarea.h"
-#include "gui/widgets/tabstrip.h"
-#include "gui/widgets/textfield.h"
-#include "gui/widgets/windowcontainer.h"
-
-#include "listeners/insertcardlistener.h"
-
-#include "net/npchandler.h"
-
-#include "resources/iteminfo.h"
-
-#include "resources/db/unitsdb.h"
-
-#include "resources/item/item.h"
-
-#include "utils/delete2.h"
-#include "utils/foreach.h"
-
-#include "debug.h"
-
-InventoryWindow *inventoryWindow = nullptr;
-InventoryWindow *storageWindow = nullptr;
-InventoryWindow *cartWindow = nullptr;
-InventoryWindow::WindowList InventoryWindow::invInstances;
-InsertCardListener insertCardListener;
-
-InventoryWindow::InventoryWindow(Inventory *const inventory) :
- Window("Inventory", Modal_false, nullptr, "inventory.xml"),
- ActionListener(),
- KeyListener(),
- SelectionListener(),
- InventoryListener(),
- AttributeListener(),
- mInventory(inventory),
- mItems(new ItemContainer(this, mInventory)),
- mUseButton(nullptr),
- mDropButton(nullptr),
- mOutfitButton(nullptr),
- mShopButton(nullptr),
- mCartButton(nullptr),
- mEquipmentButton(nullptr),
- mStoreButton(nullptr),
- mRetrieveButton(nullptr),
- mInvCloseButton(nullptr),
- mWeightBar(nullptr),
- mSlotsBar(new ProgressBar(this, 0.0F, 100, 0,
- ProgressColorId::PROG_INVY_SLOTS,
- "slotsprogressbar.xml", "slotsprogressbar_fill.xml")),
- mFilter(nullptr),
- mSortModel(new SortListModelInv),
- mSortDropDown(new DropDown(this, mSortModel, false,
- Modal_false, this, "sort")),
- mNameFilter(new TextField(this, "", LoseFocusOnTab_true,
- this, "namefilter", true)),
- mSortDropDownCell(nullptr),
- mNameFilterCell(nullptr),
- mFilterCell(nullptr),
- mSlotsBarCell(nullptr),
- mSplit(false),
- mCompactMode(false)
-{
- mSlotsBar->setColor(getThemeColor(ThemeColorId::SLOTS_BAR),
- getThemeColor(ThemeColorId::SLOTS_BAR_OUTLINE));
-
- if (inventory != nullptr)
- {
- setCaption(gettext(inventory->getName().c_str()));
- setWindowName(inventory->getName());
- switch (inventory->getType())
- {
- case InventoryType::Inventory:
- case InventoryType::Trade:
- case InventoryType::Npc:
- case InventoryType::Vending:
- case InventoryType::MailEdit:
- case InventoryType::MailView:
- case InventoryType::Craft:
- case InventoryType::TypeEnd:
- default:
- mSortDropDown->setSelected(config.getIntValue(
- "inventorySortOrder"));
- break;
- case InventoryType::Storage:
- mSortDropDown->setSelected(config.getIntValue(
- "storageSortOrder"));
- break;
- case InventoryType::Cart:
- mSortDropDown->setSelected(config.getIntValue(
- "cartSortOrder"));
- break;
- };
- }
- else
- {
- // TRANSLATORS: inventory window name
- setCaption(_("Inventory"));
- setWindowName("Inventory");
- mSortDropDown->setSelected(0);
- }
-
- if ((setupWindow != nullptr) &&
- (inventory != nullptr) &&
- inventory->getType() != InventoryType::Storage)
- {
- setupWindow->registerWindowForReset(this);
- }
-
- setResizable(true);
- setCloseButton(true);
- setSaveVisible(true);
- setStickyButtonLock(true);
-
- if (mainGraphics->mWidth > 600)
- setDefaultSize(450, 310, ImagePosition::CENTER);
- else
- setDefaultSize(387, 307, ImagePosition::CENTER);
- setMinWidth(310);
- setMinHeight(179);
- addKeyListener(this);
-
- mItems->addSelectionListener(this);
-
- const int size = config.getIntValue("fontSize");
- mFilter = new TabStrip(this, "filter_" + getWindowName(), size + 16);
- mFilter->addActionListener(this);
- mFilter->setActionEventId("tag_");
- mFilter->setSelectable(false);
-
- StringVect tags = ItemDB::getTags();
- const size_t sz = tags.size();
- for (size_t f = 0; f < sz; f ++)
- mFilter->addButton(tags[f], tags[f], false);
-
- if (mInventory == nullptr)
- {
- invInstances.push_back(this);
- return;
- }
-
- ScrollArea *const invenScroll = new ScrollArea(this, mItems,
- fromBool(getOptionBool("showbackground"), Opaque),
- "inventory_background.xml");
- invenScroll->setHorizontalScrollPolicy(ScrollArea::SHOW_NEVER);
-
- switch (mInventory->getType())
- {
- case InventoryType::Inventory:
- {
- // TRANSLATORS: inventory button
- const std::string equip = _("Equip");
- // TRANSLATORS: inventory button
- const std::string use = _("Use");
- // TRANSLATORS: inventory button
- const std::string unequip = _("Unequip");
-
- std::string longestUseString = getFont()->getWidth(equip) >
- getFont()->getWidth(use) ? equip : use;
-
- if (getFont()->getWidth(longestUseString) <
- getFont()->getWidth(unequip))
- {
- longestUseString = unequip;
- }
-
- mUseButton = new Button(this, longestUseString, "use", this);
- // TRANSLATORS: inventory button
- mDropButton = new Button(this, _("Drop..."), "drop", this);
- // TRANSLATORS: inventory outfits button
- mOutfitButton = new Button(this, _("O"), "outfit", this);
- // TRANSLATORS: inventory cart button
- mCartButton = new Button(this, _("C"), "cart", this);
- // TRANSLATORS: inventory shop button
- mShopButton = new Button(this, _("S"), "shop", this);
- // TRANSLATORS: inventory equipment button
- mEquipmentButton = new Button(this, _("E"), "equipment", this);
- mWeightBar = new ProgressBar(this, 0.0F, 100, 0,
- ProgressColorId::PROG_WEIGHT,
- "weightprogressbar.xml", "weightprogressbar_fill.xml");
- mWeightBar->setColor(getThemeColor(ThemeColorId::WEIGHT_BAR),
- getThemeColor(ThemeColorId::WEIGHT_BAR_OUTLINE));
-
- // TRANSLATORS: outfits button tooltip
- mOutfitButton->setDescription(_("Outfits"));
- // TRANSLATORS: cart button tooltip
- mCartButton->setDescription(_("Cart"));
- // TRANSLATORS: shop button tooltip
- mShopButton->setDescription(_("Shop"));
- // TRANSLATORS: equipment button tooltip
- mEquipmentButton->setDescription(_("Equipment"));
-
- place(0, 0, mWeightBar, 4);
- mSlotsBarCell = &place(4, 0, mSlotsBar, 4);
- mSortDropDownCell = &place(8, 0, mSortDropDown, 3);
-
- mFilterCell = &place(0, 1, mFilter, 10).setPadding(3);
- mNameFilterCell = &place(8, 1, mNameFilter, 3);
-
- place(0, 2, invenScroll, 11).setPadding(3);
- place(0, 3, mUseButton);
- place(1, 3, mDropButton);
- ContainerPlacer placer = getPlacer(10, 3);
- placer(0, 0, mShopButton);
- placer(1, 0, mOutfitButton);
- placer(2, 0, mCartButton);
- placer(3, 0, mEquipmentButton);
-
- updateWeight();
- break;
- }
-
- case InventoryType::Storage:
- {
- // TRANSLATORS: storage button
- mStoreButton = new Button(this, _("Store"), "store", this);
- // TRANSLATORS: storage button
- mRetrieveButton = new Button(this, _("Retrieve"),
- "retrieve", this);
- // TRANSLATORS: storage button
- mInvCloseButton = new Button(this, _("Close"), "close", this);
-
- mSlotsBarCell = &place(0, 0, mSlotsBar, 6);
- mSortDropDownCell = &place(6, 0, mSortDropDown, 1);
-
- mFilterCell = &place(0, 1, mFilter, 7).setPadding(3);
- mNameFilterCell = &place(6, 1, mNameFilter, 1);
-
- place(0, 2, invenScroll, 7, 4);
- place(0, 6, mStoreButton);
- place(1, 6, mRetrieveButton);
- place(6, 6, mInvCloseButton);
- break;
- }
-
- case InventoryType::Cart:
- {
- // TRANSLATORS: storage button
- mStoreButton = new Button(this, _("Store"), "store", this);
- // TRANSLATORS: storage button
- mRetrieveButton = new Button(this, _("Retrieve"),
- "retrieve", this);
- // TRANSLATORS: storage button
- mInvCloseButton = new Button(this, _("Close"), "close", this);
-
- mWeightBar = new ProgressBar(this, 0.0F, 100, 0,
- ProgressColorId::PROG_WEIGHT,
- "weightprogressbar.xml", "weightprogressbar_fill.xml");
- mWeightBar->setColor(getThemeColor(ThemeColorId::WEIGHT_BAR),
- getThemeColor(ThemeColorId::WEIGHT_BAR_OUTLINE));
-
- mSlotsBarCell = &place(3, 0, mSlotsBar, 3);
- mSortDropDownCell = &place(6, 0, mSortDropDown, 1);
-
- mFilterCell = &place(0, 1, mFilter, 7).setPadding(3);
- mNameFilterCell = &place(6, 1, mNameFilter, 1);
-
- place(0, 0, mWeightBar, 3);
- place(0, 2, invenScroll, 7, 4);
- place(0, 6, mStoreButton);
- place(1, 6, mRetrieveButton);
- place(6, 6, mInvCloseButton);
- break;
- }
-
- default:
- case InventoryType::Trade:
- case InventoryType::Npc:
- case InventoryType::Vending:
- case InventoryType::MailEdit:
- case InventoryType::MailView:
- case InventoryType::Craft:
- case InventoryType::TypeEnd:
- break;
- };
-
- Layout &layout = getLayout();
- layout.setRowHeight(2, LayoutType::SET);
-
- mInventory->addInventoyListener(this);
-
- invInstances.push_back(this);
-
- if (inventory->isMainInventory())
- {
- updateDropButton();
- }
- else
- {
- if (!invInstances.empty())
- invInstances.front()->updateDropButton();
- }
-
- loadWindowState();
- enableVisibleSound(true);
-}
-
-void InventoryWindow::postInit()
-{
- Window::postInit();
- slotsChanged(mInventory);
-
- mItems->setSortType(mSortDropDown->getSelected());
- widgetResized(Event(nullptr));
- if (mInventory != nullptr &&
- mInventory->getType() == InventoryType::Storage)
- {
- setVisible(Visible_true);
- }
-}
-
-InventoryWindow::~InventoryWindow()
-{
- invInstances.remove(this);
- if (mInventory != nullptr)
- mInventory->removeInventoyListener(this);
- if (!invInstances.empty())
- invInstances.front()->updateDropButton();
-
- mSortDropDown->hideDrop(false);
- delete2(mSortModel);
-}
-
-void InventoryWindow::storeSortOrder() const
-{
- if (mInventory != nullptr)
- {
- switch (mInventory->getType())
- {
- case InventoryType::Inventory:
- case InventoryType::Trade:
- case InventoryType::Npc:
- case InventoryType::Vending:
- case InventoryType::MailEdit:
- case InventoryType::MailView:
- case InventoryType::Craft:
- case InventoryType::TypeEnd:
- default:
- config.setValue("inventorySortOrder",
- mSortDropDown->getSelected());
- break;
- case InventoryType::Storage:
- config.setValue("storageSortOrder",
- mSortDropDown->getSelected());
- break;
- case InventoryType::Cart:
- config.setValue("cartSortOrder",
- mSortDropDown->getSelected());
- break;
- };
- }
-}
-
-void InventoryWindow::action(const ActionEvent &event)
-{
- const std::string &eventId = event.getId();
- if (eventId == "outfit")
- {
- inputManager.executeAction(InputAction::WINDOW_OUTFIT);
- }
- else if (eventId == "shop")
- {
- inputManager.executeAction(InputAction::WINDOW_SHOP);
- }
- else if (eventId == "equipment")
- {
- inputManager.executeAction(InputAction::WINDOW_EQUIPMENT);
- }
- else if (eventId == "cart")
- {
- inputManager.executeAction(InputAction::WINDOW_CART);
- }
- else if (eventId == "close")
- {
- close();
- }
- else if (eventId == "store")
- {
- if (inventoryWindow == nullptr || !inventoryWindow->isWindowVisible())
- return;
-
- Item *const item = inventoryWindow->getSelectedItem();
-
- if (item == nullptr)
- return;
-
- if (storageWindow != nullptr)
- {
- ItemAmountWindow::showWindow(ItemAmountWindowUsage::StoreAdd,
- this, item);
- }
- else if ((cartWindow != nullptr) && cartWindow->isWindowVisible())
- {
- ItemAmountWindow::showWindow(ItemAmountWindowUsage::CartAdd,
- this, item);
- }
- }
- else if (eventId == "sort")
- {
- mItems->setSortType(mSortDropDown->getSelected());
- storeSortOrder();
- return;
- }
- else if (eventId == "namefilter")
- {
- mItems->setName(mNameFilter->getText());
- mItems->updateMatrix();
- }
- else if (eventId.find("tag_") == 0u)
- {
- std::string tagName = event.getId().substr(4);
- mItems->setFilter(ItemDB::getTagId(tagName));
- return;
- }
-
- Item *const item = mItems->getSelectedItem();
-
- if (item == nullptr)
- return;
-
- if (eventId == "use")
- {
- PlayerInfo::useEquipItem(item, 0, Sfx_true);
- }
- if (eventId == "equip")
- {
- PlayerInfo::useEquipItem2(item, 0, Sfx_true);
- }
- else if (eventId == "drop")
- {
- if (isStorageActive())
- {
- inventoryHandler->moveItem2(InventoryType::Inventory,
- item->getInvIndex(),
- item->getQuantity(),
- InventoryType::Storage);
- }
- else if ((cartWindow != nullptr) && cartWindow->isWindowVisible())
- {
- inventoryHandler->moveItem2(InventoryType::Inventory,
- item->getInvIndex(),
- item->getQuantity(),
- InventoryType::Cart);
- }
- else
- {
- if (PlayerInfo::isItemProtected(item->getId()))
- return;
-
- if (inputManager.isActionActive(InputAction::STOP_ATTACK))
- {
- PlayerInfo::dropItem(item, item->getQuantity(), Sfx_true);
- }
- else
- {
- ItemAmountWindow::showWindow(ItemAmountWindowUsage::ItemDrop,
- this, item);
- }
- }
- }
- else if (eventId == "split")
- {
- ItemAmountWindow::showWindow(ItemAmountWindowUsage::ItemSplit,
- this, item,
- (item->getQuantity() - 1));
- }
- else if (eventId == "retrieve")
- {
- if (storageWindow != nullptr)
- {
- ItemAmountWindow::showWindow(ItemAmountWindowUsage::StoreRemove,
- this, item);
- }
- else if ((cartWindow != nullptr) && cartWindow->isWindowVisible())
- {
- ItemAmountWindow::showWindow(ItemAmountWindowUsage::CartRemove,
- this, item);
- }
- }
-}
-
-Item *InventoryWindow::getSelectedItem() const
-{
- return mItems->getSelectedItem();
-}
-
-void InventoryWindow::unselectItem()
-{
- mItems->selectNone();
-}
-
-void InventoryWindow::widgetHidden(const Event &event)
-{
- Window::widgetHidden(event);
- if (itemPopup != nullptr)
- itemPopup->setVisible(Visible_false);
-}
-
-void InventoryWindow::mouseClicked(MouseEvent &event)
-{
- Window::mouseClicked(event);
-
- const int clicks = event.getClickCount();
-
- if (clicks == 2 && (gui != nullptr))
- gui->resetClickCount();
-
- const bool mod = (isStorageActive() &&
- inputManager.isActionActive(InputAction::STOP_ATTACK));
-
- const bool mod2 = (tradeWindow != nullptr &&
- tradeWindow->isWindowVisible() &&
- inputManager.isActionActive(InputAction::STOP_ATTACK));
-
- if (mInventory != nullptr)
- {
- if (!mod && !mod2 && event.getButton() == MouseButton::RIGHT)
- {
- Item *const item = mItems->getSelectedItem();
-
- if (item == nullptr)
- return;
-
- /* Convert relative to the window coordinates to absolute screen
- * coordinates.
- */
- const int mx = event.getX() + getX();
- const int my = event.getY() + getY();
-
- if (popupMenu != nullptr)
- {
- popupMenu->showPopup(this,
- mx, my,
- item,
- mInventory->getType());
- }
- }
- }
- else
- {
- return;
- }
-
- if (event.getButton() == MouseButton::LEFT ||
- event.getButton() == MouseButton::RIGHT)
- {
- Item *const item = mItems->getSelectedItem();
-
- if (item == nullptr)
- return;
-
- if (mod)
- {
- if (mInventory->isMainInventory())
- {
- if (event.getButton() == MouseButton::RIGHT)
- {
- ItemAmountWindow::showWindow(
- ItemAmountWindowUsage::StoreAdd,
- inventoryWindow,
- item);
- }
- else
- {
- inventoryHandler->moveItem2(InventoryType::Inventory,
- item->getInvIndex(),
- item->getQuantity(),
- InventoryType::Storage);
- }
- }
- else
- {
- if (event.getButton() == MouseButton::RIGHT)
- {
- ItemAmountWindow::showWindow(
- ItemAmountWindowUsage::StoreRemove,
- inventoryWindow,
- item);
- }
- else
- {
- inventoryHandler->moveItem2(InventoryType::Storage,
- item->getInvIndex(),
- item->getQuantity(),
- InventoryType::Inventory);
- }
- }
- }
- else if (mod2 && mInventory->isMainInventory())
- {
- if (PlayerInfo::isItemProtected(item->getId()))
- return;
- if (event.getButton() == MouseButton::RIGHT)
- {
- ItemAmountWindow::showWindow(ItemAmountWindowUsage::TradeAdd,
- tradeWindow, item);
- }
- else
- {
- if (tradeWindow != nullptr)
- tradeWindow->tradeItem(item, item->getQuantity(), true);
- }
- }
- else if (clicks == 2)
- {
- if (mInventory->isMainInventory())
- {
- if (isStorageActive())
- {
- ItemAmountWindow::showWindow(
- ItemAmountWindowUsage::StoreAdd,
- inventoryWindow, item);
- }
- else if (tradeWindow != nullptr &&
- tradeWindow->isWindowVisible())
- {
- if (PlayerInfo::isItemProtected(item->getId()))
- return;
- ItemAmountWindow::showWindow(
- ItemAmountWindowUsage::TradeAdd,
- tradeWindow, item);
- }
- else
- {
- PlayerInfo::useEquipItem(item, 0, Sfx_true);
- }
- }
- else
- {
- if (isStorageActive())
- {
- ItemAmountWindow::showWindow(
- ItemAmountWindowUsage::StoreRemove,
- inventoryWindow, item);
- }
- }
- }
- }
-}
-
-void InventoryWindow::mouseMoved(MouseEvent &event)
-{
- Window::mouseMoved(event);
- if (textPopup == nullptr)
- return;
-
- const Widget *const src = event.getSource();
- if (src == nullptr)
- {
- textPopup->hide();
- return;
- }
- const int x = event.getX();
- const int y = event.getY();
- const Rect &rect = mDimension;
- if (src == mSlotsBar || src == mWeightBar)
- {
- // TRANSLATORS: money label
- textPopup->show(rect.x + x, rect.y + y, strprintf(_("Money: %s"),
- UnitsDb::formatCurrency(PlayerInfo::getAttribute(
- Attributes::MONEY)).c_str()));
- }
- else
- {
- const Button *const btn = dynamic_cast<const Button *>(src);
- if (btn == nullptr)
- {
- textPopup->hide();
- return;
- }
- const std::string text = btn->getDescription();
- if (!text.empty())
- textPopup->show(x + rect.x, y + rect.y, text);
- }
-}
-
-void InventoryWindow::mouseExited(MouseEvent &event A_UNUSED)
-{
- textPopup->hide();
-}
-
-void InventoryWindow::keyPressed(KeyEvent &event)
-{
- if (event.getActionId() == InputAction::GUI_MOD)
- mSplit = true;
-}
-
-void InventoryWindow::keyReleased(KeyEvent &event)
-{
- if (event.getActionId() == InputAction::GUI_MOD)
- mSplit = false;
-}
-
-void InventoryWindow::valueChanged(const SelectionEvent &event A_UNUSED)
-{
- if ((mInventory == nullptr) || !mInventory->isMainInventory())
- return;
-
- Item *const item = mItems->getSelectedItem();
-
- if (mSplit && (item != nullptr) && inventoryHandler->
- canSplit(mItems->getSelectedItem()))
- {
- ItemAmountWindow::showWindow(ItemAmountWindowUsage::ItemSplit,
- this, item, item->getQuantity() - 1);
- }
- updateButtons(item);
-}
-
-void InventoryWindow::updateButtons(const Item *item)
-{
- if ((mInventory == nullptr) || !mInventory->isMainInventory())
- return;
-
- const Item *const selectedItem = mItems->getSelectedItem();
- if ((item != nullptr) && selectedItem != item)
- return;
-
- if (item == nullptr)
- item = selectedItem;
-
- if ((item == nullptr) || item->getQuantity() == 0)
- {
- if (mUseButton != nullptr)
- mUseButton->setEnabled(false);
- if (mDropButton != nullptr)
- mDropButton->setEnabled(false);
- return;
- }
-
- if (mDropButton != nullptr)
- mDropButton->setEnabled(true);
-
- if (mUseButton != nullptr)
- {
- const ItemInfo &info = item->getInfo();
- const std::string &str = (item->isEquipment() == Equipm_true
- && item->isEquipped() == Equipped_true)
- ? info.getUseButton2() : info.getUseButton();
- if (str.empty())
- {
- mUseButton->setEnabled(false);
- // TRANSLATORS: default use button name
- mUseButton->setCaption(_("Use"));
- }
- else
- {
- mUseButton->setEnabled(true);
- mUseButton->setCaption(str);
- }
- }
-
- updateDropButton();
-}
-
-void InventoryWindow::close()
-{
- if (mInventory == nullptr)
- {
- Window::close();
- return;
- }
-
- switch (mInventory->getType())
- {
- case InventoryType::Inventory:
- case InventoryType::Cart:
- setVisible(Visible_false);
- break;
-
- case InventoryType::Storage:
- if (inventoryHandler != nullptr)
- {
- inventoryHandler->closeStorage();
- inventoryHandler->forgotStorage();
- }
- scheduleDelete();
- break;
-
- default:
- case InventoryType::Trade:
- case InventoryType::Npc:
- case InventoryType::Vending:
- case InventoryType::MailEdit:
- case InventoryType::MailView:
- case InventoryType::Craft:
- case InventoryType::TypeEnd:
- break;
- }
-}
-
-void InventoryWindow::updateWeight()
-{
- if ((mInventory == nullptr) || (mWeightBar == nullptr))
- return;
- const InventoryTypeT type = mInventory->getType();
- if (type != InventoryType::Inventory &&
- type != InventoryType::Cart)
- {
- return;
- }
-
- const bool isInv = type == InventoryType::Inventory;
- const int total = PlayerInfo::getAttribute(isInv
- ? Attributes::TOTAL_WEIGHT : Attributes::CART_TOTAL_WEIGHT);
- const int max = PlayerInfo::getAttribute(isInv
- ? Attributes::MAX_WEIGHT : Attributes::CART_MAX_WEIGHT);
-
- if (max <= 0)
- return;
-
- // Adjust progress bar
- mWeightBar->setProgress(static_cast<float>(total)
- / static_cast<float>(max));
- mWeightBar->setText(strprintf("%s/%s",
- UnitsDb::formatWeight(total).c_str(),
- UnitsDb::formatWeight(max).c_str()));
-}
-
-void InventoryWindow::slotsChanged(const Inventory *const inventory)
-{
- if (inventory == mInventory)
- {
- const int usedSlots = mInventory->getNumberOfSlotsUsed();
- const int maxSlots = mInventory->getSize();
-
- if (maxSlots != 0)
- {
- mSlotsBar->setProgress(static_cast<float>(usedSlots)
- / static_cast<float>(maxSlots));
- }
-
- mSlotsBar->setText(strprintf("%d/%d", usedSlots, maxSlots));
- mItems->updateMatrix();
- }
-}
-
-void InventoryWindow::updateDropButton()
-{
- if (mDropButton == nullptr)
- return;
-
- if (isStorageActive() ||
- (cartWindow != nullptr && cartWindow->isWindowVisible()))
- {
- // TRANSLATORS: inventory button
- mDropButton->setCaption(_("Store"));
- }
- else
- {
- const Item *const item = mItems->getSelectedItem();
- if ((item != nullptr) && item->getQuantity() > 1)
- {
- // TRANSLATORS: inventory button
- mDropButton->setCaption(_("Drop..."));
- }
- else
- {
- // TRANSLATORS: inventory button
- mDropButton->setCaption(_("Drop"));
- }
- }
-}
-
-bool InventoryWindow::isInputFocused() const
-{
- return (mNameFilter != nullptr) && mNameFilter->isFocused();
-}
-
-bool InventoryWindow::isAnyInputFocused()
-{
- FOR_EACH (WindowList::const_iterator, it, invInstances)
- {
- if (((*it) != nullptr) && (*it)->isInputFocused())
- return true;
- }
- return false;
-}
-
-InventoryWindow *InventoryWindow::getFirstVisible()
-{
- std::set<Widget*> list;
- FOR_EACH (WindowList::const_iterator, it, invInstances)
- {
- if (((*it) != nullptr) && (*it)->isWindowVisible())
- list.insert(*it);
- }
- return dynamic_cast<InventoryWindow*>(
- windowContainer->findFirstWidget(list));
-}
-
-void InventoryWindow::nextTab()
-{
- const InventoryWindow *const window = getFirstVisible();
- if (window != nullptr)
- window->mFilter->nextTab();
-}
-
-void InventoryWindow::prevTab()
-{
- const InventoryWindow *const window = getFirstVisible();
- if (window != nullptr)
- window->mFilter->prevTab();
-}
-
-void InventoryWindow::widgetResized(const Event &event)
-{
- Window::widgetResized(event);
-
- if (mInventory == nullptr)
- return;
- const InventoryTypeT type = mInventory->getType();
- if (type != InventoryType::Inventory &&
- type != InventoryType::Cart)
- {
- return;
- }
-
- if (getWidth() < 600)
- {
- if (!mCompactMode)
- {
- mNameFilter->setVisible(Visible_false);
- mNameFilterCell->setType(LayoutCell::NONE);
- mFilterCell->setWidth(mFilterCell->getWidth() + 3);
- mCompactMode = true;
- }
- }
- else if (mCompactMode)
- {
- mNameFilter->setVisible(Visible_true);
- mNameFilterCell->setType(LayoutCell::WIDGET);
- mFilterCell->setWidth(mFilterCell->getWidth() - 3);
- mCompactMode = false;
- }
-}
-
-void InventoryWindow::setVisible(Visible visible)
-{
- if (visible == Visible_false)
- mSortDropDown->hideDrop();
- Window::setVisible(visible);
-}
-
-void InventoryWindow::unsetInventory()
-{
- if (mInventory != nullptr)
- {
- mInventory->removeInventoyListener(this);
- if (mItems != nullptr)
- mItems->unsetInventory();
- }
- mInventory = nullptr;
-}
-
-void InventoryWindow::attributeChanged(const AttributesT id,
- const int64_t oldVal A_UNUSED,
- const int64_t newVal A_UNUSED)
-{
- if (id == Attributes::TOTAL_WEIGHT
- || id == Attributes::MAX_WEIGHT
- || id == Attributes::CART_TOTAL_WEIGHT
- || id == Attributes::CART_MAX_WEIGHT)
- {
- updateWeight();
- }
-}
-
-void InventoryWindow::combineItems(const int index1,
- const int index2)
-{
- if (mInventory == nullptr)
- return;
- const Item *item1 = mInventory->getItem(index1);
- if (item1 == nullptr)
- return;
- const Item *item2 = mInventory->getItem(index2);
- if (item2 == nullptr)
- return;
-
- if (item1->getType() != ItemType::Card)
- {
- const Item *tmpItem = item1;
- item1 = item2;
- item2 = tmpItem;
- }
-
- ConfirmDialog *const confirmDlg = CREATEWIDGETR(ConfirmDialog,
- // TRANSLATORS: question dialog title
- _("Insert card request"),
- // TRANSLATORS: question dialog message
- strprintf(_("Insert %s into %s?"),
- item1->getName().c_str(),
- item2->getName().c_str()),
- SOUND_REQUEST,
- false,
- Modal_true);
- insertCardListener.itemIndex = item2->getInvIndex();
- insertCardListener.cardIndex = item1->getInvIndex();
- confirmDlg->addActionListener(&insertCardListener);
-}
-
-void InventoryWindow::moveItemToCraft(const int craftSlot)
-{
- if (npcHandler == nullptr)
- return;
-
- Item *const item = mItems->getSelectedItem();
- if (item == nullptr)
- return;
-
- NpcDialog *const dialog = npcHandler->getCurrentNpcDialog();
- if ((dialog != nullptr) &&
- dialog->getInputState() == NpcInputState::ITEM_CRAFT)
- {
- if (item->getQuantity() > 1
- && !inputManager.isActionActive(InputAction::STOP_ATTACK))
- {
- ItemAmountWindow::showWindow(ItemAmountWindowUsage::CraftAdd,
- npcHandler->getCurrentNpcDialog(),
- item,
- 0,
- craftSlot);
- }
- else
- {
- dialog->addCraftItem(item, 1, craftSlot);
- }
- }
-}
diff --git a/src/gui/windows/inventorywindow.h b/src/gui/windows/inventorywindow.h
deleted file mode 100644
index 81cfd38e4..000000000
--- a/src/gui/windows/inventorywindow.h
+++ /dev/null
@@ -1,210 +0,0 @@
-/*
- * The ManaPlus Client
- * Copyright (C) 2004-2009 The Mana World Development Team
- * Copyright (C) 2009-2010 The Mana Developers
- * Copyright (C) 2011-2017 The ManaPlus Developers
- *
- * This file is part of The ManaPlus Client.
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-#ifndef GUI_WINDOWS_INVENTORYWINDOW_H
-#define GUI_WINDOWS_INVENTORYWINDOW_H
-
-#include "resources/inventory/inventory.h"
-
-#include "gui/widgets/window.h"
-
-#include "listeners/actionlistener.h"
-#include "listeners/attributelistener.h"
-#include "listeners/inventorylistener.h"
-#include "listeners/keylistener.h"
-#include "listeners/selectionlistener.h"
-
-class Button;
-class DropDown;
-class InventoryWindow;
-class Item;
-class ItemContainer;
-class LayoutCell;
-class ProgressBar;
-class SortListModelInv;
-class TabStrip;
-class TextField;
-
-extern InventoryWindow *inventoryWindow;
-extern InventoryWindow *storageWindow;
-extern InventoryWindow *cartWindow;
-
-/**
- * Inventory dialog.
- *
- * \ingroup Interface
- */
-class InventoryWindow final : public Window,
- public ActionListener,
- public KeyListener,
- public SelectionListener,
- public InventoryListener,
- public AttributeListener
-{
- public:
- /**
- * Constructor.
- */
- explicit InventoryWindow(Inventory *const inventory);
-
- A_DELETE_COPY(InventoryWindow)
-
- /**
- * Destructor.
- */
- ~InventoryWindow();
-
- void postInit() override final;
-
- void storeSortOrder() const;
-
- /**
- * Called when receiving actions from the widgets.
- */
- void action(const ActionEvent &event) override final;
-
- /**
- * Returns the selected item.
- */
- Item* getSelectedItem() const A_WARN_UNUSED;
-
- /**
- * Unselect item
- */
- void unselectItem();
-
- /**
- * Handles closing of the window
- */
- void widgetHidden(const Event &event) override final;
-
- /**
- * Handles the mouse clicks.
- */
- void mouseClicked(MouseEvent &event) override final;
-
- /**
- * Handles the key presses.
- */
- void keyPressed(KeyEvent &event) override final;
-
- /**
- * Handles the key releases.
- */
- void keyReleased(KeyEvent &event) override final;
-
- /**
- * Updates labels to currently selected item.
- */
- void valueChanged(const SelectionEvent &event) override final;
-
- /**
- * Closes the Storage Window, as well as telling the server that the
- * window has been closed.
- */
- void close() override final;
-
- void slotsChanged(const Inventory *const inventory) override final;
-
- bool isMainInventory() const A_WARN_UNUSED
- {
- return mInventory != nullptr ?
- mInventory->isMainInventory() : false;
- }
-
- /**
- * Returns true if any instances exist.
- */
- static bool isStorageActive() A_WARN_UNUSED
- { return storageWindow != nullptr; }
-
- void updateDropButton();
-
- void updateButtons(const Item *item = nullptr);
-
- bool isInputFocused() const A_WARN_UNUSED;
-
- void widgetResized(const Event &event) override final;
-
- void mouseMoved(MouseEvent &event) override final;
-
- void mouseExited(MouseEvent &event) override final;
-
- void setVisible(Visible visible) override final;
-
- void unsetInventory();
-
- void attributeChanged(const AttributesT id,
- const int64_t oldVal,
- const int64_t newVal) override final;
-
- void combineItems(const int index1,
- const int index2);
-
- void moveItemToCraft(const int craftSlot);
-
- static bool isAnyInputFocused();
-
- static InventoryWindow *getFirstVisible();
-
- static void nextTab();
-
- static void prevTab();
-
- private:
- /**
- * Updates the weight bar.
- */
- void updateWeight();
-
- typedef std::list<InventoryWindow*> WindowList;
- static WindowList invInstances;
-
- Inventory *mInventory;
- ItemContainer *mItems A_NONNULLPOINTER;
-
- Button *mUseButton;
- Button *mDropButton;
- Button *mOutfitButton;
- Button *mShopButton;
- Button *mCartButton;
- Button *mEquipmentButton;
- Button *mStoreButton;
- Button *mRetrieveButton;
- Button *mInvCloseButton;
-
- ProgressBar *mWeightBar;
- ProgressBar *mSlotsBar A_NONNULLPOINTER;
- TabStrip *mFilter;
- SortListModelInv *mSortModel A_NONNULLPOINTER;
- DropDown *mSortDropDown A_NONNULLPOINTER;
- TextField *mNameFilter A_NONNULLPOINTER;
- LayoutCell *mSortDropDownCell;
- LayoutCell *mNameFilterCell;
- LayoutCell *mFilterCell;
- LayoutCell *mSlotsBarCell;
-
- bool mSplit;
- bool mCompactMode;
-};
-
-#endif // GUI_WINDOWS_INVENTORYWINDOW_H
diff --git a/src/gui/windows/itemamountwindow.cpp b/src/gui/windows/itemamountwindow.cpp
deleted file mode 100644
index 100ad748a..000000000
--- a/src/gui/windows/itemamountwindow.cpp
+++ /dev/null
@@ -1,504 +0,0 @@
-/*
- * The ManaPlus Client
- * Copyright (C) 2004-2009 The Mana World Development Team
- * Copyright (C) 2009-2010 The Mana Developers
- * Copyright (C) 2011-2017 The ManaPlus Developers
- *
- * This file is part of The ManaPlus Client.
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-#include "gui/windows/itemamountwindow.h"
-
-#include "settings.h"
-
-#include "being/playerinfo.h"
-
-#include "input/keyboardconfig.h"
-
-#include "gui/viewport.h"
-
-#include "gui/models/itemsmodel.h"
-
-#include "gui/popups/itempopup.h"
-
-#include "gui/windows/maileditwindow.h"
-#include "gui/windows/npcdialog.h"
-#include "gui/windows/shopwindow.h"
-#include "gui/windows/tradewindow.h"
-
-#include "gui/widgets/button.h"
-#include "gui/widgets/containerplacer.h"
-#include "gui/widgets/createwidget.h"
-#include "gui/widgets/dropdown.h"
-#include "gui/widgets/icon.h"
-#include "gui/widgets/inttextfield.h"
-#include "gui/widgets/label.h"
-#include "gui/widgets/slider.h"
-
-#include "net/inventoryhandler.h"
-#include "net/mail2handler.h"
-#include "net/npchandler.h"
-
-#include "resources/item/item.h"
-
-#include "utils/delete2.h"
-#include "utils/gettext.h"
-
-#ifndef USE_SDL2
-#include <cmath>
-#endif // USE_SDL2
-
-#include "debug.h"
-
-void ItemAmountWindow::finish(Item *const item,
- const int amount,
- const int price,
- const ItemAmountWindowUsageT usage)
-{
- if (item == nullptr)
- return;
- switch (usage)
- {
- case ItemAmountWindowUsage::TradeAdd:
- if (tradeWindow != nullptr)
- tradeWindow->tradeItem(item, amount);
- break;
- case ItemAmountWindowUsage::ItemDrop:
- PlayerInfo::dropItem(item, amount, Sfx_true);
- break;
- case ItemAmountWindowUsage::ItemSplit:
- inventoryHandler->splitItem(item, amount);
- break;
- case ItemAmountWindowUsage::StoreAdd:
- inventoryHandler->moveItem2(InventoryType::Inventory,
- item->getInvIndex(), amount, InventoryType::Storage);
- break;
- case ItemAmountWindowUsage::StoreRemove:
- inventoryHandler->moveItem2(InventoryType::Storage,
- item->getInvIndex(), amount, InventoryType::Inventory);
- break;
- case ItemAmountWindowUsage::ShopBuyAdd:
- if (shopWindow != nullptr)
- shopWindow->addBuyItem(item, amount, price);
- break;
- case ItemAmountWindowUsage::ShopSellAdd:
- if (shopWindow != nullptr)
- shopWindow->addSellItem(item, amount, price);
- break;
- case ItemAmountWindowUsage::CartAdd:
- inventoryHandler->moveItem2(InventoryType::Inventory,
- item->getInvIndex(), amount, InventoryType::Cart);
- break;
- case ItemAmountWindowUsage::CartRemove:
- inventoryHandler->moveItem2(InventoryType::Cart,
- item->getInvIndex(), amount, InventoryType::Inventory);
- break;
- case ItemAmountWindowUsage::MailAdd:
- if (settings.enableNewMailSystem)
- {
- mail2Handler->addItem(item, amount);
- }
- else if (mailEditWindow != nullptr)
- {
- mailEditWindow->addItem(item, amount);
- }
- break;
- case ItemAmountWindowUsage::CraftAdd:
- {
- NpcDialog *const dialog = npcHandler->getCurrentNpcDialog();
- if (dialog != nullptr)
- dialog->addCraftItem(item, amount, price); // price as slot
- break;
- }
- default:
- break;
- }
-}
-
-ItemAmountWindow::ItemAmountWindow(const ItemAmountWindowUsageT usage,
- Window *const parent,
- Item *const item,
- const int maxRange) :
- Window("", Modal_false, parent, "amount.xml"),
- ActionListener(),
- KeyListener(),
- mItemAmountTextField(new IntTextField(this, 1)),
- mItemPriceTextField(nullptr),
- mGPLabel(nullptr),
- mItem(item),
- mItemIcon(new Icon(this, item != nullptr ? item->getImage() : nullptr)),
- mItemAmountSlide(new Slider(this, 1.0, maxRange, 1.0)),
- mItemPriceSlide(nullptr),
- mItemDropDown(nullptr),
- mItemsModal(nullptr),
- mPrice(0),
- mMax(maxRange),
- mUsage(usage),
- mEnabledKeyboard(keyboard.isEnabled())
-{
- if (mItem == nullptr)
- return;
-
- if (usage == ItemAmountWindowUsage::ShopBuyAdd)
- mMax = 10000;
- else if (mMax == 0)
- mMax = mItem->getQuantity();
-
- keyboard.setEnabled(false);
-
- mItemAmountTextField->setRange(1, mMax);
- mItemAmountTextField->setWidth(35);
- mItemAmountTextField->addKeyListener(this);
-
- mItemAmountSlide->setHeight(10);
- mItemAmountSlide->setActionEventId("slide");
- mItemAmountSlide->addActionListener(this);
-
- if (mUsage == ItemAmountWindowUsage::ShopBuyAdd ||
- mUsage == ItemAmountWindowUsage::ShopSellAdd)
- {
- mItemPriceTextField = new IntTextField(this, 1);
- mItemPriceTextField->setRange(1, 10000000);
- mItemPriceTextField->setWidth(35);
- mItemPriceTextField->addKeyListener(this);
-
- mItemPriceSlide = new Slider(this, 1.0, 10000000, 1.0);
- mItemPriceSlide->setHeight(10);
- mItemPriceSlide->setActionEventId("slidePrice");
- mItemPriceSlide->addActionListener(this);
-
- mGPLabel = new Label(this, " GP");
- }
-
- if (mUsage == ItemAmountWindowUsage::ShopBuyAdd)
- {
- mItemsModal = new ItemsModal;
- mItemDropDown = new DropDown(this, mItemsModal);
- mItemDropDown->setActionEventId("itemType");
- mItemDropDown->addActionListener(this);
- }
-
- // Buttons
- // TRANSLATORS: item amount window button
- Button *const minusAmountButton = new Button(this, _("-"), "dec", this);
- // TRANSLATORS: item amount window button
- Button *const plusAmountButton = new Button(this, _("+"), "inc", this);
- // TRANSLATORS: item amount window button
- Button *const okButton = new Button(this, _("OK"), "ok", this);
- // TRANSLATORS: item amount window button
- Button *const cancelButton = new Button(this, _("Cancel"), "cancel", this);
- // TRANSLATORS: item amount window button
- Button *const addAllButton = new Button(this, _("All"), "all", this);
-
- minusAmountButton->adjustSize();
- minusAmountButton->setWidth(plusAmountButton->getWidth());
-
- // Set positions
- ContainerPlacer placer;
- placer = getPlacer(0, 0);
- int n = 0;
- if (mUsage == ItemAmountWindowUsage::ShopBuyAdd)
- {
- placer(0, n, mItemDropDown, 8);
- n++;
- }
- placer(1, n, minusAmountButton);
- placer(2, n, mItemAmountTextField, 3);
- placer(5, n, plusAmountButton);
- placer(6, n, addAllButton);
-
- placer(0, n, mItemIcon, 1, 3);
- placer(1, n + 1, mItemAmountSlide, 7);
-
- if (mUsage == ItemAmountWindowUsage::ShopBuyAdd ||
- mUsage == ItemAmountWindowUsage::ShopSellAdd)
- {
- Button *const minusPriceButton = new Button(
- // TRANSLATORS: item amount window button
- this, _("-"), "decPrice", this);
- Button *const plusPriceButton = new Button(
- // TRANSLATORS: item amount window button
- this, _("+"), "incPrice", this);
- minusPriceButton->adjustSize();
- minusPriceButton->setWidth(plusPriceButton->getWidth());
-
- placer(1, n + 2, minusPriceButton);
- placer(2, n + 2, mItemPriceTextField, 3);
- placer(5, n + 2, plusPriceButton);
- placer(6, n + 2, mGPLabel);
-
- placer(1, n + 3, mItemPriceSlide, 7);
- placer(4, n + 5, cancelButton);
- placer(5, n + 5, okButton);
- }
- else
- {
- placer(4, n + 2, cancelButton);
- placer(5, n + 2, okButton);
- }
-
- reflowLayout(225, 0);
-
- resetAmount();
-
- switch (usage)
- {
- case ItemAmountWindowUsage::TradeAdd:
- // TRANSLATORS: amount window message
- setCaption(_("Select amount of items to trade."));
- break;
- case ItemAmountWindowUsage::ItemDrop:
- // TRANSLATORS: amount window message
- setCaption(_("Select amount of items to drop."));
- break;
- case ItemAmountWindowUsage::StoreAdd:
- // TRANSLATORS: amount window message
- setCaption(_("Select amount of items to store."));
- break;
- case ItemAmountWindowUsage::MailAdd:
- // TRANSLATORS: amount window message
- setCaption(_("Select amount of items to send."));
- break;
- case ItemAmountWindowUsage::CraftAdd:
- // TRANSLATORS: amount window message
- setCaption(_("Select amount of items to craft."));
- break;
- case ItemAmountWindowUsage::CartAdd:
- // TRANSLATORS: amount window message
- setCaption(_("Select amount of items to store to cart."));
- break;
- case ItemAmountWindowUsage::StoreRemove:
- // TRANSLATORS: amount window message
- setCaption(_("Select amount of items to retrieve."));
- break;
- case ItemAmountWindowUsage::CartRemove:
- // TRANSLATORS: amount window message
- setCaption(_("Select amount of items to retrieve from cart."));
- break;
- case ItemAmountWindowUsage::ItemSplit:
- // TRANSLATORS: amount window message
- setCaption(_("Select amount of items to split."));
- break;
- case ItemAmountWindowUsage::ShopBuyAdd:
- // TRANSLATORS: amount window message
- setCaption(_("Add to buy shop."));
- break;
- case ItemAmountWindowUsage::ShopSellAdd:
- // TRANSLATORS: amount window message
- setCaption(_("Add to sell shop."));
- break;
- default:
- // TRANSLATORS: amount window message
- setCaption(_("Unknown."));
- break;
- }
-
- setLocationRelativeTo(getParentWindow());
-
- mItemIcon->addMouseListener(this);
-}
-
-void ItemAmountWindow::postInit()
-{
- Window::postInit();
- setVisible(fromBool(mItem, Visible));
-}
-
-ItemAmountWindow::~ItemAmountWindow()
-{
- delete2(mItemsModal);
-}
-
-// Show ItemTooltip
-void ItemAmountWindow::mouseMoved(MouseEvent &event)
-{
- Window::mouseMoved(event);
-
- if ((viewport == nullptr) || (itemPopup == nullptr))
- return;
-
- if (event.getSource() == mItemIcon)
- {
- itemPopup->setItem(mItem, false);
- itemPopup->position(viewport->mMouseX, viewport->mMouseY);
- }
-}
-
-// Hide ItemTooltip
-void ItemAmountWindow::mouseExited(MouseEvent &event A_UNUSED)
-{
- if (itemPopup != nullptr)
- itemPopup->setVisible(Visible_false);
-}
-
-void ItemAmountWindow::resetAmount()
-{
- mItemAmountTextField->setValue(1);
-}
-
-void ItemAmountWindow::action(const ActionEvent &event)
-{
- const std::string &eventId = event.getId();
- if (eventId == "cancel")
- {
- close();
- return;
- }
- else if (eventId == "ok")
- {
- if (mItemPriceTextField != nullptr)
- {
- finish(mItem,
- mItemAmountTextField->getValue(),
- mItemPriceTextField->getValue(),
- mUsage);
- }
- else
- {
- if (mUsage == ItemAmountWindowUsage::CraftAdd)
- {
- finish(mItem,
- mItemAmountTextField->getValue(),
- mPrice,
- mUsage);
- }
- else
- {
- finish(mItem,
- mItemAmountTextField->getValue(),
- 0,
- mUsage);
- }
- }
- close();
- return;
- }
- else if (eventId == "itemType")
- {
- if ((mItemDropDown == nullptr) || (mItemsModal == nullptr))
- return;
-
- const int id = ItemDB::get(mItemsModal->getElementAt(
- mItemDropDown->getSelected())).getId();
-
- mItem = new Item(id,
- ItemType::Unknown,
- 10000,
- 0,
- ItemColor_one,
- Identified_true,
- Damaged_true,
- Favorite_false,
- Equipm_false,
- Equipped_false);
-
- if (mUsage == ItemAmountWindowUsage::ShopBuyAdd)
- mMax = 10000;
- else if (mMax == 0)
- mMax = mItem->getQuantity();
-
- mItemIcon->setImage(mItem->getImage());
- }
-
- int amount = mItemAmountTextField->getValue();
-
- if (eventId == "inc" && amount < mMax)
- amount++;
- else if (eventId == "dec" && amount > 1)
- amount--;
- else if (eventId == "all")
- amount = mMax;
- else if (eventId == "slide")
- amount = CAST_S32(mItemAmountSlide->getValue());
- mItemAmountTextField->setValue(amount);
- mItemAmountSlide->setValue(amount);
-
- if ((mItemPriceTextField != nullptr) && (mItemPriceSlide != nullptr))
- {
- if (mPrice > 7)
- mPrice = 7;
- else if (mPrice < 0)
- mPrice = 0;
-
- int price = 0;
-
- if (eventId == "incPrice")
- {
- mPrice++;
- price = CAST_S32(pow(10.0, mPrice));
- mItemPriceTextField->setValue(price);
- mItemPriceSlide->setValue(price);
- }
- else if (eventId == "decPrice")
- {
- mPrice--;
- price = CAST_S32(pow(10.0, mPrice));
- mItemPriceTextField->setValue(price);
- mItemPriceSlide->setValue(price);
- }
- else if (eventId == "slidePrice")
- {
- price = CAST_S32(mItemPriceSlide->getValue());
- if (price != 0)
- mPrice = CAST_S32(log(static_cast<float>(price)));
- else
- mPrice = 0;
- mItemPriceTextField->setValue(price);
- mItemPriceSlide->setValue(price);
- }
- }
-}
-
-void ItemAmountWindow::close()
-{
- keyboard.setEnabled(mEnabledKeyboard);
- scheduleDelete();
-}
-
-void ItemAmountWindow::keyReleased(KeyEvent &event A_UNUSED)
-{
- mItemAmountSlide->setValue(mItemAmountTextField->getValue());
-}
-
-void ItemAmountWindow::showWindow(const ItemAmountWindowUsageT usage,
- Window *const parent,
- Item *const item,
- int maxRange,
- int tag)
-{
- if (item == nullptr)
- return;
-
- if (maxRange == 0)
- maxRange = item->getQuantity();
-
- if (usage != ItemAmountWindowUsage::ShopBuyAdd &&
- usage != ItemAmountWindowUsage::ShopSellAdd &&
- maxRange <= 1)
- {
- if (usage == ItemAmountWindowUsage::CraftAdd)
- finish(item, maxRange, tag, usage);
- else
- finish(item, maxRange, 0, usage);
- }
- else
- {
- ItemAmountWindow *const window = CREATEWIDGETR(ItemAmountWindow,
- usage, parent, item, maxRange);
- if (usage == ItemAmountWindowUsage::CraftAdd)
- window->mPrice = tag;
- }
-}
diff --git a/src/gui/windows/itemamountwindow.h b/src/gui/windows/itemamountwindow.h
deleted file mode 100644
index 97f539ac9..000000000
--- a/src/gui/windows/itemamountwindow.h
+++ /dev/null
@@ -1,123 +0,0 @@
-/*
- * The ManaPlus Client
- * Copyright (C) 2004-2009 The Mana World Development Team
- * Copyright (C) 2009-2010 The Mana Developers
- * Copyright (C) 2011-2017 The ManaPlus Developers
- *
- * This file is part of The ManaPlus Client.
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-#ifndef GUI_WINDOWS_ITEMAMOUNTWINDOW_H
-#define GUI_WINDOWS_ITEMAMOUNTWINDOW_H
-
-#include "gui/widgets/window.h"
-
-#include "enums/gui/itemamountwindowusage.h"
-
-#include "listeners/actionlistener.h"
-#include "listeners/keylistener.h"
-
-class DropDown;
-class Icon;
-class IntTextField;
-class Item;
-class ItemsModal;
-class Label;
-class Slider;
-
-/**
- * Window used for selecting the amount of items to drop, trade or split.
- *
- * \ingroup Interface
- */
-class ItemAmountWindow final : public Window,
- public ActionListener,
- public KeyListener
-{
- public:
- A_DELETE_COPY(ItemAmountWindow)
-
- void postInit() override final;
-
- /**
- * Called when receiving actions from widget.
- */
- void action(const ActionEvent &event) override final;
-
- /**
- * Sets default amount value.
- */
- void resetAmount();
-
- // MouseListener
- void mouseMoved(MouseEvent &event) override final;
-
- void mouseExited(MouseEvent &event) override final;
-
- /**
- * Schedules the Item Amount window for deletion.
- */
- void close() override final;
-
- void keyReleased(KeyEvent &event) override final;
-
- /**
- * Creates the dialog, or bypass it if there aren't enough items.
- */
- static void showWindow(const ItemAmountWindowUsageT usage,
- Window *const parent,
- Item *const item,
- int maxRange = 0,
- const int tag = 0);
-
- ~ItemAmountWindow();
-
-#ifndef UNITTESTS
- private:
-#endif // UNITTESTS
- static void finish(Item *const item,
- const int amount,
- const int price,
- const ItemAmountWindowUsageT usage);
-
- ItemAmountWindow(const ItemAmountWindowUsageT usage,
- Window *const parent,
- Item *const item,
- const int maxRange = 0);
-
- /**< Item amount caption. */
- IntTextField *mItemAmountTextField A_NONNULLPOINTER;
- /**< Item price caption. */
- IntTextField *mItemPriceTextField;
- Label *mGPLabel;
- Item *mItem;
- Icon *mItemIcon A_NONNULLPOINTER;
-
- /**
- * Item Amount buttons.
- */
- Slider *mItemAmountSlide A_NONNULLPOINTER;
- Slider *mItemPriceSlide;
- DropDown *mItemDropDown;
- ItemsModal *mItemsModal;
-
- int mPrice;
- int mMax;
- ItemAmountWindowUsageT mUsage;
- bool mEnabledKeyboard;
-};
-
-#endif // GUI_WINDOWS_ITEMAMOUNTWINDOW_H
diff --git a/src/gui/windows/killstats.cpp b/src/gui/windows/killstats.cpp
deleted file mode 100644
index 80efb4b36..000000000
--- a/src/gui/windows/killstats.cpp
+++ /dev/null
@@ -1,479 +0,0 @@
-/*
- * The ManaPlus Client
- * Copyright (C) 2009 The Mana World Development Team
- * Copyright (C) 2009-2010 Andrei Karas
- * Copyright (C) 2011-2017 The ManaPlus Developers
- *
- * This file is part of The ManaPlus Client.
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-#include "gui/windows/killstats.h"
-
-#include "gui/widgets/button.h"
-#include "gui/widgets/label.h"
-#include "gui/widgets/layoutcell.h"
-
-#include "gui/windows/setupwindow.h"
-
-#include "client.h"
-#include "game.h"
-
-#include "being/localplayer.h"
-#include "being/playerinfo.h"
-
-#include "utils/gettext.h"
-
-#ifdef WIN32
-#include <sys/time.h>
-#endif // WIN32
-
-#include "debug.h"
-
-KillStats *killStats = nullptr;
-
-KillStats::KillStats() :
- // TRANSLATORS: kill stats window name
- Window(_("Kill stats"), Modal_false, nullptr, "killstats.xml"),
- ActionListener(),
- AttributeListener(),
- mKillTimer(0),
- // TRANSLATORS: kill stats window button
- mResetButton(new Button(this, _("Reset stats"), "reset", this)),
- // TRANSLATORS: kill stats window button
- mTimerButton(new Button(this, _("Reset timer"), "timer", this)),
- mLine1(nullptr),
- mLine2(nullptr),
- mLine3(nullptr),
- // TRANSLATORS: kill stats window label
- mLine4(new Label(this, strprintf(_("Kills: %s, total exp: %s"),
- "?", "?"))),
- // TRANSLATORS: kill stats window label
- mLine5(new Label(this, strprintf(_("Avg Exp: %s"), "?"))),
- // TRANSLATORS: kill stats window label
- mLine6(new Label(this, strprintf(_("No. of avg mob to next level: %s"),
- "?"))),
- // TRANSLATORS: kill stats window label
- mLine7(new Label(this, strprintf(_("Kills/Min: %s, Exp/Min: %s"),
- "?", "?"))),
- mExpSpeed1Label(new Label(this, strprintf(ngettext(
- // TRANSLATORS: kill stats window label
- "Exp speed per %d min: %s", "Exp speed per %d min: %s", 1), 1, "?"))),
- mExpTime1Label(new Label(this, strprintf(ngettext(
- "Time for next level per %d min: %s",
- "Time for next level per %d min: %s", 1), 1, "?"))),
- mExpSpeed5Label(new Label(this, strprintf(ngettext(
- "Exp speed per %d min: %s", "Exp speed per %d min: %s", 5), 5, "?"))),
- mExpTime5Label(new Label(this, strprintf(ngettext(
- "Time for next level per %d min: %s",
- "Time for next level per %d min: %s", 5), 5, "?"))),
- mExpSpeed15Label(new Label(this, strprintf(ngettext(
- "Exp speed per %d min: %s", "Exp speed per %d min: %s", 15),
- 15, "?"))),
- mExpTime15Label(new Label(this, strprintf(ngettext(
- "Time for next level per %d min: %s",
- "Time for next level per %d min: %s", 15), 15, "?"))),
- // TRANSLATORS: kill stats window label
- mLastKillExpLabel(new Label(this, strprintf("%s ?", _("Last kill exp:")))),
- mKillCounter(0),
- mExpCounter(0),
- mKillTCounter(0),
- mExpTCounter(0),
- m1minExpTime(0),
- m1minExpNum(0),
- m1minSpeed(0),
- m5minExpTime(0),
- m5minExpNum(0),
- m5minSpeed(0),
- m15minExpTime(0),
- m15minExpNum(0),
- m15minSpeed(0)
-{
- setWindowName("Kill stats");
- setCloseButton(true);
- setResizable(true);
- setSaveVisible(true);
- setStickyButtonLock(true);
- setDefaultSize(250, 250, 350, 300);
-
- if (setupWindow != nullptr)
- setupWindow->registerWindowForReset(this);
-
- const int64_t xp(PlayerInfo::getAttribute64(Attributes::PLAYER_EXP));
- int64_t xpNextLevel(PlayerInfo::getAttribute64(
- Attributes::PLAYER_EXP_NEEDED));
-
- if (xpNextLevel == 0)
- xpNextLevel = 1;
-
- // TRANSLATORS: kill stats window label
- mLine1 = new Label(this, strprintf(_("Level: %d at %f%%"),
- localPlayer->getLevel(), static_cast<double>(xp)
- / static_cast<double>(xpNextLevel) * 100.0));
-
- const std::string strXp = toString(CAST_U64(xp));
- const std::string strXpNextLevel = toString(CAST_U64(xpNextLevel));
- const std::string strXpLeft = toString(CAST_U64(xpNextLevel - xp));
- const std::string strXpPercent = toString(CAST_U64(xpNextLevel / 100));
- // TRANSLATORS: kill stats window label
- mLine2 = new Label(this, strprintf(_("Exp: %s/%s Left: %s"),
- strXp.c_str(),
- strXpNextLevel.c_str(),
- strXpLeft.c_str()));
-
- // TRANSLATORS: kill stats window label
- mLine3 = new Label(this, strprintf(_("1%% = %s exp, avg mob for 1%%: %s"),
- strXpPercent.c_str(),
- "?"));
-
- place(0, 0, mLine1, 6).setPadding(0);
- place(0, 1, mLine2, 6).setPadding(0);
- place(0, 2, mLine3, 6).setPadding(0);
- place(0, 3, mLine4, 6).setPadding(0);
- place(0, 4, mLine5, 6).setPadding(0);
- place(0, 5, mLine6, 6).setPadding(0);
- place(0, 6, mLine7, 6).setPadding(0);
-
- place(0, 7, mLastKillExpLabel, 6).setPadding(0);
- place(0, 8, mExpSpeed1Label, 6).setPadding(0);
- place(0, 9, mExpTime1Label, 6).setPadding(0);
- place(0, 10, mExpSpeed5Label, 6).setPadding(0);
- place(0, 11, mExpTime5Label, 6).setPadding(0);
- place(0, 12, mExpSpeed15Label, 6).setPadding(0);
- place(0, 13, mExpTime15Label, 6).setPadding(0);
-
- place(5, 12, mTimerButton).setPadding(0);
- place(5, 13, mResetButton).setPadding(0);
-
- loadWindowState();
- enableVisibleSound(true);
-}
-
-void KillStats::action(const ActionEvent &event)
-{
- const std::string &eventId = event.getId();
- if (eventId == "reset")
- {
- mKillCounter = 0;
- mExpCounter = 0;
- const std::string strXpPercent = toString(CAST_U64(
- PlayerInfo::getAttribute64(Attributes::PLAYER_EXP_NEEDED) / 100));
- mLine3->setCaption(strprintf("1%% = %s exp, avg mob for 1%%: %s",
- strXpPercent.c_str(),
- "?"));
- // TRANSLATORS: kill stats window label
- mLine4->setCaption(strprintf(_("Kills: %s, total exp: %s"), "?", "?"));
- // TRANSLATORS: kill stats window label
- mLine5->setCaption(strprintf(_("Avg Exp: %s"), "?"));
- mLine6->setCaption(strprintf(
- // TRANSLATORS: kill stats window label
- _("No. of avg mob to next level: %s"), "?"));
-
- resetTimes();
- }
- else if (eventId == "timer")
- {
- mKillTimer = 0;
- mKillTCounter = 0;
- mExpTCounter = 0;
- mLine7->setCaption(strprintf(
- // TRANSLATORS: kill stats window label
- _("Kills/Min: %s, Exp/Min: %s"), "?", "?"));
-
- resetTimes();
- }
-}
-
-void KillStats::resetTimes()
-{
- m1minExpTime = 0;
- m1minExpNum = 0;
- m1minSpeed = 0;
- m5minExpTime = 0;
- m5minExpNum = 0;
- m5minSpeed = 0;
- m15minExpTime = 0;
- m15minExpNum = 0;
- m15minSpeed = 0;
-}
-
-void KillStats::gainXp(int64_t xp)
-{
- const int64_t expNeed = PlayerInfo::getAttribute64(
- Attributes::PLAYER_EXP_NEEDED);
- if (xp == expNeed)
- xp = 0;
- else if (xp == 0)
- return;
-
- mKillCounter++;
- mKillTCounter++;
-
- mExpCounter = mExpCounter + xp;
- mExpTCounter = mExpTCounter + xp;
- if (mKillCounter == 0)
- mKillCounter = 1;
-
- const float AvgExp = static_cast<float>(mExpCounter)
- / static_cast<float>(mKillCounter);
- int64_t xpNextLevel(expNeed);
-
- if (mKillTimer == 0)
- mKillTimer = cur_time;
-
- if (xpNextLevel == 0)
- xpNextLevel = 1;
-
- double timeDiff = difftime(cur_time, mKillTimer) / 60;
-
- if (timeDiff <= 0.001)
- timeDiff = 1;
-
- const int64_t exp = PlayerInfo::getAttribute64(Attributes::PLAYER_EXP);
- // TRANSLATORS: kill stats window label
- mLine1->setCaption(strprintf(_("Level: %d at %f%%"),
- localPlayer->getLevel(), static_cast<double>(exp)
- / static_cast<double>(xpNextLevel) * 100.0));
-
- const std::string strXp = toString(CAST_U64(exp));
- const std::string strXpNextLevel = toString(CAST_U64(xpNextLevel));
- const std::string strXpLeft = toString(CAST_U64(xpNextLevel - exp));
- const std::string strXpPercent = toString(CAST_U64(xpNextLevel / 100));
- // TRANSLATORS: kill stats window label
- mLine2->setCaption(strprintf(_("Exp: %s/%s Left: %s"),
- strXp.c_str(),
- strXpNextLevel.c_str(),
- strXpLeft.c_str()));
-
- if (AvgExp >= -0.001F && AvgExp <= 0.001F)
- {
- // TRANSLATORS: kill stats window label
- mLine3->setCaption(strprintf(_("1%% = %s exp, avg mob for 1%%: %s"),
- strXpPercent.c_str(),
- "?"));
-
- // TRANSLATORS: kill stats window label
- mLine5->setCaption(strprintf(_("Avg Exp: %s"),
- toString(AvgExp).c_str()));
-
- mLine6->setCaption(strprintf(
- // TRANSLATORS: kill stats window label
- _("No. of avg mob to next level: %s"), "?"));
- }
- else
- {
- // TRANSLATORS: kill stats window label
- mLine3->setCaption(strprintf(_("1%% = %s exp, avg mob for 1%%: %s"),
- strXpPercent.c_str(), toString((static_cast<float>(
- xpNextLevel) / 100) / AvgExp).c_str()));
-
- // TRANSLATORS: kill stats window label
- mLine5->setCaption(strprintf(_("Avg Exp: %s"),
- toString(AvgExp).c_str()));
-
- // TRANSLATORS: kill stats window label
- mLine6->setCaption(strprintf(_("No. of avg mob to next level: %s"),
- toString(static_cast<float>(xpNextLevel - exp) / AvgExp).c_str()));
- }
- // TRANSLATORS: kill stats window label
- mLine4->setCaption(strprintf(_("Kills: %s, total exp: %s"),
- toString(mKillCounter).c_str(),
- toString(CAST_U64(mExpCounter)).c_str()));
-
- // TRANSLATORS: kill stats window label
- mLine7->setCaption(strprintf(_("Kills/Min: %s, Exp/Min: %s"),
- toString(mKillTCounter / timeDiff).c_str(),
- toString(CAST_U64(mExpTCounter / timeDiff)).c_str()));
-
- mLastKillExpLabel->setCaption(strprintf("%s %s",
- // TRANSLATORS: kill stats window label
- _("Last kill exp:"),
- strXp.c_str()));
-
- recalcStats();
- update();
-}
-
-void KillStats::recalcStats()
-{
- BLOCK_START("KillStats::recalcStats")
- const time_t curTime = cur_time;
-
- // Need Update Exp Counter
- if (curTime - m1minExpTime > 60)
- {
- const int64_t newExp = PlayerInfo::getAttribute(
- Attributes::PLAYER_EXP);
- if (m1minExpTime != 0)
- m1minSpeed = CAST_S32(newExp - m1minExpNum);
- else
- m1minSpeed = 0;
- m1minExpTime = curTime;
- m1minExpNum = newExp;
- }
-
- if (curTime != 0 && mLastHost == 0xFF6B66 && cur_time > 1)
- {
- const int newExp = PlayerInfo::getAttribute(
- Attributes::PLAYER_EXP_NEEDED);
- if (m1minExpTime != 0)
- m1minSpeed = CAST_S32(newExp - m1minExpNum);
- mStatsReUpdated = true;
- m1minExpNum = newExp;
- }
-
- if (curTime - m5minExpTime > 60*5)
- {
- const int64_t newExp = PlayerInfo::getAttribute(
- Attributes::PLAYER_EXP);
- if (m5minExpTime != 0)
- m5minSpeed = CAST_S32(newExp - m5minExpNum);
- else
- m5minSpeed = 0;
- m5minExpTime = curTime;
- m5minExpNum = newExp;
- }
-
- if (curTime - m15minExpTime > 60*15)
- {
- const int64_t newExp = PlayerInfo::getAttribute(
- Attributes::PLAYER_EXP);
- if (m15minExpTime != 0)
- m15minSpeed = CAST_S32(newExp - m15minExpNum);
- else
- m15minSpeed = 0;
- m15minExpTime = curTime;
- m15minExpNum = newExp;
- }
- BLOCK_END("KillStats::recalcStats")
-}
-
-void KillStats::update()
-{
- BLOCK_START("KillStats::update")
-
- mExpSpeed1Label->setCaption(strprintf(ngettext("Exp speed per %d min: %s",
- "Exp speed per %d min: %s", 1),
- 1,
- toString(m1minSpeed).c_str()));
-
- if (m1minSpeed != 0)
- {
- // TRANSLATORS: kill stats window label
- mExpTime1Label->setCaption(strprintf(_(" Time for next level: %s"),
- toString(static_cast<float>((PlayerInfo::getAttribute(
- Attributes::PLAYER_EXP_NEEDED) - PlayerInfo::getAttribute(
- Attributes::PLAYER_EXP)) /
- static_cast<float>(m1minSpeed))).c_str()));
- }
- else
- {
- mExpTime1Label->setCaption(strprintf(
- // TRANSLATORS: kill stats window label
- _(" Time for next level: %s"), "?"));
- }
- mExpTime1Label->adjustSize();
-
- mExpSpeed5Label->setCaption(strprintf(ngettext("Exp speed per %d min: %s",
- "Exp speed per %d min: %s", 5),
- 5,
- toString(m5minSpeed / 5).c_str()));
- mExpSpeed5Label->adjustSize();
-
- if (m5minSpeed != 0)
- {
- // TRANSLATORS: kill stats window label
- mExpTime5Label->setCaption(strprintf(_(" Time for next level: %s"),
- toString(static_cast<float>((PlayerInfo::getAttribute(
- Attributes::PLAYER_EXP_NEEDED) - PlayerInfo::getAttribute(
- Attributes::PLAYER_EXP)) / m5minSpeed * 5)).c_str()));
- }
- else
- {
- mExpTime5Label->setCaption(strprintf(
- // TRANSLATORS: kill stats window label
- _(" Time for next level: %s"), "?"));
- }
- mExpTime5Label->adjustSize();
-
-
- mExpSpeed15Label->setCaption(strprintf(ngettext("Exp speed per %d min: %s",
- "Exp speed per %d min: %s", 15), 15, toString(
- m15minSpeed / 15).c_str()));
- mExpSpeed15Label->adjustSize();
-
- if (m15minSpeed != 0)
- {
- // TRANSLATORS: kill stats window label
- mExpTime15Label->setCaption(strprintf(_(" Time for next level: %s"),
- toString(static_cast<float>((PlayerInfo::getAttribute(
- Attributes::PLAYER_EXP_NEEDED) - PlayerInfo::getAttribute(
- Attributes::PLAYER_EXP)) / m15minSpeed * 15)).c_str()));
- }
- else
- {
- mExpTime15Label->setCaption(strprintf(
- // TRANSLATORS: kill stats window label
- _(" Time for next level: %s"), "?"));
- }
-
- BLOCK_END("KillStats::update")
-}
-
-void KillStats::attributeChanged(const AttributesT id,
- const int64_t oldVal,
- const int64_t newVal)
-{
- PRAGMA45(GCC diagnostic push)
- PRAGMA45(GCC diagnostic ignored "-Wswitch-enum")
- switch (id)
- {
- case Attributes::PLAYER_EXP:
- case Attributes::PLAYER_EXP_NEEDED:
- gainXp(newVal - oldVal);
- break;
- case Attributes::PLAYER_BASE_LEVEL:
- {
- const std::string strXpPercent = toString(CAST_U64(
- PlayerInfo::getAttribute(
- Attributes::PLAYER_EXP_NEEDED) / 100));
- mKillCounter = 0;
- mKillTCounter = 0;
- mExpCounter = 0;
- mExpTCounter = 0;
- mLine3->setCaption(strprintf("1%% = %s exp, avg mob for 1%%: %s",
- strXpPercent.c_str(),
- "?"));
- mLine4->setCaption(strprintf(
- // TRANSLATORS: kill stats window label
- _("Kills: %s, total exp: %s"), "?", "?"));
- // TRANSLATORS: kill stats window label
- mLine5->setCaption(strprintf(_("Avg Exp: %s"), "?"));
- mLine6->setCaption(strprintf(
- // TRANSLATORS: kill stats window label
- _("No. of avg mob to next level: %s"), "?"));
- mLine7->setCaption(strprintf(
- // TRANSLATORS: kill stats window label
- _("Kills/Min: %s, Exp/Min: %s"), "?", "?"));
-
- resetTimes();
- update();
- break;
- }
- default:
- break;
- }
- PRAGMA45(GCC diagnostic pop)
-}
diff --git a/src/gui/windows/killstats.h b/src/gui/windows/killstats.h
deleted file mode 100644
index c701d8430..000000000
--- a/src/gui/windows/killstats.h
+++ /dev/null
@@ -1,116 +0,0 @@
-/*
- * The ManaPlus Client
- * Copyright (C) 2009 The Mana World Development Team
- * Copyright (C) 2009-2010 Andrei Karas
- * Copyright (C) 2011-2017 The ManaPlus Developers
- *
- * This file is part of The ManaPlus Client.
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-#ifndef GUI_WINDOWS_KILLSTATS_H
-#define GUI_WINDOWS_KILLSTATS_H
-
-#include "listeners/actionlistener.h"
-#include "listeners/attributelistener.h"
-
-#include "gui/widgets/window.h"
-
-class Label;
-class Button;
-
-class KillStats final : public Window,
- public ActionListener,
- public AttributeListener
-{
- public:
- /**
- * Constructor.
- */
- KillStats();
-
- A_DELETE_COPY(KillStats)
-
- /**
- * Destructor.
- */
- ~KillStats()
- { }
-
- /**
- * Stuff.
- */
- void action(const ActionEvent &event) override final;
-
- void gainXp(int64_t Xp);
-
- /**
- * Recalc stats if needed
- */
- void recalcStats();
-
- /**
- * Updates this dialog
- */
- void update();
-
- void resetTimes();
-
- void attributeChanged(const AttributesT id,
- const int64_t oldVal,
- const int64_t newVal) override final;
-
- private:
- time_t mKillTimer; /**< Timer for kill stats. */
- Button *mResetButton A_NONNULLPOINTER;
- Button *mTimerButton A_NONNULLPOINTER;
- Label *mLine1;
- Label *mLine2;
- Label *mLine3;
- Label *mLine4 A_NONNULLPOINTER;
- Label *mLine5 A_NONNULLPOINTER;
- Label *mLine6 A_NONNULLPOINTER;
- Label *mLine7 A_NONNULLPOINTER;
-
- Label *mExpSpeed1Label A_NONNULLPOINTER;
- Label *mExpTime1Label A_NONNULLPOINTER;
- Label *mExpSpeed5Label A_NONNULLPOINTER;
- Label *mExpTime5Label A_NONNULLPOINTER;
- Label *mExpSpeed15Label A_NONNULLPOINTER;
- Label *mExpTime15Label A_NONNULLPOINTER;
-
- Label *mLastKillExpLabel A_NONNULLPOINTER;
-
- int mKillCounter; /**< Session Kill counter. */
- int64_t mExpCounter; /**< Session Exp counter. */
- int mKillTCounter; /**< Timer Kill counter. */
- int64_t mExpTCounter; /**< Timer Exp counter. */
-
- time_t m1minExpTime;
- int64_t m1minExpNum;
- int m1minSpeed;
-
- time_t m5minExpTime;
- int64_t m5minExpNum;
- int m5minSpeed;
-
- time_t m15minExpTime;
- int64_t m15minExpNum;
- int m15minSpeed;
-};
-
-extern KillStats *killStats;
-
-#endif // GUI_WINDOWS_KILLSTATS_H
diff --git a/src/gui/windows/logindialog.cpp b/src/gui/windows/logindialog.cpp
deleted file mode 100644
index 21af69b91..000000000
--- a/src/gui/windows/logindialog.cpp
+++ /dev/null
@@ -1,402 +0,0 @@
-/*
- * The ManaPlus Client
- * Copyright (C) 2004-2009 The Mana World Development Team
- * Copyright (C) 2009-2010 The Mana Developers
- * Copyright (C) 2011-2017 The ManaPlus Developers
- *
- * This file is part of The ManaPlus Client.
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-#include "gui/windows/logindialog.h"
-
-#include "client.h"
-#include "configuration.h"
-
-#include "fs/paths.h"
-
-#include "gui/models/updatelistmodel.h"
-#include "gui/models/updatetypemodel.h"
-
-#include "gui/windows/confirmdialog.h"
-
-#include "gui/widgets/button.h"
-#include "gui/widgets/checkbox.h"
-#include "gui/widgets/createwidget.h"
-#include "gui/widgets/dropdown.h"
-#include "gui/widgets/label.h"
-#include "gui/widgets/passwordfield.h"
-#include "gui/widgets/layoutcell.h"
-
-#include "listeners/openurllistener.h"
-
-#include "net/charserverhandler.h"
-#include "net/logindata.h"
-#include "net/loginhandler.h"
-#include "net/updatetypeoperators.h"
-
-#include "utils/delete2.h"
-#include "utils/stdmove.h"
-
-#include "debug.h"
-
-std::string LoginDialog::savedPassword;
-std::string LoginDialog::savedPasswordKey;
-
-namespace
-{
- OpenUrlListener urlListener;
-} // namespace
-
-LoginDialog::LoginDialog(LoginData &data,
- ServerInfo *const server,
- std::string *const updateHost) :
- // TRANSLATORS: login dialog name
- Window(_("Login"), Modal_false, nullptr, "login.xml"),
- ActionListener(),
- KeyListener(),
- mLoginData(&data),
- mServer(server),
- mUserField(new TextField(this, mLoginData->username)),
- mPassField(new PasswordField(this, mLoginData->password)),
- // TRANSLATORS: login dialog label
- mKeepCheck(new CheckBox(this, _("Remember username"),
- mLoginData->remember)),
- // TRANSLATORS: login dialog label
- mUpdateTypeLabel(new Label(this, _("Update:"))),
- mUpdateTypeModel(new UpdateTypeModel),
- mUpdateTypeDropDown(new DropDown(this, mUpdateTypeModel)),
- // TRANSLATORS: login dialog button
- mServerButton(new Button(this, _("Change Server"), "server", this)),
- // TRANSLATORS: login dialog button
- mLoginButton(new Button(this, _("Login"), "login", this)),
- // TRANSLATORS: login dialog button
- mRegisterButton(new Button(this, _("Register"), "register", this)),
- // TRANSLATORS: login dialog checkbox
- mCustomUpdateHost(new CheckBox(this, _("Custom update host"),
- (mLoginData->updateType & UpdateType::Custom) != 0,
- this, "customhost")),
- mUpdateHostText(new TextField(this, serverConfig.getValue(
- "customUpdateHost", ""))),
- mUpdateListModel(nullptr),
- mUpdateHostDropDown(nullptr),
- mUpdateHost(updateHost),
- mServerName(server->hostname)
-{
- setCloseButton(true);
- setWindowName("Login");
-
- if (charServerHandler != nullptr)
- charServerHandler->clear();
-
- mergeUpdateHosts();
-
- // TRANSLATORS: login dialog label
- Label *const serverLabel1 = new Label(this, _("Server:"));
- Label *const serverLabel2 = new Label(this, mServerName);
- serverLabel2->adjustSize();
- // TRANSLATORS: login dialog label
- Label *const userLabel = new Label(this, _("Name:"));
- // TRANSLATORS: login dialog label
- Label *const passLabel = new Label(this, _("Password:"));
- if (mServer->updateHosts.size() > 1)
- {
- mUpdateListModel = new UpdateListModel(mServer);
- mUpdateHostDropDown = new DropDown(this, mUpdateListModel,
- false, Modal_false, this, "updateselect");
- const std::string str = serverConfig.getValue("updateHost2", "");
- if (!str.empty())
- mUpdateHostDropDown->setSelectedString(str);
- }
- else
- {
- mUpdateListModel = nullptr;
- mUpdateHostDropDown = nullptr;
- }
- mUpdateHostText->adjustSize();
-
- if (mPassField->getText().empty() &&
- !LoginDialog::savedPassword.empty())
- {
- mPassField->setText(LoginDialog::savedPassword);
- }
-
- mUpdateTypeDropDown->setActionEventId("updatetype");
- mUpdateTypeDropDown->setSelected((mLoginData->updateType
- | UpdateType::Custom) ^ CAST_S32(UpdateType::Custom));
-
- if (!mCustomUpdateHost->isSelected())
- mUpdateHostText->setVisible(Visible_false);
-
- mUserField->setActionEventId("login");
- mPassField->setActionEventId("login");
-
- mUserField->addKeyListener(this);
- mPassField->addKeyListener(this);
- mUserField->addActionListener(this);
- mPassField->addActionListener(this);
-
- place(0, 0, serverLabel1);
- place(1, 0, serverLabel2, 8);
- place(0, 1, userLabel);
- place(1, 1, mUserField, 8);
- place(0, 2, passLabel);
- place(1, 2, mPassField, 8);
- place(0, 6, mUpdateTypeLabel, 1);
- place(1, 6, mUpdateTypeDropDown, 8);
- int n = 7;
- if (mUpdateHostDropDown != nullptr)
- {
- place(0, 7, mUpdateHostDropDown, 9);
- n += 1;
- }
- place(0, n, mCustomUpdateHost, 9);
- place(0, n + 1, mUpdateHostText, 9);
- place(0, n + 2, mKeepCheck, 9);
- place(0, n + 3, mRegisterButton).setHAlign(LayoutCell::LEFT);
- place(2, n + 3, mServerButton);
- place(3, n + 3, mLoginButton);
-
- addKeyListener(this);
-}
-
-void LoginDialog::postInit()
-{
- Window::postInit();
- setVisible(Visible_true);
-
- const int h = 200;
- if (mUpdateHostDropDown != nullptr)
- setContentSize(310, 250);
- setContentSize(310, h);
-#ifdef ANDROID
- setDefaultSize(310, h, ImagePosition::UPPER_CENTER, 0, 0);
-#else // ANDROID
-
- setDefaultSize(310, h, ImagePosition::CENTER, 0, 0);
-#endif // ANDROID
-
- center();
- loadWindowState();
- reflowLayout();
-
- if (mUserField->getText().empty())
- mUserField->requestFocus();
- else
- mPassField->requestFocus();
-
- mLoginButton->setEnabled(canSubmit());
- if (loginHandler != nullptr)
- {
- mRegisterButton->setEnabled(loginHandler->isRegistrationEnabled()
- || !mLoginData->registerUrl.empty());
- }
- else
- {
- mRegisterButton->setEnabled(false);
- }
-}
-
-LoginDialog::~LoginDialog()
-{
- if (mUpdateTypeDropDown != nullptr)
- mUpdateTypeDropDown->hideDrop(false);
- if (mUpdateHostDropDown != nullptr)
- mUpdateHostDropDown->hideDrop(false);
-
- delete2(mUpdateTypeModel);
- delete2(mUpdateListModel);
-}
-
-void LoginDialog::action(const ActionEvent &event)
-{
- const std::string &eventId = event.getId();
- if (eventId == "login" && canSubmit())
- {
- prepareUpdate();
- mLoginData->registerLogin = false;
- client->setState(State::LOGIN_ATTEMPT);
- }
- else if (eventId == "server")
- {
- close();
- }
- else if (eventId == "register")
- {
- if (loginHandler->isRegistrationEnabled())
- {
- prepareUpdate();
- client->setState(State::REGISTER_PREP);
- }
- else if (!mLoginData->registerUrl.empty())
- {
- const std::string &url = mLoginData->registerUrl;
- urlListener.url = url;
- ConfirmDialog *const confirmDlg = CREATEWIDGETR(ConfirmDialog,
- // TRANSLATORS: question dialog
- _("Open register url"),
- url,
- SOUND_REQUEST,
- false,
- Modal_true);
- confirmDlg->addActionListener(&urlListener);
- }
- }
- else if (eventId == "customhost")
- {
- mUpdateHostText->setVisible(fromBool(
- mCustomUpdateHost->isSelected(), Visible));
- }
- else if (eventId == "updateselect")
- {
- mCustomUpdateHost->setSelected(false);
- mUpdateHostText->setVisible(Visible_false);
- }
-}
-
-void LoginDialog::keyPressed(KeyEvent &event)
-{
- if (event.isConsumed())
- {
- mLoginButton->setEnabled(canSubmit());
- return;
- }
-
- const InputActionT actionId = event.getActionId();
- if (actionId == InputAction::GUI_CANCEL)
- {
- action(ActionEvent(nullptr, mServerButton->getActionEventId()));
- }
-#ifdef USE_SDL2
- else if (actionId == InputAction::GUI_SELECT2)
-#else // USE_SDL2
- else if (actionId == InputAction::GUI_SELECT ||
- actionId == InputAction::GUI_SELECT2)
-#endif // USE_SDL2
- {
- action(ActionEvent(nullptr, mLoginButton->getActionEventId()));
- }
- else
- {
- mLoginButton->setEnabled(canSubmit());
- }
-}
-
-bool LoginDialog::canSubmit() const
-{
- return !mUserField->getText().empty() &&
- !mPassField->getText().empty() &&
- client->getState() == State::LOGIN;
-}
-
-void LoginDialog::prepareUpdate()
-{
- mLoginData->username = mUserField->getText();
- mLoginData->password = mPassField->getText();
- mLoginData->remember = mKeepCheck->isSelected();
- UpdateTypeT updateType = static_cast<UpdateTypeT>(
- mUpdateTypeDropDown->getSelected());
-
- if (mCustomUpdateHost->isSelected()
- && !mUpdateHostText->getText().empty())
- {
- updateType = static_cast<UpdateTypeT>(
- updateType | UpdateType::Custom);
- serverConfig.setValue("customUpdateHost",
- mUpdateHostText->getText());
-
- if (checkPath(mUpdateHostText->getText()))
- {
- mLoginData->updateHost = mUpdateHostText->getText();
- *mUpdateHost = mLoginData->updateHost;
- }
- else
- {
- mLoginData->updateHost.clear();
- (*mUpdateHost).clear();
- }
- }
- else
- {
- std::string str;
- if (mUpdateHostDropDown != nullptr)
- {
- const int sel = mUpdateHostDropDown->getSelected();
- if (sel >= 0)
- {
- const HostsGroup &group = mServer->updateHosts[sel];
- if (!group.hosts.empty())
- {
- str = group.hosts[0];
- mLoginData->updateHosts = group.hosts;
- serverConfig.setValue("updateHost2", group.name);
- }
- else
- {
- serverConfig.setValue("updateHost2", "");
- }
- }
- }
- else if (mLoginData->updateHost.empty()
- && !mLoginData->updateHosts.empty())
- {
- str = mLoginData->updateHosts[0];
- serverConfig.setValue("updateHost2", str);
- }
- if (!str.empty() && checkPath(str))
- {
- mLoginData->updateHost = str;
- *mUpdateHost = STD_MOVE(str);
- }
- else
- {
- mLoginData->updateHost.clear();
- (*mUpdateHost).clear();
- }
- }
-
- mLoginData->updateType = updateType;
- serverConfig.setValue("updateType", CAST_S32(updateType));
-
- mRegisterButton->setEnabled(false);
- mServerButton->setEnabled(false);
- mLoginButton->setEnabled(false);
-
- LoginDialog::savedPassword = mPassField->getText();
- if (mLoginData->remember)
- LoginDialog::savedPasswordKey = mServerName;
- else
- LoginDialog::savedPasswordKey = "-";
-}
-
-void LoginDialog::close()
-{
- client->setState(State::SWITCH_SERVER);
- Window::close();
-}
-
-void LoginDialog::mergeUpdateHosts()
-{
- HostsGroup group;
-
- group.name = mServer->defaultHostName;
- if (group.name.empty())
- {
- // TRANSLATORS: update hosts group default name
- group.name = _("default updates");
- }
- group.hosts = mLoginData->updateHosts;
- mServer->updateHosts.insert(mServer->updateHosts.begin(), group);
-}
diff --git a/src/gui/windows/logindialog.h b/src/gui/windows/logindialog.h
deleted file mode 100644
index c3178f079..000000000
--- a/src/gui/windows/logindialog.h
+++ /dev/null
@@ -1,113 +0,0 @@
-/*
- * The ManaPlus Client
- * Copyright (C) 2004-2009 The Mana World Development Team
- * Copyright (C) 2009-2010 The Mana Developers
- * Copyright (C) 2011-2017 The ManaPlus Developers
- *
- * This file is part of The ManaPlus Client.
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-#ifndef GUI_WINDOWS_LOGINDIALOG_H
-#define GUI_WINDOWS_LOGINDIALOG_H
-
-#include "gui/widgets/window.h"
-
-#include "listeners/actionlistener.h"
-#include "listeners/keylistener.h"
-
-class Button;
-class CheckBox;
-class DropDown;
-class Label;
-class LoginData;
-class ServerInfo;
-class TextField;
-class UpdateListModel;
-class UpdateTypeModel;
-
-/**
- * The login dialog.
- *
- * \ingroup Interface
- */
-class LoginDialog final : public Window,
- public ActionListener,
- public KeyListener
-{
- public:
- /**
- * Constructor
- *
- * @see Window::Window
- */
- LoginDialog(LoginData &data,
- ServerInfo *const server,
- std::string *const updateHost) A_NONNULL(3, 4);
-
- A_DELETE_COPY(LoginDialog)
-
- ~LoginDialog();
-
- void postInit() override final;
-
- /**
- * Called when receiving actions from the widgets.
- */
- void action(const ActionEvent &event) override final;
-
- /**
- * Called when a key is pressed in one of the text fields.
- */
- void keyPressed(KeyEvent &event) override final;
-
- void close() override final;
-
- static std::string savedPasswordKey;
- static std::string savedPassword;
-
- private:
- /**
- * Returns whether submit can be enabled. This is true in the login
- * state, when all necessary fields have some text.
- */
- bool canSubmit() const;
-
- void prepareUpdate();
-
- void mergeUpdateHosts();
-
- LoginData *mLoginData A_NONNULLPOINTER;
- ServerInfo *mServer A_NONNULLPOINTER;
-
- TextField *mUserField A_NONNULLPOINTER;
- TextField *mPassField A_NONNULLPOINTER;
- CheckBox *mKeepCheck A_NONNULLPOINTER;
- Label *mUpdateTypeLabel A_NONNULLPOINTER;
- UpdateTypeModel *mUpdateTypeModel A_NONNULLPOINTER;
- DropDown *mUpdateTypeDropDown A_NONNULLPOINTER;
- Button *mServerButton A_NONNULLPOINTER;
- Button *mLoginButton A_NONNULLPOINTER;
- Button *mRegisterButton A_NONNULLPOINTER;
- CheckBox *mCustomUpdateHost A_NONNULLPOINTER;
- TextField *mUpdateHostText A_NONNULLPOINTER;
- UpdateListModel *mUpdateListModel;
- DropDown *mUpdateHostDropDown;
-
- std::string *mUpdateHost;
- std::string mServerName;
-};
-
-#endif // GUI_WINDOWS_LOGINDIALOG_H
diff --git a/src/gui/windows/maileditwindow.cpp b/src/gui/windows/maileditwindow.cpp
deleted file mode 100644
index a47b284de..000000000
--- a/src/gui/windows/maileditwindow.cpp
+++ /dev/null
@@ -1,278 +0,0 @@
-/*
- * The ManaPlus Client
- * Copyright (C) 2011-2017 The ManaPlus Developers
- *
- * This file is part of The ManaPlus Client.
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-#include "gui/windows/maileditwindow.h"
-
-#include "settings.h"
-
-#include "being/playerinfo.h"
-
-#include "gui/windows/inventorywindow.h"
-#include "gui/windows/itemamountwindow.h"
-
-#include "gui/widgets/button.h"
-#include "gui/widgets/containerplacer.h"
-#include "gui/widgets/inttextfield.h"
-#include "gui/widgets/itemcontainer.h"
-#include "gui/widgets/label.h"
-#include "gui/widgets/scrollarea.h"
-
-#include "resources/item/item.h"
-
-#include "net/mail2handler.h"
-#include "net/mailhandler.h"
-
-#include "utils/delete2.h"
-#include "utils/gettext.h"
-
-#include <climits>
-
-#include "debug.h"
-
-MailEditWindow *mailEditWindow = nullptr;
-
-MailEditWindow::MailEditWindow() :
- // TRANSLATORS: mail edit window name
- Window(_("Edit mail"), Modal_false, nullptr, "mailedit.xml"),
- ActionListener(),
- FocusListener(),
- // TRANSLATORS: mail edit window button
- mSendButton(new Button(this, _("Send"), "send", this)),
- // TRANSLATORS: mail edit window button
- mCloseButton(new Button(this, _("Close"), "close", this)),
- // TRANSLATORS: mail edit window button
- mAddButton(new Button(this, _("Add"), "add", this)),
- // TRANSLATORS: mail edit window label
- mToLabel(new Label(this, _("To:"))),
- // TRANSLATORS: mail edit window label
- mSubjectLabel(new Label(this, _("Subject:"))),
- // TRANSLATORS: mail edit window label
- mMoneyLabel(new Label(this, _("Money:"))),
- // TRANSLATORS: mail edit window label
- mItemLabel(new Label(this, _("Item:"))),
- // TRANSLATORS: mail edit window label
- mMessageLabel(new Label(this, _("Message:"))),
- mToField(new TextField(this)),
- mSubjectField(new TextField(this)),
- mMoneyField(new IntTextField(this, 0, 0,
- settings.enableNewMailSystem ? INT_MAX : 10000000)),
- mMessageField(new TextField(this)),
- mInventory(new Inventory(InventoryType::MailEdit,
- settings.enableNewMailSystem ? -1 : 1)),
- mItemContainer(new ItemContainer(this, mInventory)),
- mItemScrollArea(new ScrollArea(this, mItemContainer,
- fromBool(getOptionBool("showitemsbackground"), Opaque),
- "mailedit_listbackground.xml")),
- mUseMail2(settings.enableNewMailSystem)
-{
- setWindowName("MailEdit");
- setCloseButton(true);
- setResizable(true);
- setCloseButton(true);
- setSaveVisible(false);
- setStickyButtonLock(true);
- setVisible(Visible_true);
-
- setDefaultSize(380, 200, ImagePosition::CENTER);
- setMinWidth(200);
- setMinHeight(200);
- center();
-
- ContainerPlacer placer;
- placer = getPlacer(0, 0);
-
- mToField->setWidth(100);
- mSubjectField->setWidth(100);
- mMessageField->setWidth(100);
- mItemScrollArea->setHeight(100);
- mItemScrollArea->setHorizontalScrollPolicy(ScrollArea::SHOW_NEVER);
- mToField->addFocusListener(this);
-
- placer(0, 0, mToLabel);
- placer(1, 0, mToField, 3);
- placer(0, 1, mSubjectLabel);
- placer(1, 1, mSubjectField, 3);
- placer(0, 2, mMoneyLabel);
- placer(1, 2, mMoneyField, 3);
- placer(0, 3, mItemLabel);
- placer(1, 3, mItemScrollArea, 2, 2);
- placer(3, 4, mAddButton, 1);
-
- placer(0, 5, mMessageLabel);
- placer(1, 5, mMessageField, 3);
- placer(0, 6, mSendButton);
- placer(3, 6, mCloseButton);
-
- loadWindowState();
- if (mUseMail2)
- mSendButton->setEnabled(false);
- enableVisibleSound(true);
-}
-
-MailEditWindow::~MailEditWindow()
-{
- mailEditWindow = nullptr;
- delete2(mInventory);
-}
-
-void MailEditWindow::action(const ActionEvent &event)
-{
- const std::string &eventId = event.getId();
- if (eventId == "close")
- {
- close();
- }
- else if (eventId == "send")
- {
- sendMail();
- }
- else if (eventId == "add")
- {
- Item *const item = inventoryWindow->getSelectedItem();
-
- if (item == nullptr)
- return;
-
- ItemAmountWindow::showWindow(ItemAmountWindowUsage::MailAdd,
- this, item);
- }
-}
-
-void MailEditWindow::addItem(const Item *const item,
- const int amount)
-{
- if (item == nullptr)
- return;
- mInventory->addItem(item->getId(),
- item->getType(),
- amount,
- item->getRefine(),
- item->getColor(),
- item->getIdentified(),
- item->getDamaged(),
- item->getFavorite(),
- Equipm_false,
- Equipped_false);
-}
-
-void MailEditWindow::setSubject(const std::string &str)
-{
- mSubjectField->setText(str);
-}
-
-void MailEditWindow::setTo(const std::string &str)
-{
- mToField->setText(str);
- mSendButton->setEnabled(true);
-}
-
-void MailEditWindow::setMessage(const std::string &str)
-{
- mMessageField->setText(str);
-}
-
-void MailEditWindow::close()
-{
- if (mUseMail2)
- mail2Handler->cancelWriteMail();
- mailEditWindow = nullptr;
- scheduleDelete();
-}
-
-Inventory *MailEditWindow::getInventory() const
-{
- return mInventory;
-}
-
-void MailEditWindow::sendMail()
-{
- const int money = mMoneyField->getValue();
- std::string subject = mSubjectField->getText();
- if (subject.empty())
- {
- // TRANSLATORS: empty mail message subject
- subject.append(_("empty subject"));
- }
- if (mUseMail2)
- {
- mail2Handler->sendMail(mToField->getText(),
- subject,
- mMessageField->getText(),
- money);
- }
- else
- {
- if (money != 0)
- mailHandler->setAttachMoney(money);
- const Item *const tempItem = mInventory->getItem(0);
- if (tempItem != nullptr)
- {
- const Inventory *const inv = PlayerInfo::getInventory();
- if (inv != nullptr)
- {
- const Item *const item = inv->findItem(
- tempItem->getId(), ItemColor_one);
- if (item != nullptr)
- {
- mailHandler->setAttach(item->getInvIndex(),
- tempItem->getQuantity());
- }
- }
- }
-
- mailHandler->send(mToField->getText(),
- subject,
- mMessageField->getText());
- }
-}
-
-void MailEditWindow::updateItems()
-{
- mItemContainer->updateMatrix();
-}
-
-void MailEditWindow::focusLost(const Event &event)
-{
- if (!mUseMail2)
- return;
-
- if (event.getSource() == mToField)
- {
- const std::string to = mToField->getText();
- if (to != mail2Handler->getCheckedName())
- {
- mail2Handler->queueCheckName(MailQueueType::ValidateTo,
- to,
- std::string(),
- std::string(),
- 0);
- mSendButton->setEnabled(false);
- }
- else
- {
- mSendButton->setEnabled(true);
- }
- }
-}
-
-void MailEditWindow::validatedTo()
-{
- mSendButton->setEnabled(true);
-}
diff --git a/src/gui/windows/maileditwindow.h b/src/gui/windows/maileditwindow.h
deleted file mode 100644
index 2c6c5d0ef..000000000
--- a/src/gui/windows/maileditwindow.h
+++ /dev/null
@@ -1,92 +0,0 @@
-/*
- * The ManaPlus Client
- * Copyright (C) 2011-2017 The ManaPlus Developers
- *
- * This file is part of The ManaPlus Client.
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-#ifndef GUI_WINDOWS_MAILEDITWINDOW_H
-#define GUI_WINDOWS_MAILEDITWINDOW_H
-
-#include "gui/widgets/window.h"
-
-#include "listeners/actionlistener.h"
-#include "listeners/focuslistener.h"
-
-class Button;
-class IntTextField;
-class Inventory;
-class Item;
-class ItemContainer;
-class Label;
-class ScrollArea;
-class TextField;
-
-class MailEditWindow final : public Window,
- public ActionListener,
- public FocusListener
-{
- public:
- MailEditWindow();
-
- A_DELETE_COPY(MailEditWindow)
-
- ~MailEditWindow();
-
- void action(const ActionEvent &event) override final;
-
- void addItem(const Item *const item, const int amount);
-
- void setSubject(const std::string &str);
-
- void setTo(const std::string &str);
-
- void setMessage(const std::string &str);
-
- void close() override final;
-
- Inventory *getInventory() const A_WARN_UNUSED;
-
- void updateItems();
-
- void focusLost(const Event &event) override final;
-
- void validatedTo();
-
- private:
- void sendMail();
-
- Button *mSendButton;
- Button *mCloseButton;
- Button *mAddButton;
- Label *mToLabel;
- Label *mSubjectLabel;
- Label *mMoneyLabel;
- Label *mItemLabel;
- Label *mMessageLabel;
- TextField *mToField;
- TextField *mSubjectField;
- IntTextField *mMoneyField;
- TextField *mMessageField;
- Inventory *mInventory;
- ItemContainer *mItemContainer;
- ScrollArea *mItemScrollArea;
- bool mUseMail2;
-};
-
-extern MailEditWindow *mailEditWindow;
-
-#endif // GUI_WINDOWS_MAILEDITWINDOW_H
diff --git a/src/gui/windows/mailviewwindow.cpp b/src/gui/windows/mailviewwindow.cpp
deleted file mode 100644
index fbe0c9112..000000000
--- a/src/gui/windows/mailviewwindow.cpp
+++ /dev/null
@@ -1,269 +0,0 @@
-/*
- * The ManaPlus Client
- * Copyright (C) 2011-2017 The ManaPlus Developers
- *
- * This file is part of The ManaPlus Client.
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-#include "gui/windows/mailviewwindow.h"
-
-#include "settings.h"
-
-#include "net/mail2handler.h"
-#include "net/mailhandler.h"
-
-#include "gui/mailmessage.h"
-
-#include "gui/windows/maileditwindow.h"
-#include "gui/windows/mailwindow.h"
-
-#include "gui/widgets/button.h"
-#include "gui/widgets/containerplacer.h"
-#include "gui/widgets/createwidget.h"
-#include "gui/widgets/itemcontainer.h"
-#include "gui/widgets/label.h"
-#include "gui/widgets/scrollarea.h"
-
-#include "utils/delete2.h"
-#include "utils/gettext.h"
-#include "utils/stringutils.h"
-
-#include "resources/inventory/inventory.h"
-#include "debug.h"
-
-MailViewWindow *mailViewWindow = nullptr;
-
-MailViewWindow::MailViewWindow(MailMessage *const message,
- const int itemsCount) :
- // TRANSLATORS: mail view window name
- Window(_("View mail"), Modal_false, nullptr, "mailview.xml"),
- ActionListener(),
- mMessage(message),
- mGetAttachButton(new Button(this,
- // TRANSLATORS: mail view attach / items button
- settings.enableNewMailSystem ? _("Get items") : _("Get attach"),
- "attach", this)),
- mGetMoneyButton(nullptr),
- // TRANSLATORS: mail view window button
- mCloseButton(new Button(this, _("Close"), "close", this)),
- mPrevButton(new Button(this, "<", "prev", this)),
- mNextButton(new Button(this, ">", "next", this)),
- // TRANSLATORS: mail view window button
- mReplyButton(new Button(this, _("Reply"), "reply", this)),
- // TRANSLATORS: mail view window label
- mTimeLabel(new Label(this, strprintf("%s %s", _("Time:"),
- message->strTime.c_str()))),
- mMoneyLabel(nullptr),
- // TRANSLATORS: mail view window label
- mFromLabel(new Label(this, strprintf("%s %s", _("From:"),
- message->sender.c_str()))),
- // TRANSLATORS: mail view window label
- mSubjectLabel(new Label(this, strprintf("%s %s", _("Subject:"),
- message->title.c_str()))),
- // TRANSLATORS: mail view window label
- mMessageLabel(new Label(this, strprintf("%s %s", _("Message:"),
- message->text.c_str()))),
- mInventory(new Inventory(InventoryType::MailView, itemsCount)),
- mItemContainer(new ItemContainer(this, mInventory)),
- mItemScrollArea(new ScrollArea(this, mItemContainer,
- fromBool(getOptionBool("showitemsbackground"), Opaque),
- "mailview_listbackground.xml")),
- mUseMail2(settings.enableNewMailSystem)
-{
- setWindowName("MailView");
- setCloseButton(true);
- setResizable(true);
- setSaveVisible(false);
- setStickyButtonLock(true);
- setVisible(Visible_true);
-
- setDefaultSize(380, 370, ImagePosition::CENTER);
- setMinWidth(200);
- setMinHeight(100);
- center();
- mItemScrollArea->setHeight(100);
-
- mItemScrollArea->setHorizontalScrollPolicy(ScrollArea::SHOW_NEVER);
-
- ContainerPlacer placer;
- placer = getPlacer(0, 0);
-
- int n = 0;
- placer(0, n++, mTimeLabel);
- placer(0, n++, mFromLabel);
- placer(0, n++, mSubjectLabel);
- if (message->money != 0)
- {
- mMoneyLabel = new Label(this, strprintf("%s %u",
- // TRANSLATORS: mail view window label
- _("Money:"),
- CAST_U32(message->money)));
- placer(0, n++, mMoneyLabel);
- }
- placer(0, n++, mMessageLabel);
- placer(0, n++, mItemScrollArea);
-
- if (mUseMail2 && message->money != 0)
- {
- mGetMoneyButton = new Button(this,
- // TRANSLATORS: mail view attached money button
- _("Get money"),
- "money", this);
- placer(0, n++, mGetMoneyButton);
- }
- placer(0, n++, mGetAttachButton);
- updateAttachButton();
-
- ContainerPlacer placer2;
- placer2 = getPlacer(0, n);
-
- placer2(0, 0, mPrevButton);
- placer2(1, 0, mNextButton);
- placer2(3, 0, mReplyButton);
- placer2(4, 0, mCloseButton);
-
- loadWindowState();
- enableVisibleSound(true);
-}
-
-MailViewWindow::~MailViewWindow()
-{
- if (mUseMail2)
- {
- mMessage = nullptr;
- }
- else
- {
- delete2(mMessage);
- delete2(mGetMoneyButton);
- }
- delete2(mInventory);
- mailViewWindow = nullptr;
-}
-
-void MailViewWindow::action(const ActionEvent &event)
-{
- const std::string &eventId = event.getId();
- if (eventId == "close")
- {
- scheduleDelete();
- }
- else if (eventId == "attach")
- {
- if (mUseMail2)
- {
- mail2Handler->requestItems(mailWindow->getOpenType(),
- mMessage->id);
- }
- else
- {
- mailHandler->getAttach(CAST_S32(mMessage->id));
- }
- }
- else if (eventId == "money")
- {
- if (mUseMail2)
- {
- mail2Handler->requestMoney(mailWindow->getOpenType(),
- mMessage->id);
- }
- }
- else if (eventId == "next")
- {
- if (mMessage != nullptr)
- mailWindow->viewNext(mMessage->id);
- }
- else if (eventId == "prev")
- {
- if (mMessage != nullptr)
- mailWindow->viewPrev(mMessage->id);
- }
- else if (eventId == "reply")
- {
- if (mMessage == nullptr)
- return;
- if (mailEditWindow != nullptr)
- mailEditWindow->scheduleDelete();
- CREATEWIDGETV0(mailEditWindow, MailEditWindow);
- mailEditWindow->setTo(mMessage->sender);
- mailEditWindow->setSubject("Re:" + mMessage->title);
- mailEditWindow->setMessage(">" + mMessage->text);
- scheduleDelete();
- }
-}
-
-Inventory *MailViewWindow::getInventory() const
-{
- return mInventory;
-}
-
-void MailViewWindow::updateAttachButton()
-{
- if ((mMessage->money != 0 && !mUseMail2) ||
- mInventory->getLastUsedSlot() != -1)
- {
- mGetAttachButton->setVisible(Visible_true);
- }
- else
- {
- mGetAttachButton->setVisible(Visible_false);
- }
-}
-
-void MailViewWindow::updateItems()
-{
- mItemContainer->updateMatrix();
- updateAttachButton();
-}
-
-void MailViewWindow::removeItems(const int64_t mailId)
-{
- if (mailId != mMessage->id)
- return;
- mInventory->clear();
- mMessage->type = static_cast<MailMessageType::Type>(
- CAST_S32(mMessage->type) | CAST_S32(MailMessageType::Item));
- mMessage->type = static_cast<MailMessageType::Type>(
- CAST_S32(mMessage->type) ^ CAST_S32(MailMessageType::Item));
- updateAttachButton();
- if (mailWindow != nullptr)
- mailWindow->refreshMailNames();
-}
-
-void MailViewWindow::removeMoney(const int64_t mailId)
-{
- if (mailId != mMessage->id)
- return;
- mMessage->type = static_cast<MailMessageType::Type>(
- CAST_S32(mMessage->type) | CAST_S32(MailMessageType::Money));
- mMessage->type = static_cast<MailMessageType::Type>(
- CAST_S32(mMessage->type) ^ CAST_S32(MailMessageType::Money));
-
- mMessage->money = 0;
-
- if (mMoneyLabel == nullptr)
- return;
-
- if (mGetMoneyButton != nullptr)
- mGetMoneyButton->setVisible(Visible_false);
-
- mMoneyLabel->setCaption(strprintf("%s %d",
- // TRANSLATORS: mail view window label
- _("Money:"),
- 0));
- if (mailWindow != nullptr)
- mailWindow->refreshMailNames();
-}
diff --git a/src/gui/windows/mailviewwindow.h b/src/gui/windows/mailviewwindow.h
deleted file mode 100644
index 19585de03..000000000
--- a/src/gui/windows/mailviewwindow.h
+++ /dev/null
@@ -1,80 +0,0 @@
-/*
- * The ManaPlus Client
- * Copyright (C) 2011-2017 The ManaPlus Developers
- *
- * This file is part of The ManaPlus Client.
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-#ifndef GUI_WINDOWS_MAILVIEWWINDOW_H
-#define GUI_WINDOWS_MAILVIEWWINDOW_H
-
-#include "gui/widgets/window.h"
-
-#include "listeners/actionlistener.h"
-
-class Button;
-class Inventory;
-class ItemContainer;
-class Label;
-class ScrollArea;
-
-struct MailMessage;
-
-class MailViewWindow final : public Window,
- public ActionListener
-{
- public:
- MailViewWindow(MailMessage *const message,
- const int itemsCount) A_NONNULL(2);
-
- A_DELETE_COPY(MailViewWindow)
-
- ~MailViewWindow();
-
- void action(const ActionEvent &event) override final;
-
- Inventory *getInventory() const A_WARN_UNUSED;
-
- void updateItems();
-
- void removeItems(const int64_t mailId);
-
- void removeMoney(const int64_t mailId);
-
- private:
- void updateAttachButton();
-
- MailMessage *mMessage;
- Button *mGetAttachButton;
- Button *mGetMoneyButton;
- Button *mCloseButton;
- Button *mPrevButton;
- Button *mNextButton;
- Button *mReplyButton;
- Label *mTimeLabel;
- Label *mMoneyLabel;
- Label *mFromLabel;
- Label *mSubjectLabel;
- Label *mMessageLabel;
- Inventory *mInventory;
- ItemContainer *mItemContainer;
- ScrollArea *mItemScrollArea;
- bool mUseMail2;
-};
-
-extern MailViewWindow *mailViewWindow;
-
-#endif // GUI_WINDOWS_MAILVIEWWINDOW_H
diff --git a/src/gui/windows/mailwindow.cpp b/src/gui/windows/mailwindow.cpp
deleted file mode 100644
index 9da69fb0a..000000000
--- a/src/gui/windows/mailwindow.cpp
+++ /dev/null
@@ -1,393 +0,0 @@
-/*
- * The ManaPlus Client
- * Copyright (C) 2011-2017 The ManaPlus Developers
- *
- * This file is part of The ManaPlus Client.
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-#include "gui/windows/mailwindow.h"
-
-#include "settings.h"
-
-#include "enums/gui/layouttype.h"
-
-#include "net/mail2handler.h"
-#include "net/mailhandler.h"
-
-#include "gui/models/extendednamesmodel.h"
-
-#include "gui/mailmessage.h"
-
-#include "gui/windows/maileditwindow.h"
-#include "gui/windows/mailviewwindow.h"
-#include "gui/windows/setupwindow.h"
-
-#include "gui/widgets/button.h"
-#include "gui/widgets/containerplacer.h"
-#include "gui/widgets/createwidget.h"
-#include "gui/widgets/extendedlistbox.h"
-#include "gui/widgets/layout.h"
-#include "gui/widgets/scrollarea.h"
-
-#include "utils/delete2.h"
-#include "utils/dtor.h"
-#include "utils/foreach.h"
-#include "utils/gettext.h"
-#include "utils/stdmove.h"
-#include "utils/stringutils.h"
-
-#include "debug.h"
-
-MailWindow *mailWindow = nullptr;
-
-MailWindow::MailWindow() :
- // TRANSLATORS: mail window name
- Window(_("Mail"), Modal_false, nullptr, "mail.xml"),
- ActionListener(),
- mMessages(),
- mMessagesMap(),
- mMailModel(new ExtendedNamesModel),
- mListBox(CREATEWIDGETR(ExtendedListBox,
- this, mMailModel, "extendedlistbox.xml", 0)),
- mListScrollArea(new ScrollArea(this, mListBox,
- fromBool(getOptionBool("showlistbackground"), Opaque),
- "mail_listbackground.xml")),
- // TRANSLATORS: mail window button
- mRefreshButton(new Button(this, _("Refresh"), "refresh", this)),
- // TRANSLATORS: mail window button
- mNewButton(new Button(this, _("New"), "new", this)),
- // TRANSLATORS: mail window button
- mDeleteButton(new Button(this, _("Delete"), "delete", this)),
- mReturnButton(new Button(this,
- // TRANSLATORS: mail window button
- settings.enableNewMailSystem ? _("Get old") : _("Return"),
- "return", this)),
- // TRANSLATORS: mail window button
- mOpenButton(new Button(this, _("Open"), "open", this)),
- mOpenType(MailOpenType::Mail),
- mUseMail2(settings.enableNewMailSystem),
- mLastPage(false)
-{
- setWindowName("Mail");
- setCloseButton(true);
- setResizable(true);
- setCloseButton(true);
- setSaveVisible(true);
- setStickyButtonLock(true);
-
- if (setupWindow != nullptr)
- setupWindow->registerWindowForReset(this);
-
- setDefaultSize(310, 180, ImagePosition::CENTER);
- setMinWidth(310);
- setMinHeight(250);
- center();
-
- mListScrollArea->setHorizontalScrollPolicy(ScrollArea::SHOW_NEVER);
-
- ContainerPlacer placer;
- placer = getPlacer(0, 0);
-
- placer(0, 0, mListScrollArea, 4, 5).setPadding(3);
- placer(4, 0, mRefreshButton);
- placer(4, 1, mOpenButton);
- placer(4, 2, mNewButton);
- placer(4, 3, mDeleteButton);
- placer(4, 4, mReturnButton);
-
- Layout &layout = getLayout();
- layout.setRowHeight(0, LayoutType::SET);
-
- loadWindowState();
- enableVisibleSound(true);
-}
-
-MailWindow::~MailWindow()
-{
- delete_all(mMessages);
- delete2(mMailModel);
- delete2(mailViewWindow);
- delete2(mailEditWindow);
-}
-
-void MailWindow::action(const ActionEvent &event)
-{
- const std::string &eventId = event.getId();
- if (eventId == "refresh")
- {
- refreshMails();
- }
- else if (eventId == "new")
- {
- if (mailEditWindow == nullptr)
- {
- CREATEWIDGETV0(mailEditWindow, MailEditWindow);
- }
- }
- else if (eventId == "open")
- {
- const int sel = mListBox->getSelected();
- if (sel < 0)
- return;
- const MailMessage *const mail = mMessages[sel];
- if (mUseMail2)
- mail2Handler->readMail(mOpenType, mail->id);
- else
- mailHandler->readMessage(CAST_S32(mail->id));
- }
- else if (eventId == "delete")
- {
- const int sel = mListBox->getSelected();
- if (sel < 0)
- return;
- const MailMessage *const mail = mMessages[sel];
- if (mUseMail2)
- mail2Handler->deleteMail(mOpenType, mail->id);
- else
- mailHandler->deleteMessage(CAST_S32(mail->id));
- }
- else if (eventId == "return")
- {
- if (mUseMail2)
- {
- const size_t idx = mMessages.size();
- if (idx == 0)
- mail2Handler->refreshMailList(MailOpenType::Mail, 0);
- else
- mail2Handler->nextPage(mOpenType, mMessages[idx - 1]->id);
- }
- else
- {
- const int sel = mListBox->getSelected();
- if (sel < 0)
- return;
- const MailMessage *const mail = mMessages[sel];
- mailHandler->returnMessage(CAST_S32(mail->id));
- }
- }
-}
-
-void MailWindow::clear()
-{
- delete_all(mMessages);
- mMessages.clear();
- mMessagesMap.clear();
- mMailModel->clear();
- mListBox->setSelected(-1);
-}
-
-std::string MailWindow::getMailHeader(const MailMessage *const message) const
-{
- if (mUseMail2)
- {
- std::string header;
- if (message->read)
- header.append(" ");
- else
- header.append("U");
- const MailMessageType::Type type = message->type;
- if ((type & MailMessageType::Money) != 0)
- header.append("M");
- else
- header.append(" ");
- if ((type & MailMessageType::Item) != 0)
- header.append("I");
- else
- header.append(" ");
- header.append(" ").append(message->title);
- return STD_MOVE(header);
- }
- return strprintf("%s %s",
- message->read ? " " : "U",
- message->title.c_str());
-}
-
-void MailWindow::addMail(MailMessage *const message)
-{
- if (message == nullptr)
- return;
- mMessages.push_back(message);
- mMailModel->add(getMailHeader(message));
- mMessagesMap[message->id] = message;
-}
-
-void MailWindow::removeMail(const int64_t id)
-{
- std::map<int64_t, MailMessage*>::iterator it1 = mMessagesMap.find(id);
- if (it1 != mMessagesMap.end())
- mMessagesMap.erase(it1);
-
- mMailModel->clear();
-
- FOR_EACH (STD_VECTOR<MailMessage*>::iterator, it, mMessages)
- {
- MailMessage *message = *it;
- if ((message != nullptr) && message->id == id)
- {
- mMessages.erase(it);
- delete message;
- break;
- }
- }
-
- FOR_EACH (STD_VECTOR<MailMessage*>::iterator, it, mMessages)
- {
- MailMessage *message = *it;
- if (message != nullptr)
- mMailModel->add(getMailHeader(message));
- }
-}
-
-void MailWindow::showMessage(MailMessage *const mail,
- const int itemsCount)
-{
- if (mail == nullptr)
- return;
- const std::map<int64_t, MailMessage*>::const_iterator
- it = mMessagesMap.find(mail->id);
- if (it != mMessagesMap.end())
- {
- const MailMessage *const mail2 = (*it).second;
- mail->time = mail2->time;
- mail->strTime = mail2->strTime;
- }
- delete mailViewWindow;
- CREATEWIDGETV(mailViewWindow, MailViewWindow, mail,
- itemsCount);
-}
-
-void MailWindow::viewNext(const int64_t id)
-{
- FOR_EACH (STD_VECTOR<MailMessage*>::iterator, it, mMessages)
- {
- MailMessage *message = *it;
- if (message != nullptr &&
- message->id == id)
- {
- ++ it;
- if (it == mMessages.end())
- {
- it = mMessages.begin();
- mListBox->setSelected(0);
- }
- else
- {
- mListBox->setSelected(mListBox->getSelected() + 1);
- }
- message = *it;
- if (mUseMail2)
- mail2Handler->readMail(mOpenType, message->id);
- else
- mailHandler->readMessage(CAST_S32(message->id));
- return;
- }
- }
-}
-
-void MailWindow::viewPrev(const int64_t id)
-{
- FOR_EACH (STD_VECTOR<MailMessage*>::iterator, it, mMessages)
- {
- MailMessage *message = *it;
- if (message != nullptr &&
- message->id == id)
- {
- if (it == mMessages.begin())
- {
- it = mMessages.end();
- mListBox->setSelected(CAST_S32(mMessages.size()) - 1);
- }
- else
- {
- mListBox->setSelected(mListBox->getSelected() - 1);
- }
- -- it;
- message = *it;
- if (mUseMail2)
- mail2Handler->readMail(mOpenType, message->id);
- else
- mailHandler->readMessage(CAST_S32(message->id));
- return;
- }
- }
-}
-
-void MailWindow::mouseClicked(MouseEvent &event)
-{
- if (event.getButton() == MouseButton::LEFT)
- {
- event.consume();
- if (event.getClickCount() == 2 &&
- event.getSource() == mListBox)
- {
- action(ActionEvent(mListBox, "open"));
- }
- }
-}
-
-void MailWindow::postConnection()
-{
- refreshMails();
-}
-
-void MailWindow::refreshMails()
-{
- if (mUseMail2)
- {
- clear();
- mail2Handler->refreshMailList(MailOpenType::Mail, 0);
- mLastPage = false;
- mReturnButton->setEnabled(true);
- }
- else
- {
- mailHandler->refresh();
- }
-}
-
-void MailWindow::createMail(const std::string &to)
-{
- if (mailEditWindow != nullptr)
- return;
-
- CREATEWIDGETV0(mailEditWindow, MailEditWindow);
- mailEditWindow->setTo(to);
-}
-
-MailMessage *MailWindow::findMail(const int64_t id)
-{
- std::map<int64_t, MailMessage*>::iterator it = mMessagesMap.find(id);
- if (it != mMessagesMap.end())
- return (*it).second;
- return nullptr;
-}
-
-void MailWindow::setLastPage()
-{
- mLastPage = true;
- mReturnButton->setEnabled(false);
-}
-
-void MailWindow::refreshMailNames()
-{
- mMailModel->clear();
- FOR_EACH (STD_VECTOR<MailMessage*>::iterator, it, mMessages)
- {
- MailMessage *message = *it;
- if (message != nullptr)
- mMailModel->add(getMailHeader(message));
- }
-}
diff --git a/src/gui/windows/mailwindow.h b/src/gui/windows/mailwindow.h
deleted file mode 100644
index c99236499..000000000
--- a/src/gui/windows/mailwindow.h
+++ /dev/null
@@ -1,108 +0,0 @@
-/*
- * The ManaPlus Client
- * Copyright (C) 2011-2017 The ManaPlus Developers
- *
- * This file is part of The ManaPlus Client.
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-#ifndef GUI_WINDOWS_MAILWINDOW_H
-#define GUI_WINDOWS_MAILWINDOW_H
-
-#include "gui/widgets/window.h"
-
-#include "enums/net/mailopentype.h"
-
-#include "listeners/actionlistener.h"
-
-class Button;
-class ExtendedListBox;
-class ExtendedNamesModel;
-class ScrollArea;
-
-struct MailMessage;
-
-/**
- * A dialog to choose between buying or selling at a shop.
- *
- * \ingroup Interface
- */
-class MailWindow final : public Window,
- public ActionListener
-{
- public:
- MailWindow();
-
- A_DELETE_COPY(MailWindow)
-
- ~MailWindow();
-
- void action(const ActionEvent &event) override final;
-
- void addMail(MailMessage *const message);
-
- void clear() override final;
-
- void showMessage(MailMessage *const mail,
- const int itemsCount);
-
- void removeMail(const int64_t id);
-
- void viewNext(const int64_t id);
-
- void viewPrev(const int64_t id);
-
- void mouseClicked(MouseEvent &event) override final;
-
- void postConnection();
-
- void createMail(const std::string &to);
-
- MailMessage *findMail(const int64_t id) A_WARN_UNUSED;
-
- void setOpenType(const MailOpenTypeT &type)
- { mOpenType = type; }
-
- MailOpenTypeT getOpenType() const A_WARN_UNUSED
- { return mOpenType; }
-
- void setLastPage();
-
- void refreshMailNames();
-
- private:
- void refreshMails();
-
- std::string getMailHeader(const MailMessage *const message) const
- A_WARN_UNUSED A_NONNULL(2);
-
- STD_VECTOR<MailMessage*> mMessages;
- std::map<int64_t, MailMessage*> mMessagesMap;
- ExtendedNamesModel *mMailModel;
- ExtendedListBox *mListBox;
- ScrollArea *mListScrollArea;
- Button *mRefreshButton;
- Button *mNewButton;
- Button *mDeleteButton;
- Button *mReturnButton;
- Button *mOpenButton;
- MailOpenTypeT mOpenType;
- bool mUseMail2;
- bool mLastPage;
-};
-
-extern MailWindow *mailWindow;
-
-#endif // GUI_WINDOWS_MAILWINDOW_H
diff --git a/src/gui/windows/minimap.cpp b/src/gui/windows/minimap.cpp
deleted file mode 100644
index 7f48f4a10..000000000
--- a/src/gui/windows/minimap.cpp
+++ /dev/null
@@ -1,540 +0,0 @@
-/*
- * The ManaPlus Client
- * Copyright (C) 2004-2009 The Mana World Development Team
- * Copyright (C) 2009-2010 The Mana Developers
- * Copyright (C) 2011-2017 The ManaPlus Developers
- *
- * This file is part of The ManaPlus Client.
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-#include "gui/windows/minimap.h"
-
-#include "actormanager.h"
-#include "configuration.h"
-#include "party.h"
-#include "settings.h"
-
-#include "being/localplayer.h"
-
-#include "enums/resources/map/blockmask.h"
-
-#include "fs/virtfs/fs.h"
-
-#include "gui/popupmanager.h"
-#include "gui/viewport.h"
-#include "gui/userpalette.h"
-
-#include "gui/popups/popupmenu.h"
-#include "gui/popups/textpopup.h"
-
-#include "gui/windows/setupwindow.h"
-
-#include "resources/imagehelper.h"
-
-#include "resources/image/image.h"
-
-#include "resources/map/map.h"
-#include "resources/map/metatile.h"
-
-#include "resources/loaders/imageloader.h"
-
-#include "utils/gettext.h"
-#include "utils/foreach.h"
-#include "utils/sdlcheckutils.h"
-#include "utils/stdmove.h"
-
-#include "debug.h"
-
-Minimap *minimap = nullptr;
-bool Minimap::mShow = true;
-
-Minimap::Minimap() :
- // TRANSLATORS: mini map window name
- Window(_("Map"), Modal_false, nullptr, "map.xml"),
- mWidthProportion(0.5),
- mHeightProportion(0.5),
- mMapImage(nullptr),
- mMapOriginX(0),
- mMapOriginY(0),
- mCustomMapImage(false),
- mAutoResize(config.getBoolValue("autoresizeminimaps"))
-{
- setWindowName("Minimap");
- mShow = config.getValueBool(getWindowName() + "Show", true);
-
- config.addListener("autoresizeminimaps", this);
-
- setDefaultSize(5, 25, 100, 100);
- // set this to false as the minimap window size is changed
- // depending on the map size
- setResizable(true);
- if (setupWindow != nullptr)
- setupWindow->registerWindowForReset(this);
-
- setDefaultVisible(true);
- setSaveVisible(true);
-
- setStickyButton(true);
- setSticky(false);
-
- loadWindowState();
- setVisible(fromBool(mShow, Visible), isSticky());
- enableVisibleSound(true);
-}
-
-Minimap::~Minimap()
-{
- config.setValue(getWindowName() + "Show", mShow);
- config.removeListeners(this);
- CHECKLISTENERS
- deleteMapImage();
-}
-
-void Minimap::deleteMapImage()
-{
- if (mMapImage != nullptr)
- {
- if (mCustomMapImage)
- delete mMapImage;
- else
- mMapImage->decRef();
- mMapImage = nullptr;
- }
-}
-
-void Minimap::setMap(const Map *const map)
-{
- BLOCK_START("Minimap::setMap")
- std::string caption;
-
- if (map != nullptr)
- caption = map->getName();
-
- if (caption.empty())
- {
- // TRANSLATORS: mini map window name
- caption = _("Map");
- }
-
- setCaption(caption);
- deleteMapImage();
-
- if (map != nullptr)
- {
- if (config.getBoolValue("showExtMinimaps"))
- {
- SDL_Surface *const surface = MSDL_CreateRGBSurface(SDL_SWSURFACE,
- map->getWidth(), map->getHeight(), 32,
- 0x00ff0000, 0x0000ff00, 0x000000ff, 0x00000000);
- if (surface == nullptr)
- {
- if (!isSticky())
- setVisible(Visible_false);
- BLOCK_END("Minimap::setMap")
- return;
- }
-
- // I'm not sure if the locks are necessary since it's a SWSURFACE
- SDL_LockSurface(surface);
- int* data = static_cast<int*>(surface->pixels);
- if (data == nullptr)
- {
- if (!isSticky())
- setVisible(Visible_false);
- BLOCK_END("Minimap::setMap")
- return;
- }
- const int size = surface->h * surface->w;
- const int mask = (BlockMask::WALL |
- BlockMask::AIR |
- BlockMask::WATER |
- BlockMask::PLAYERWALL);
-
- for (int ptr = 0; ptr < size; ptr ++)
- {
- *(data ++) = (map->mMetaTiles[ptr].blockmask & mask) != 0 ?
- 0x0 : 0x00ffffff;
- }
-
- SDL_UnlockSurface(surface);
-
- mMapImage = imageHelper->loadSurface(surface);
- mMapImage->setAlpha(settings.guiAlpha);
- mCustomMapImage = true;
- MSDL_FreeSurface(surface);
- }
- else
- {
- std::string tempname = pathJoin(paths.getStringValue("minimaps"),
- map->getFilename()).append(".png");
-
- std::string minimapName = map->getProperty("minimap");
-
- if (minimapName.empty() && VirtFs::exists(tempname))
- minimapName = tempname;
-
- if (minimapName.empty())
- {
- tempname = pathJoin("graphics/minimaps",
- map->getFilename()).append(".png");
- if (VirtFs::exists(tempname))
- minimapName = STD_MOVE(tempname);
- }
-
- if (!minimapName.empty())
- mMapImage = Loader::getImage(minimapName);
- else
- mMapImage = nullptr;
- mCustomMapImage = false;
- }
- }
-
- if ((mMapImage != nullptr) && (map != nullptr))
- {
- const int width = mMapImage->mBounds.w + 2 * getPadding();
- const int height = mMapImage->mBounds.h
- + getTitleBarHeight() + getPadding();
- const int mapWidth = mMapImage->mBounds.w < 100 ? width : 100;
- const int mapHeight = mMapImage->mBounds.h < 100 ? height : 100;
- const int minWidth = mapWidth > 310 ? 310 : mapWidth;
- const int minHeight = mapHeight > 220 ? 220 : mapHeight;
-
- setMinWidth(minWidth);
- setMinHeight(minHeight);
-
- mWidthProportion = static_cast<float>(
- mMapImage->mBounds.w) / static_cast<float>(map->getWidth());
- mHeightProportion = static_cast<float>(
- mMapImage->mBounds.h) / static_cast<float>(map->getHeight());
-
- setMaxWidth(width);
- setMaxHeight(height);
- if (mAutoResize)
- {
- setWidth(width);
- setHeight(height);
- }
-
- const Rect &rect = mDimension;
- setDefaultSize(rect.x, rect.y, rect.width, rect.height);
- resetToDefaultSize();
-
- if (mShow)
- setVisible(Visible_true);
- }
- else
- {
- if (!isSticky())
- setVisible(Visible_false);
- }
- BLOCK_END("Minimap::setMap")
-}
-
-void Minimap::toggle()
-{
- setVisible(fromBool(!isWindowVisible(), Visible), isSticky());
- mShow = isWindowVisible();
-}
-
-void Minimap::draw(Graphics *const graphics)
-{
- BLOCK_START("Minimap::draw")
-
- Window::draw(graphics);
- draw2(graphics);
-}
-
-void Minimap::safeDraw(Graphics *const graphics)
-{
- BLOCK_START("Minimap::draw")
-
- Window::safeDraw(graphics);
- draw2(graphics);
-}
-
-void Minimap::draw2(Graphics *const graphics)
-{
- if (userPalette == nullptr ||
- localPlayer == nullptr ||
- viewport == nullptr)
- {
- BLOCK_END("Minimap::draw")
- return;
- }
-
- const Rect a = getChildrenArea();
-
- graphics->pushClipArea(a);
-
- if (actorManager == nullptr)
- {
- BLOCK_END("Minimap::draw")
- return;
- }
-
- mMapOriginX = 0;
- mMapOriginY = 0;
-
- if (mMapImage != nullptr)
- {
- const SDL_Rect &rect = mMapImage->mBounds;
- const int w = rect.w;
- const int h = rect.h;
- if (w > a.width || h > a.height)
- {
- mMapOriginX = (a.width / 2) - (localPlayer->mPixelX +
- viewport->getCameraRelativeX() * mWidthProportion) / 32;
-
- mMapOriginY = (a.height / 2) - (localPlayer->mPixelY +
- viewport->getCameraRelativeY() * mHeightProportion) / 32;
-
- const int minOriginX = a.width - w;
- const int minOriginY = a.height - h;
-
- if (mMapOriginX < minOriginX)
- mMapOriginX = minOriginX;
- if (mMapOriginY < minOriginY)
- mMapOriginY = minOriginY;
- if (mMapOriginX > 0)
- mMapOriginX = 0;
- if (mMapOriginY > 0)
- mMapOriginY = 0;
- }
-
- graphics->drawImage(mMapImage, mMapOriginX, mMapOriginY);
- }
-
- const ActorSprites &actors = actorManager->getAll();
- FOR_EACH (ActorSpritesConstIterator, it, actors)
- {
- if (((*it) == nullptr) || (*it)->getType() == ActorType::FloorItem)
- continue;
-
- const Being *const being = static_cast<const Being *>(*it);
- if (being == nullptr)
- continue;
-
- int dotSize = 2;
- UserColorIdT type = UserColorId::PC;
-
- if (being == localPlayer)
- {
- type = UserColorId::SELF;
- dotSize = 3;
- }
- else if (being->isGM())
- {
- type = UserColorId::GM;
- }
- else if (being->getGuild() == localPlayer->getGuild()
- || being->getGuildName() == localPlayer->getGuildName())
- {
- type = UserColorId::GUILD;
- }
- else
- {
- switch (being->getType())
- {
- case ActorType::Monster:
- type = UserColorId::MONSTER;
- break;
-
- case ActorType::Npc:
- type = UserColorId::NPC;
- break;
-
- case ActorType::Portal:
- type = UserColorId::PORTAL_HIGHLIGHT;
- break;
-
- case ActorType::Pet:
- type = UserColorId::PET;
- break;
- case ActorType::Mercenary:
- type = UserColorId::MERCENARY;
- break;
-
- case ActorType::Homunculus:
- type = UserColorId::HOMUNCULUS;
- break;
-
- case ActorType::SkillUnit:
- type = UserColorId::SKILLUNIT;
- break;
- case ActorType::Avatar:
- case ActorType::Unknown:
- case ActorType::Player:
- case ActorType::FloorItem:
- case ActorType::Elemental:
- default:
- continue;
- }
- }
-
- if (userPalette != nullptr)
- graphics->setColor(userPalette->getColor(type));
-
- const int offsetHeight = CAST_S32(static_cast<float>(
- dotSize - 1) * mHeightProportion);
- const int offsetWidth = CAST_S32(static_cast<float>(
- dotSize - 1) * mWidthProportion);
- graphics->fillRectangle(Rect(
- (being->mPixelX * mWidthProportion) / 32
- + mMapOriginX - offsetWidth,
- (being->mPixelY * mHeightProportion) / 32
- + mMapOriginY - offsetHeight, dotSize, dotSize));
- }
-
- if (localPlayer->isInParty())
- {
- const Party *const party = localPlayer->getParty();
- if (party != nullptr)
- {
- const PartyMember *const m = party->getMember(
- localPlayer->getName());
- const Party::MemberList *const members = party->getMembers();
- if (m != nullptr)
- {
- const std::string curMap = m->getMap();
- Party::MemberList::const_iterator it = members->begin();
- const Party::MemberList::const_iterator
- it_end = members->end();
- while (it != it_end)
- {
- const PartyMember *const member = *it;
- if ((member != nullptr) && member->getMap() == curMap
- && member->getOnline() && member != m)
- {
- if (userPalette != nullptr)
- {
- graphics->setColor(userPalette->getColor(
- UserColorId::PARTY));
- }
-
- const int offsetHeight = CAST_S32(
- mHeightProportion);
- const int offsetWidth = CAST_S32(
- mWidthProportion);
-
- graphics->fillRectangle(Rect(
- CAST_S32(member->getX()
- * mWidthProportion) + mMapOriginX - offsetWidth,
- CAST_S32(member->getY()
- * mHeightProportion) + mMapOriginY - offsetHeight,
- 2, 2));
- }
- ++ it;
- }
- }
- }
- }
-
- const int gw = graphics->getWidth();
- const int gh = graphics->getHeight();
- int x = (localPlayer->mPixelX - (gw / 2)
- + viewport->getCameraRelativeX())
- * mWidthProportion / 32 + mMapOriginX;
- int y = (localPlayer->mPixelY - (gh / 2)
- + viewport->getCameraRelativeY())
- * mHeightProportion / 32 + mMapOriginY;
-
- const int w = CAST_S32(static_cast<float>(
- gw) * mWidthProportion / 32);
- const int h = CAST_S32(static_cast<float>(
- gh) * mHeightProportion / 32);
-
- if (w <= a.width)
- {
- if (x < 0 && (w != 0))
- x = 0;
- if (x + w > a.width)
- x = a.width - w;
- }
- if (h <= a.height)
- {
- if (y < 0 && (h != 0))
- y = 0;
- if (y + h > a.height)
- y = a.height - h;
- }
-
- graphics->setColor(userPalette->getColor(UserColorId::PC));
- graphics->drawRectangle(Rect(x, y, w, h));
- graphics->popClipArea();
- BLOCK_END("Minimap::draw")
-}
-
-void Minimap::mousePressed(MouseEvent &event)
-{
- if (event.getButton() == MouseButton::RIGHT)
- return;
- Window::mousePressed(event);
-}
-
-void Minimap::mouseReleased(MouseEvent &event)
-{
- Window::mouseReleased(event);
-
- if ((localPlayer == nullptr) || (popupManager == nullptr))
- return;
-
- if (event.getButton() == MouseButton::LEFT)
- {
- int x = event.getX();
- int y = event.getY();
- screenToMap(x, y);
-
- localPlayer->navigateTo(x, y);
- }
- else if (event.getButton() == MouseButton::RIGHT)
- {
- int x = event.getX();
- int y = event.getY();
- screenToMap(x, y);
- popupMenu->showMapPopup(viewport->mMouseX,
- viewport->mMouseY,
- x, y,
- true);
- }
-}
-
-void Minimap::mouseMoved(MouseEvent &event)
-{
- Window::mouseMoved(event);
- const int x = event.getX();
- const int y = event.getY();
- const Rect &rect = mDimension;
- textPopup->show(x + rect.x, y + rect.y, mCaption);
-}
-
-void Minimap::mouseExited(MouseEvent &event)
-{
- Window::mouseExited(event);
- textPopup->hide();
-}
-
-void Minimap::screenToMap(int &x, int &y)
-{
- const Rect a = getChildrenArea();
- x = (x - a.x - mMapOriginX + mWidthProportion) / mWidthProportion;
- y = (y - a.y - mMapOriginY + mHeightProportion) / mHeightProportion;
-}
-
-void Minimap::optionChanged(const std::string &name)
-{
- if (name == "autoresizeminimaps")
- mAutoResize = config.getBoolValue("autoresizeminimaps");
-}
diff --git a/src/gui/windows/minimap.h b/src/gui/windows/minimap.h
deleted file mode 100644
index 5aad6e8be..000000000
--- a/src/gui/windows/minimap.h
+++ /dev/null
@@ -1,95 +0,0 @@
-/*
- * The ManaPlus Client
- * Copyright (C) 2004-2009 The Mana World Development Team
- * Copyright (C) 2009-2010 The Mana Developers
- * Copyright (C) 2011-2017 The ManaPlus Developers
- *
- * This file is part of The ManaPlus Client.
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-#ifndef GUI_WINDOWS_MINIMAP_H
-#define GUI_WINDOWS_MINIMAP_H
-
-#include "gui/widgets/window.h"
-
-class Image;
-class Map;
-
-/**
- * Minimap window. Shows a minimap image and the name of the current map.
- *
- * The name of the map is defined by the map property "name". The minimap image
- * is defined by the map property "minimap". The path to the image should be
- * given relative to the root of the client data.
- *
- * \ingroup Interface
- */
-class Minimap final : public Window, public ConfigListener
-{
- public:
- Minimap();
-
- A_DELETE_COPY(Minimap)
-
- ~Minimap();
-
- /**
- * Sets the map image that should be displayed.
- */
- void setMap(const Map *const map);
-
- /**
- * Toggles the displaying of the minimap.
- */
- void toggle();
-
- /**
- * Draws the minimap.
- */
- void draw(Graphics *const graphics) override final A_NONNULL(2);
-
- void safeDraw(Graphics *const graphics) override final A_NONNULL(2);
-
- void draw2(Graphics *const graphics) A_NONNULL(2);
-
- void mouseMoved(MouseEvent &event) override final;
-
- void mouseReleased(MouseEvent &event) override final;
-
- void mousePressed(MouseEvent &event) override final;
-
- void mouseExited(MouseEvent &event) override final;
-
- void screenToMap(int &x, int &y);
-
- void optionChanged(const std::string &name) override final;
-
- private:
- void deleteMapImage();
-
- float mWidthProportion;
- float mHeightProportion;
- Image *mMapImage;
- int mMapOriginX;
- int mMapOriginY;
- bool mCustomMapImage;
- bool mAutoResize;
- static bool mShow;
-};
-
-extern Minimap *minimap;
-
-#endif // GUI_WINDOWS_MINIMAP_H
diff --git a/src/gui/windows/ministatuswindow.cpp b/src/gui/windows/ministatuswindow.cpp
deleted file mode 100644
index e596f1fae..000000000
--- a/src/gui/windows/ministatuswindow.cpp
+++ /dev/null
@@ -1,594 +0,0 @@
-/*
- * The ManaPlus Client
- * Copyright (C) 2004-2009 The Mana World Development Team
- * Copyright (C) 2009-2010 The Mana Developers
- * Copyright (C) 2011-2017 The ManaPlus Developers
- *
- * This file is part of The ManaPlus Client.
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-#include "gui/windows/ministatuswindow.h"
-
-#include "configuration.h"
-
-#include "being/localplayer.h"
-#include "being/playerinfo.h"
-
-#include "gui/popupmanager.h"
-#include "gui/skin.h"
-
-#include "gui/popups/popupmenu.h"
-#include "gui/popups/statuspopup.h"
-#include "gui/popups/textpopup.h"
-
-#include "gui/windows/statuswindow.h"
-
-#include "gui/widgets/createwidget.h"
-#include "gui/widgets/progressbar.h"
-
-#include "net/playerhandler.h"
-
-#include "resources/inventory/inventory.h"
-
-#include "resources/sprite/animatedsprite.h"
-
-#include "utils/delete2.h"
-#include "utils/dtor.h"
-#include "utils/foreach.h"
-#include "utils/gettext.h"
-
-#include "debug.h"
-
-MiniStatusWindow *miniStatusWindow = nullptr;
-extern volatile int tick_time;
-
-typedef STD_VECTOR <ProgressBar*>::const_iterator ProgressBarVectorCIter;
-
-MiniStatusWindow::MiniStatusWindow() :
- Window("MiniStatus", Modal_false, nullptr, "ministatus.xml"),
- InventoryListener(),
- AttributeListener(),
- StatListener(),
- ArrowsListener(),
- UpdateStatusListener(),
- mBars(),
- mBarNames(),
- mIcons(),
- mHpBar(createBar(0, 100, 0, ThemeColorId::HP_BAR, ProgressColorId::PROG_HP,
- "hpprogressbar.xml", "hpprogressbar_fill.xml",
- // TRANSLATORS: status bar name
- "hp bar", _("health bar"))),
- mMpBar(createBar(0, 100, 0, playerHandler->canUseMagic()
- ? ThemeColorId::MP_BAR : ThemeColorId::NO_MP_BAR,
- playerHandler->canUseMagic()
- ? ProgressColorId::PROG_MP : ProgressColorId::PROG_NO_MP,
- playerHandler->canUseMagic()
- ? "mpprogressbar.xml" : "nompprogressbar.xml",
- playerHandler->canUseMagic()
- ? "mpprogressbar_fill.xml" : "nompprogressbar_fill.xml",
- // TRANSLATORS: status bar name
- "mp bar", _("mana bar"))),
- mXpBar(createBar(0, 100, 0,
- ThemeColorId::XP_BAR, ProgressColorId::PROG_EXP,
- "xpprogressbar.xml", "xpprogressbar_fill.xml",
- // TRANSLATORS: status bar name
- "xp bar", _("experience bar"))),
- mJobBar(nullptr),
- mWeightBar(createBar(0, 140, 0, ThemeColorId::WEIGHT_BAR,
- ProgressColorId::PROG_WEIGHT,
- "weightprogressbar.xml", "weightprogressbar_fill.xml",
- // TRANSLATORS: status bar name
- "weight bar", _("weight bar"))),
- mInvSlotsBar(createBar(0, 45, 0,
- ThemeColorId::SLOTS_BAR, ProgressColorId::PROG_INVY_SLOTS,
- "slotsprogressbar.xml", "slotsprogressbar_fill.xml",
- "inventory slots bar",
- // TRANSLATORS: status bar name
- _("inventory slots bar"))),
- mMoneyBar(createBar(0, 130, 0, ThemeColorId::MONEY_BAR,
- ProgressColorId::PROG_MONEY,
- "moneyprogressbar.xml", "moneyprogressbar_fill.xml",
- // TRANSLATORS: status bar name
- "money bar", _("money bar"))),
- mArrowsBar(createBar(0, 50, 0, ThemeColorId::ARROWS_BAR,
- ProgressColorId::PROG_ARROWS,
- "arrowsprogressbar.xml", "arrowsprogressbar_fill.xml",
- // TRANSLATORS: status bar name
- "arrows bar", _("arrows bar"))),
- mStatusBar(createBar(100, (config.getIntValue("fontSize") > 16
- ? 270 : 180), 0, ThemeColorId::STATUS_BAR,
- ProgressColorId::PROG_STATUS,
- "statusprogressbar.xml", "statusprogressbar_fill.xml",
- // TRANSLATORS: status bar name
- "status bar", _("status bar"))),
- mStatusPopup(CREATEWIDGETR0(StatusPopup)),
- mSpacing(mSkin != nullptr ? mSkin->getOption("spacing", 3) : 3),
- mIconPadding(mSkin != nullptr ? mSkin->getOption("iconPadding", 3) : 3),
- mIconSpacing(mSkin != nullptr ? mSkin->getOption("iconSpacing", 2) : 2),
- mMaxX(0)
-{
- StatusWindow::updateHPBar(mHpBar);
-
- if (statusWindow != nullptr)
- statusWindow->updateMPBar(mMpBar);
-
- const bool job = serverConfig.getValueBool("showJob", true);
-
- StatusWindow::updateXPBar(mXpBar);
-
- if (job)
- {
- mJobBar = createBar(0, 100, 0,
- ThemeColorId::JOB_BAR,
- ProgressColorId::PROG_JOB,
- "jobprogressbar.xml", "jobprogressbar_fill.xml",
- // TRANSLATORS: status bar name
- "job bar", _("job bar"));
- StatusWindow::updateJobBar(mJobBar);
- }
-
- loadBars();
- updateBars();
-
- setVisible(Visible_true);
- addMouseListener(this);
- Inventory *const inv = PlayerInfo::getInventory();
- if (inv != nullptr)
- inv->addInventoyListener(this);
-
- StatusWindow::updateMoneyBar(mMoneyBar);
- StatusWindow::updateArrowsBar(mArrowsBar);
- updateStatus();
-}
-
-MiniStatusWindow::~MiniStatusWindow()
-{
- delete2(mStatusPopup);
- delete_all(mIcons);
- mIcons.clear();
-
- Inventory *const inv = PlayerInfo::getInventory();
- if (inv != nullptr)
- inv->removeInventoyListener(this);
-
- FOR_EACH (ProgressBarVectorCIter, it, mBars)
- {
- ProgressBar *bar = *it;
- if (bar == nullptr)
- continue;
- if (bar->mVisible == Visible_false)
- delete bar;
- }
- mBars.clear();
-}
-
-ProgressBar *MiniStatusWindow::createBar(const float progress,
- const int width,
- const int height,
- const ThemeColorIdT textColor,
- const ProgressColorIdT backColor,
- const std::string &restrict skin,
- const std::string &restrict skinFill,
- const std::string &restrict name,
- const std::string &restrict
- description)
-{
- ProgressBar *const bar = new ProgressBar(this,
- progress, width, height, backColor, skin, skinFill);
- bar->setActionEventId(name);
- bar->setId(description);
- bar->setColor(getThemeColor(textColor), getThemeColor(textColor + 1));
- mBars.push_back(bar);
- mBarNames[name] = bar;
- return bar;
-}
-
-void MiniStatusWindow::updateBars()
-{
- int x = 0;
- const ProgressBar *lastBar = nullptr;
- FOR_EACH (ProgressBarVectorCIter, it, mBars)
- remove(*it);
-
- FOR_EACH (ProgressBarVectorCIter, it, mBars)
- {
- ProgressBar *const bar = *it;
- if (bar == nullptr)
- continue;
- if (bar->mVisible == Visible_true)
- {
- bar->setPosition(x, 0);
- add(bar);
- x += bar->getWidth() + mSpacing;
- lastBar = bar;
- }
- }
-
- if (lastBar != nullptr)
- {
- setContentSize(lastBar->getX() + lastBar->getWidth(),
- lastBar->getY() + lastBar->getHeight());
- }
- mMaxX = x;
-}
-
-void MiniStatusWindow::setIcon(const int index, AnimatedSprite *const sprite)
-{
- if (index >= CAST_S32(mIcons.size()))
- mIcons.resize(index + 1, nullptr);
-
- delete mIcons[index];
- mIcons[index] = sprite;
-}
-
-void MiniStatusWindow::eraseIcon(const int index)
-{
- if (index < CAST_S32(mIcons.size()))
- {
- delete mIcons[index];
- mIcons.erase(mIcons.begin() + index);
- }
-}
-
-void MiniStatusWindow::drawIcons(Graphics *const graphics)
-{
- // Draw icons
- int icon_x = mMaxX + mIconPadding;
- for (size_t i = 0, sz = mIcons.size(); i < sz; i ++)
- {
- const AnimatedSprite *const icon = mIcons[i];
- if (icon != nullptr)
- {
- icon->draw(graphics, icon_x, mIconPadding);
- icon_x += mIconSpacing + icon->getWidth();
- }
- }
-}
-
-void MiniStatusWindow::statChanged(const AttributesT id A_UNUSED,
- const int oldVal1 A_UNUSED,
- const int oldVal2 A_UNUSED)
-{
- if (statusWindow != nullptr)
- statusWindow->updateMPBar(mMpBar);
- StatusWindow::updateJobBar(mJobBar);
-}
-
-void MiniStatusWindow::attributeChanged(const AttributesT id,
- const int64_t oldVal A_UNUSED,
- const int64_t newVal A_UNUSED)
-{
- PRAGMA45(GCC diagnostic push)
- PRAGMA45(GCC diagnostic ignored "-Wswitch-enum")
- switch (id)
- {
- case Attributes::PLAYER_HP:
- case Attributes::PLAYER_MAX_HP:
- StatusWindow::updateHPBar(mHpBar);
- break;
- case Attributes::PLAYER_MP:
- case Attributes::PLAYER_MAX_MP:
- statusWindow->updateMPBar(mMpBar);
- break;
- case Attributes::PLAYER_EXP:
- case Attributes::PLAYER_EXP_NEEDED:
- StatusWindow::updateXPBar(mXpBar);
- break;
- case Attributes::TOTAL_WEIGHT:
- case Attributes::MAX_WEIGHT:
- StatusWindow::updateWeightBar(mWeightBar);
- break;
- case Attributes::MONEY:
- StatusWindow::updateMoneyBar(mMoneyBar);
- break;
- default:
- break;
- }
- PRAGMA45(GCC diagnostic pop)
-}
-
-void MiniStatusWindow::updateStatus()
-{
- if (statusWindow != nullptr)
- statusWindow->updateStatusBar(mStatusBar);
- if ((mStatusPopup != nullptr) && mStatusPopup->isPopupVisible())
- mStatusPopup->update();
-}
-
-void MiniStatusWindow::logic()
-{
- BLOCK_START("MiniStatusWindow::logic")
- Window::logic();
-
- for (size_t i = 0, sz = mIcons.size(); i < sz; i++)
- {
- AnimatedSprite *const icon = mIcons[i];
- if (icon != nullptr)
- icon->update(tick_time * 10);
- }
- BLOCK_END("MiniStatusWindow::logic")
-}
-
-void MiniStatusWindow::draw(Graphics *const graphics)
-{
- BLOCK_START("MiniStatusWindow::draw")
- drawChildren(graphics);
- BLOCK_END("MiniStatusWindow::draw")
-}
-
-void MiniStatusWindow::safeDraw(Graphics *const graphics)
-{
- BLOCK_START("MiniStatusWindow::draw")
- safeDrawChildren(graphics);
- BLOCK_END("MiniStatusWindow::draw")
-}
-
-void MiniStatusWindow::mouseMoved(MouseEvent &event)
-{
- Window::mouseMoved(event);
-
- const int x = event.getX();
- const int y = event.getY();
-
- const Rect &rect = mDimension;
- if (event.getSource() == mStatusBar)
- {
- mStatusPopup->view(x + rect.x, y + rect.y);
- textPopup->hide();
- }
- else if (event.getSource() == mXpBar)
- {
- std::string level;
- if ((localPlayer != nullptr) && localPlayer->isGM())
- {
- // TRANSLATORS: status bar label
- level = strprintf(_("Level: %d (GM %d)"),
- PlayerInfo::getAttribute(Attributes::PLAYER_BASE_LEVEL),
- localPlayer->getGroupId());
- }
- else
- {
- // TRANSLATORS: status bar label
- level = strprintf(_("Level: %d"),
- PlayerInfo::getAttribute(Attributes::PLAYER_BASE_LEVEL));
- }
-
- const int64_t exp = PlayerInfo::getAttribute64(Attributes::PLAYER_EXP);
- const int64_t expNeed = PlayerInfo::getAttribute64(
- Attributes::PLAYER_EXP_NEEDED);
- const std::string str = toString(CAST_U64(exp)) +
- "/" +
- toString(CAST_U64(expNeed));
- if (exp > expNeed)
- {
- textPopup->show(x + rect.x,
- y + rect.y,
- level,
- str);
- }
- else
- {
- const std::string str2 = toString(CAST_U64(expNeed - exp));
- textPopup->show(x + rect.x,
- y + rect.y,
- level,
- str,
- // TRANSLATORS: status bar label
- strprintf("%s: %s", _("Need"), str2.c_str()));
- }
- mStatusPopup->hide();
- }
- else if (event.getSource() == mHpBar)
- {
- textPopup->show(x + rect.x, y + rect.y, event.getSource()->getId(),
- strprintf("%d/%d", PlayerInfo::getAttribute(Attributes::PLAYER_HP),
- PlayerInfo::getAttribute(Attributes::PLAYER_MAX_HP)));
- mStatusPopup->hide();
- }
- else if (event.getSource() == mMpBar)
- {
- textPopup->show(x + rect.x, y + rect.y, event.getSource()->getId(),
- strprintf("%d/%d", PlayerInfo::getAttribute(Attributes::PLAYER_MP),
- PlayerInfo::getAttribute(Attributes::PLAYER_MAX_MP)));
- mStatusPopup->hide();
- }
- else if (event.getSource() == mJobBar)
- {
- const int64_t exp = PlayerInfo::getAttribute64(
- Attributes::PLAYER_JOB_EXP);
- const int64_t expNeed = PlayerInfo::getAttribute64(
- Attributes::PLAYER_JOB_EXP_NEEDED);
- const int32_t jobLevel = PlayerInfo::getAttribute(
- Attributes::PLAYER_JOB_LEVEL);
- const std::string expStr = toString(CAST_U64(exp));
- const std::string expNeedStr = toString(CAST_U64(expNeed));
- const std::string expLeftStr = toString(CAST_U64(expNeed - exp));
-
- // TRANSLATORS: job bar label
- const std::string level = strprintf(_("Job level: %d"),
- jobLevel);
-
- if (exp > expNeed)
- {
- textPopup->show(x + rect.x,
- y + rect.y,
- level,
- strprintf("%s/%s", expStr.c_str(), expNeedStr.c_str()));
- }
- else
- {
- textPopup->show(x + rect.x,
- y + rect.y,
- level,
- strprintf("%s/%s", expStr.c_str(), expNeedStr.c_str()),
- // TRANSLATORS: status bar label
- strprintf("%s: %s", _("Need"), expLeftStr.c_str()));
- }
- mStatusPopup->hide();
- }
- else if (event.getSource() == mWeightBar)
- {
- textPopup->show(x + rect.x, y + rect.y, event.getSource()->getId(),
- strprintf("%d/%d", PlayerInfo::getAttribute(
- Attributes::TOTAL_WEIGHT),
- PlayerInfo::getAttribute(Attributes::MAX_WEIGHT)));
- mStatusPopup->hide();
- }
- else if (event.getSource() == mInvSlotsBar)
- {
- const Inventory *const inv = PlayerInfo::getInventory();
- if (inv != nullptr)
- {
- const int usedSlots = inv->getNumberOfSlotsUsed();
- const int maxSlots = inv->getSize();
- textPopup->show(x + rect.x, y + rect.y,
- event.getSource()->getId(),
- strprintf("%d/%d", usedSlots, maxSlots));
- }
- mStatusPopup->hide();
- }
- else if (event.getSource() == mMoneyBar)
- {
- textPopup->show(x + rect.x, y + rect.y,
- event.getSource()->getId(),
- toString(PlayerInfo::getAttribute(Attributes::MONEY)));
- }
- else
- {
- textPopup->hide();
- mStatusPopup->hide();
- }
-}
-
-void MiniStatusWindow::mousePressed(MouseEvent &event)
-{
- if (event.getButton() == MouseButton::RIGHT)
- {
- const ProgressBar *const bar = dynamic_cast<ProgressBar*>(
- event.getSource());
- if (bar == nullptr)
- return;
- event.consume();
- if (popupManager != nullptr)
- {
- popupMenu->showPopup(getX() + event.getX(),
- getY() + event.getY(), bar);
- }
- }
-}
-
-void MiniStatusWindow::mouseExited(MouseEvent &event)
-{
- Window::mouseExited(event);
-
- textPopup->hide();
- mStatusPopup->hide();
-}
-
-void MiniStatusWindow::showBar(const std::string &name,
- const Visible visible)
-{
- ProgressBar *const bar = mBarNames[name];
- if (bar == nullptr)
- return;
- bar->setVisible(visible);
- updateBars();
- saveBars();
-}
-
-void MiniStatusWindow::loadBars()
-{
- if (config.getIntValue("ministatussaved") == 0)
- {
- if (mWeightBar != nullptr)
- mWeightBar->setVisible(Visible_false);
- if (mInvSlotsBar != nullptr)
- mInvSlotsBar->setVisible(Visible_false);
- if (mMoneyBar != nullptr)
- mMoneyBar->setVisible(Visible_false);
- if (mArrowsBar != nullptr)
- mArrowsBar->setVisible(Visible_false);
- if (mStatusBar != nullptr)
- mStatusBar->setVisible(Visible_false);
- if (mJobBar != nullptr)
- mJobBar->setVisible(Visible_true);
- return;
- }
-
- for (int f = 0; f < 10; f ++)
- {
- const std::string str = config.getValue(
- "ministatus" + toString(f), "");
- if (str.empty())
- continue;
- ProgressBar *const bar = mBarNames[str];
- if (bar == nullptr)
- continue;
- bar->setVisible(Visible_false);
- }
-}
-
-void MiniStatusWindow::saveBars() const
-{
- int i = 0;
- FOR_EACH (ProgressBarVectorCIter, it, mBars)
- {
- const ProgressBar *const bar = *it;
- if (bar->mVisible == Visible_false)
- {
- config.setValue("ministatus" + toString(i),
- bar->getActionEventId());
- i ++;
- }
- }
- for (int f = i; f < 10; f ++)
- config.deleteKey("ministatus" + toString(f));
-
- config.setValue("ministatussaved", true);
-}
-
-void MiniStatusWindow::slotsChanged(const Inventory *const inventory)
-{
- if (inventory == nullptr)
- return;
-
- if (inventory->getType() == InventoryType::Inventory)
- StatusWindow::updateInvSlotsBar(mInvSlotsBar);
-}
-
-Rect MiniStatusWindow::getChildrenArea()
-{
- const int padding = mPadding;
- const int padding2 = padding * 2;
- const Rect &rect = mDimension;
- return Rect(padding, padding,
- rect.width - padding2,
- rect.height - padding2);
-}
-
-void MiniStatusWindow::arrowsChanged()
-{
- StatusWindow::updateArrowsBar(mArrowsBar);
-}
-
-#ifdef USE_PROFILER
-void MiniStatusWindow::logicChildren()
-{
- BLOCK_START("MiniStatusWindow::logicChildren")
- BasicContainer::logicChildren();
- BLOCK_END("MiniStatusWindow::logicChildren")
-}
-#endif // USE_PROFILER
diff --git a/src/gui/windows/ministatuswindow.h b/src/gui/windows/ministatuswindow.h
deleted file mode 100644
index 9d6e19ac7..000000000
--- a/src/gui/windows/ministatuswindow.h
+++ /dev/null
@@ -1,151 +0,0 @@
-/*
- * The ManaPlus Client
- * Copyright (C) 2004-2009 The Mana World Development Team
- * Copyright (C) 2009-2010 The Mana Developers
- * Copyright (C) 2011-2017 The ManaPlus Developers
- *
- * This file is part of The ManaPlus Client.
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-#ifndef GUI_WINDOWS_MINISTATUSWINDOW_H
-#define GUI_WINDOWS_MINISTATUSWINDOW_H
-
-#include "listeners/arrowslistener.h"
-#include "listeners/attributelistener.h"
-#include "listeners/inventorylistener.h"
-#include "listeners/statlistener.h"
-#include "listeners/updatestatuslistener.h"
-
-#include "gui/widgets/window.h"
-
-class AnimatedSprite;
-class Graphics;
-class Inventory;
-class ProgressBar;
-class StatusPopup;
-
-/**
- * The player mini-status dialog.
- *
- * \ingroup Interface
- */
-class MiniStatusWindow final : public Window,
- public InventoryListener,
- public AttributeListener,
- public StatListener,
- public ArrowsListener,
- public UpdateStatusListener
-{
- public:
- MiniStatusWindow();
-
- A_DELETE_COPY(MiniStatusWindow)
-
- ~MiniStatusWindow();
-
- /**
- * Sets one of the icons.
- */
- void setIcon(const int index, AnimatedSprite *const sprite);
-
- void eraseIcon(const int index);
-
- void drawIcons(Graphics *const graphics) A_NONNULL(2);
-
- void updateStatus() override final;
-
- void logic() override final;
-
- void draw(Graphics *const graphics) override final A_NONNULL(2);
-
- void safeDraw(Graphics *const graphics) override final A_NONNULL(2);
-
- void mouseMoved(MouseEvent &event) override final;
-
- void mousePressed(MouseEvent &event) override final;
-
- void mouseExited(MouseEvent &event) override final;
-
- void showBar(const std::string &name, const Visible visible);
-
- void updateBars();
-
- void slotsChanged(const Inventory *const inventory) override final;
-
- STD_VECTOR <ProgressBar*> &getBars() A_WARN_UNUSED
- { return mBars; }
-
- Rect getChildrenArea() override final A_WARN_UNUSED;
-
- void attributeChanged(const AttributesT id,
- const int64_t oldVal,
- const int64_t newVal) override final;
-
- void statChanged(const AttributesT id,
- const int oldVal1,
- const int oldVal2) override final;
-
- void arrowsChanged() override final;
-
-#ifdef USE_PROFILER
- void logicChildren();
-#endif // USE_PROFILER
-
- private:
- bool isInBar(ProgressBar *bar, int x, int y) const;
-
- ProgressBar *createBar(const float progress,
- const int width,
- const int height,
- const ThemeColorIdT textColor,
- const ProgressColorIdT backColor,
- const std::string &restrict skin,
- const std::string &restrict skinFill,
- const std::string &restrict name,
- const std::string &restrict description)
- A_WARN_UNUSED;
-
- void loadBars();
-
- void saveBars() const;
-
- STD_VECTOR <ProgressBar*> mBars;
- std::map <std::string, ProgressBar*> mBarNames;
- STD_VECTOR<AnimatedSprite *> mIcons;
-
- /*
- * Mini Status Bars
- */
- ProgressBar *mHpBar;
- ProgressBar *mMpBar;
- ProgressBar *mXpBar;
- ProgressBar *mJobBar;
- ProgressBar *mWeightBar;
- ProgressBar *mInvSlotsBar;
- ProgressBar *mMoneyBar;
- ProgressBar *mArrowsBar;
- ProgressBar *mStatusBar;
- StatusPopup *mStatusPopup;
-
- int mSpacing;
- int mIconPadding;
- int mIconSpacing;
- int mMaxX;
-};
-
-extern MiniStatusWindow *miniStatusWindow;
-
-#endif // GUI_WINDOWS_MINISTATUSWINDOW_H
diff --git a/src/gui/windows/npcdialog.cpp b/src/gui/windows/npcdialog.cpp
deleted file mode 100644
index fb38dcc72..000000000
--- a/src/gui/windows/npcdialog.cpp
+++ /dev/null
@@ -1,1395 +0,0 @@
-/*
- * The ManaPlus Client
- * Copyright (C) 2004-2009 The Mana World Development Team
- * Copyright (C) 2009-2010 The Mana Developers
- * Copyright (C) 2011-2017 The ManaPlus Developers
- *
- * This file is part of The ManaPlus Client.
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-#include "gui/windows/npcdialog.h"
-
-#include "actormanager.h"
-#include "configuration.h"
-#include "settings.h"
-#include "soundmanager.h"
-
-#include "const/sound.h"
-
-#include "being/being.h"
-#include "being/playerinfo.h"
-
-#include "enums/gui/layouttype.h"
-
-#include "gui/gui.h"
-#include "gui/viewport.h"
-
-#include "gui/fonts/font.h"
-
-#include "gui/popups/popupmenu.h"
-
-#include "gui/windows/cutinwindow.h"
-#include "gui/windows/inventorywindow.h"
-
-#include "gui/widgets/browserbox.h"
-#include "gui/widgets/button.h"
-#include "gui/widgets/createwidget.h"
-#include "gui/widgets/icon.h"
-#include "gui/widgets/inttextfield.h"
-#include "gui/widgets/itemcontainer.h"
-#include "gui/widgets/itemlinkhandler.h"
-#include "gui/widgets/layout.h"
-#include "gui/widgets/extendedlistbox.h"
-#include "gui/widgets/playerbox.h"
-#include "gui/widgets/scrollarea.h"
-
-#include "resources/npcdialoginfo.h"
-
-#include "resources/db/avatardb.h"
-#include "resources/db/npcdb.h"
-#include "resources/db/npcdialogdb.h"
-
-#include "resources/inventory/complexinventory.h"
-
-#include "resources/item/complexitem.h"
-
-#include "resources/loaders/imageloader.h"
-
-#include "net/npchandler.h"
-#include "net/packetlimiter.h"
-
-#include "utils/copynpaste.h"
-#include "utils/delete2.h"
-#include "utils/foreach.h"
-#include "utils/gettext.h"
-
-#include <sstream>
-
-#include "debug.h"
-
-// TRANSLATORS: npc dialog button
-#define CAPTION_WAITING _("Stop waiting")
-// TRANSLATORS: npc dialog button
-#define CAPTION_NEXT _("Next")
-// TRANSLATORS: npc dialog button
-#define CAPTION_CLOSE _("Close")
-// TRANSLATORS: npc dialog button
-#define CAPTION_SUBMIT _("Submit")
-
-NpcDialog::DialogList NpcDialog::instances;
-NpcDialogs NpcDialog::mNpcDialogs;
-
-typedef STD_VECTOR<Image *>::iterator ImageVectorIter;
-
-NpcDialog::NpcDialog(const BeingId npcId) :
- // TRANSLATORS: npc dialog name
- Window(_("NPC"), Modal_false, nullptr, "npc.xml"),
- ActionListener(),
- mNpcId(npcId),
- mDefaultInt(0),
- mDefaultString(),
- mTextBox(new BrowserBox(this, Opaque_true,
- "browserbox.xml")),
- mScrollArea(new ScrollArea(this, mTextBox,
- fromBool(getOptionBool("showtextbackground"), Opaque),
- "npc_textbackground.xml")),
- mText(),
- mNewText(),
- mItems(),
- mImages(),
- mItemList(CREATEWIDGETR(ExtendedListBox,
- this, this, "extendedlistbox.xml")),
- mListScrollArea(new ScrollArea(this, mItemList,
- fromBool(getOptionBool("showlistbackground"), Opaque),
- "npc_listbackground.xml")),
- mSkinContainer(new Container(this)),
- mSkinScrollArea(new ScrollArea(this, mSkinContainer,
- fromBool(getOptionBool("showlistbackground"), Opaque),
- "npc_listbackground.xml")),
- mItemLinkHandler(new ItemLinkHandler),
- mTextField(new TextField(this, "")),
- mIntField(new IntTextField(this)),
- // TRANSLATORS: npc dialog button
- mPlusButton(new Button(this, _("+"), "inc", this)),
- // TRANSLATORS: npc dialog button
- mMinusButton(new Button(this, _("-"), "dec", this)),
- // TRANSLATORS: npc dialog button
- mClearButton(new Button(this, _("Clear"), "clear", this)),
- mButton(new Button(this, "", "ok", this)),
- // TRANSLATORS: npc dialog button
- mButton2(new Button(this, _("Close"), "close", this)),
- // TRANSLATORS: npc dialog button
- mButton3(new Button(this, _("Add"), "add", this)),
- // TRANSLATORS: npc dialog button
- mResetButton(new Button(this, _("Reset"), "reset", this)),
- mInventory(new Inventory(InventoryType::Npc, 1)),
- mComplexInventory(new ComplexInventory(InventoryType::Craft, 1)),
- mItemContainer(new ItemContainer(this, mInventory,
- 10000, ShowEmptyRows_true)),
- mItemScrollArea(new ScrollArea(this, mItemContainer,
- fromBool(getOptionBool("showitemsbackground"), Opaque),
- "npc_listbackground.xml")),
- mInputState(NpcInputState::NONE),
- mActionState(NpcActionState::WAIT),
- mSkinControls(),
- mSkinName(),
- mPlayerBox(new PlayerBox(nullptr)),
- mAvatarBeing(nullptr),
- mDialogInfo(nullptr),
- mLastNextTime(0),
- mCameraMode(-1),
- mCameraX(0),
- mCameraY(0),
- mShowAvatar(false),
- mLogInteraction(config.getBoolValue("logNpcInGui"))
-{
- // Basic Window Setup
- setWindowName("NpcText");
- setResizable(true);
- setFocusable(true);
- setStickyButtonLock(true);
-
- setMinWidth(200);
- setMinHeight(150);
-
- setDefaultSize(300, 578, ImagePosition::LOWER_LEFT);
-
- mPlayerBox->setWidth(70);
- mPlayerBox->setHeight(100);
-
- // Setup output text box
- mTextBox->setOpaque(Opaque_false);
- mTextBox->setMaxRow(config.getIntValue("ChatLogLength"));
- mTextBox->setLinkHandler(mItemLinkHandler);
- mTextBox->setProcessVars(true);
- mTextBox->setFont(gui->getNpcFont());
- mTextBox->setEnableKeys(true);
- mTextBox->setEnableTabs(true);
- mTextBox->setEnableImages(true);
-
- mScrollArea->setHorizontalScrollPolicy(ScrollArea::SHOW_NEVER);
- mScrollArea->setVerticalScrollPolicy(ScrollArea::SHOW_ALWAYS);
-
- // Setup listbox
- mItemList->setWrappingEnabled(true);
- mItemList->setActionEventId("ok");
- mItemList->addActionListener(this);
- mItemList->setDistributeMousePressed(false);
- mItemList->setFont(gui->getNpcFont());
- if (gui->getNpcFont()->getHeight() < 20)
- mItemList->setRowHeight(20);
- else
- mItemList->setRowHeight(gui->getNpcFont()->getHeight());
-
- setContentSize(260, 175);
- mListScrollArea->setHorizontalScrollPolicy(ScrollArea::SHOW_NEVER);
- mItemScrollArea->setHorizontalScrollPolicy(ScrollArea::SHOW_NEVER);
- mSkinScrollArea->setScrollPolicy(ScrollArea::SHOW_NEVER,
- ScrollArea::SHOW_NEVER);
- mItemList->setVisible(Visible_true);
- mTextField->setVisible(Visible_true);
- mIntField->setVisible(Visible_true);
-
- const Font *const fnt = mButton->getFont();
- int width = std::max(fnt->getWidth(CAPTION_WAITING),
- fnt->getWidth(CAPTION_NEXT));
- width = std::max(width, fnt->getWidth(CAPTION_CLOSE));
- width = std::max(width, fnt->getWidth(CAPTION_SUBMIT));
- mButton->setWidth(8 + width);
-
- // Place widgets
- buildLayout();
-
- center();
- loadWindowState();
-
- instances.push_back(this);
-}
-
-void NpcDialog::postInit()
-{
- Window::postInit();
- setVisible(Visible_true);
- requestFocus();
- enableVisibleSound(true);
- soundManager.playGuiSound(SOUND_SHOW_WINDOW);
-
- if (actorManager != nullptr)
- {
- const Being *const being = actorManager->findBeing(mNpcId);
- if (being != nullptr)
- {
- showAvatar(NPCDB::getAvatarFor(fromInt(
- being->getSubType(), BeingTypeId)));
- setCaption(being->getName());
- }
- }
-
- config.addListener("logNpcInGui", this);
-}
-
-NpcDialog::~NpcDialog()
-{
- config.removeListeners(this);
- CHECKLISTENERS
- clearLayout();
-
- if (mPlayerBox != nullptr)
- {
- delete mPlayerBox->getBeing();
- delete mPlayerBox;
- }
-
- deleteSkinControls();
-
- delete2(mTextBox);
- delete2(mClearButton);
- delete2(mButton);
- delete2(mButton2);
- delete2(mButton3);
- delete2(mScrollArea);
- delete2(mItemList);
- delete2(mTextField);
- delete2(mIntField);
- delete2(mResetButton);
- delete2(mPlusButton);
- delete2(mMinusButton);
- delete2(mItemLinkHandler);
- delete2(mItemContainer);
- delete2(mInventory);
- delete2(mComplexInventory);
- delete2(mItemScrollArea);
- delete2(mListScrollArea);
- delete2(mSkinScrollArea);
-
- FOR_EACH (ImageVectorIter, it, mImages)
- {
- if (*it != nullptr)
- (*it)->decRef();
- }
-
- mImages.clear();
-
- instances.remove(this);
-}
-
-void NpcDialog::addText(const std::string &text, const bool save)
-{
- if (save || mLogInteraction)
- {
- if (mText.size() > 5000)
- mText.clear();
-
- mNewText.append(text);
- mTextBox->addRow(text);
- }
- mScrollArea->setVerticalScrollAmount(mScrollArea->getVerticalMaxScroll());
- mActionState = NpcActionState::WAIT;
- buildLayout();
-}
-
-void NpcDialog::showNextButton()
-{
- mActionState = NpcActionState::NEXT;
- buildLayout();
-}
-
-void NpcDialog::showCloseButton()
-{
- mActionState = NpcActionState::CLOSE;
- buildLayout();
-}
-
-void NpcDialog::action(const ActionEvent &event)
-{
- const std::string &eventId = event.getId();
- if (eventId == "ok")
- {
- if (mActionState == NpcActionState::NEXT)
- {
- if (!PacketLimiter::limitPackets(PacketType::PACKET_NPC_NEXT))
- return;
-
- nextDialog();
- addText(std::string(), false);
- }
- else if (mActionState == NpcActionState::CLOSE
- || mActionState == NpcActionState::WAIT)
- {
- if (cutInWindow != nullptr)
- cutInWindow->hide();
- closeDialog();
- }
- else if (mActionState == NpcActionState::INPUT)
- {
- std::string printText; // Text that will get printed
- // in the textbox
- switch (mInputState)
- {
- case NpcInputState::LIST:
- {
- if (mDialogInfo != nullptr)
- return;
- if (gui != nullptr)
- gui->resetClickCount();
- const int selectedIndex = mItemList->getSelected();
-
- if (selectedIndex >= CAST_S32(mItems.size())
- || selectedIndex < 0
- || !PacketLimiter::limitPackets(
- PacketType::PACKET_NPC_INPUT))
- {
- return;
- }
- unsigned char choice = CAST_U8(
- selectedIndex + 1);
- printText = mItems[selectedIndex];
-
- npcHandler->listInput(mNpcId, choice);
- break;
- }
- case NpcInputState::STRING:
- {
- if (!PacketLimiter::limitPackets(
- PacketType::PACKET_NPC_INPUT))
- {
- return;
- }
- printText = mTextField->getText();
- npcHandler->stringInput(mNpcId, printText);
- break;
- }
- case NpcInputState::INTEGER:
- {
- if (!PacketLimiter::limitPackets(
- PacketType::PACKET_NPC_INPUT))
- {
- return;
- }
- printText = strprintf("%d", mIntField->getValue());
- npcHandler->integerInput(
- mNpcId, mIntField->getValue());
- break;
- }
- case NpcInputState::ITEM:
- {
- restoreVirtuals();
- if (!PacketLimiter::limitPackets(
- PacketType::PACKET_NPC_INPUT))
- {
- return;
- }
-
- std::string str;
- const int sz = mInventory->getSize();
- if (sz == 0)
- {
- str = "0,0";
- }
- else
- {
- const Item *item = mInventory->getItem(0);
- if (item != nullptr)
- {
- str = strprintf("%d,%d", item->getId(),
- toInt(item->getColor(), int));
- }
- else
- {
- str = "0,0";
- }
- for (int f = 1; f < sz; f ++)
- {
- str.append(";");
- item = mInventory->getItem(f);
- if (item != nullptr)
- {
- str.append(strprintf("%d,%d", item->getId(),
- toInt(item->getColor(), int)));
- }
- else
- {
- str.append("0,0");
- }
- }
- }
-
- // need send selected item
- npcHandler->stringInput(mNpcId, str);
- mInventory->clear();
- break;
- }
- case NpcInputState::ITEM_INDEX:
- {
- restoreVirtuals();
- if (!PacketLimiter::limitPackets(
- PacketType::PACKET_NPC_INPUT))
- {
- return;
- }
-
- std::string str;
- const int sz = mInventory->getSize();
- if (sz == 0)
- {
- str = "-1";
- }
- else
- {
- const Item *item = mInventory->getItem(0);
- if (item != nullptr)
- {
- str = strprintf("%d", item->getTag());
- }
- else
- {
- str = "-1";
- }
- for (int f = 1; f < sz; f ++)
- {
- str.append(";");
- item = mInventory->getItem(f);
- if (item != nullptr)
- str.append(strprintf("%d", item->getTag()));
- else
- str.append("-1");
- }
- }
-
- // need send selected item
- npcHandler->stringInput(mNpcId, str);
- mInventory->clear();
- break;
- }
- case NpcInputState::ITEM_CRAFT:
- {
- restoreVirtuals();
- if (!PacketLimiter::limitPackets(
- PacketType::PACKET_NPC_INPUT))
- {
- return;
- }
-
- std::string str;
- const int sz = mComplexInventory->getSize();
- if (sz == 0)
- {
- str.clear();
- }
- else
- {
- const ComplexItem *item = dynamic_cast<ComplexItem*>(
- mComplexInventory->getItem(0));
- str = complexItemToStr(item);
- for (int f = 1; f < sz; f ++)
- {
- str.append("|");
- item = dynamic_cast<ComplexItem*>(
- mComplexInventory->getItem(f));
- str.append(complexItemToStr(item));
- }
- }
-
- // need send selected item
- npcHandler->stringInput(mNpcId, str);
- mInventory->clear();
- break;
- }
-
- case NpcInputState::NONE:
- default:
- break;
- }
- if (mInputState != NpcInputState::ITEM &&
- mInputState != NpcInputState::ITEM_INDEX &&
- mInputState != NpcInputState::ITEM_CRAFT)
- {
- // addText will auto remove the input layout
- addText(strprintf("> \"%s\"", printText.c_str()), false);
- }
- mNewText.clear();
- }
-
- if (!mLogInteraction)
- mTextBox->clearRows();
- }
- else if (eventId == "reset")
- {
- switch (mInputState)
- {
- case NpcInputState::STRING:
- mTextField->setText(mDefaultString);
- break;
- case NpcInputState::INTEGER:
- mIntField->setValue(mDefaultInt);
- break;
- case NpcInputState::ITEM:
- case NpcInputState::ITEM_INDEX:
- mInventory->clear();
- break;
- case NpcInputState::ITEM_CRAFT:
- mComplexInventory->clear();
- break;
- case NpcInputState::NONE:
- case NpcInputState::LIST:
- default:
- break;
- }
- }
- else if (eventId == "inc")
- {
- mIntField->setValue(mIntField->getValue() + 1);
- }
- else if (eventId == "dec")
- {
- mIntField->setValue(mIntField->getValue() - 1);
- }
- else if (eventId == "clear")
- {
- switch (mInputState)
- {
- case NpcInputState::ITEM:
- case NpcInputState::ITEM_INDEX:
- mInventory->clear();
- break;
- case NpcInputState::ITEM_CRAFT:
- mComplexInventory->clear();
- break;
- case NpcInputState::STRING:
- case NpcInputState::INTEGER:
- case NpcInputState::LIST:
- case NpcInputState::NONE:
- default:
- clearRows();
- break;
- }
- }
- else if (eventId == "close")
- {
- restoreVirtuals();
- if (mActionState == NpcActionState::INPUT)
- {
- switch (mInputState)
- {
- case NpcInputState::ITEM:
- npcHandler->stringInput(mNpcId, "0,0");
- break;
- case NpcInputState::ITEM_INDEX:
- npcHandler->stringInput(mNpcId, "-1");
- break;
- case NpcInputState::ITEM_CRAFT:
- npcHandler->stringInput(mNpcId, "");
- break;
- case NpcInputState::STRING:
- case NpcInputState::INTEGER:
- case NpcInputState::NONE:
- case NpcInputState::LIST:
- default:
- npcHandler->listInput(mNpcId, 255);
- break;
- }
- if (cutInWindow != nullptr)
- cutInWindow->hide();
- closeDialog();
- }
- }
- else if (eventId == "add")
- {
- if (inventoryWindow != nullptr)
- {
- Item *const item = inventoryWindow->getSelectedItem();
- Inventory *const inventory = PlayerInfo::getInventory();
- if (inventory != nullptr)
- {
- if (mInputState == NpcInputState::ITEM_CRAFT)
- {
- if (mComplexInventory->addVirtualItem(item, -1, 1))
- inventory->virtualRemove(item, 1);
- }
- else
- {
- if (mInventory->addVirtualItem(item, -1, 1))
- inventory->virtualRemove(item, 1);
- }
- }
- }
- }
- else if (eventId.find("skin_") == 0)
- {
- const std::string cmd = eventId.substr(5);
- std::string printText;
- int cnt = 0;
- FOR_EACH (StringVectCIter, it, mItems)
- {
- if (cmd == *it)
- {
- npcHandler->listInput(mNpcId, CAST_U8(cnt + 1));
- printText = mItems[cnt];
-
- if (mInputState != NpcInputState::ITEM &&
- mInputState != NpcInputState::ITEM_INDEX &&
- mInputState != NpcInputState::ITEM_CRAFT)
- {
- // addText will auto remove the input layout
- addText(strprintf("> \"%s\"", printText.c_str()), false);
- }
- mNewText.clear();
- break;
- }
- cnt ++;
- }
- }
-}
-
-void NpcDialog::nextDialog()
-{
- npcHandler->nextDialog(mNpcId);
-}
-
-void NpcDialog::closeDialog()
-{
- restoreCamera();
- npcHandler->closeDialog(mNpcId);
-}
-
-int NpcDialog::getNumberOfElements()
-{
- return CAST_S32(mItems.size());
-}
-
-std::string NpcDialog::getElementAt(int i)
-{
- return mItems[i];
-}
-
-const Image *NpcDialog::getImageAt(int i)
-{
- return mImages[i];
-}
-
-void NpcDialog::choiceRequest()
-{
- mItems.clear();
- FOR_EACH (ImageVectorIter, it, mImages)
- {
- if (*it != nullptr)
- (*it)->decRef();
- }
- mImages.clear();
- mActionState = NpcActionState::INPUT;
- mInputState = NpcInputState::LIST;
- buildLayout();
-}
-
-void NpcDialog::addChoice(const std::string &choice)
-{
- mItems.push_back(choice);
- mImages.push_back(nullptr);
-}
-
-void NpcDialog::parseListItems(const std::string &itemString)
-{
- std::istringstream iss(itemString);
- std::string tmp;
- const std::string path = paths.getStringValue("guiIcons");
- while (getline(iss, tmp, ':'))
- {
- if (tmp.empty())
- continue;
- const size_t pos = tmp.find('|');
- if (pos == std::string::npos)
- {
- mItems.push_back(tmp);
- mImages.push_back(nullptr);
- }
- else
- {
- mItems.push_back(tmp.substr(pos + 1));
- Image *const img = Loader::getImage(pathJoin(path,
- std::string(tmp.substr(0, pos)).append(".png")));
- mImages.push_back(img);
- }
- }
-
- if (!mItems.empty())
- {
- mItemList->setSelected(0);
- mItemList->requestFocus();
- }
- else
- {
- mItemList->setSelected(-1);
- }
-}
-
-void NpcDialog::refocus()
-{
- if (!mItems.empty())
- mItemList->refocus();
-}
-
-void NpcDialog::textRequest(const std::string &defaultText)
-{
- mActionState = NpcActionState::INPUT;
- mInputState = NpcInputState::STRING;
- mDefaultString = defaultText;
- mTextField->setText(defaultText);
-
- buildLayout();
-}
-
-bool NpcDialog::isTextInputFocused() const
-{
- return mTextField->isFocused();
-}
-
-bool NpcDialog::isInputFocused() const
-{
- return mTextField->isFocused() || mIntField->isFocused()
- || mItemList->isFocused();
-}
-
-bool NpcDialog::isAnyInputFocused()
-{
- FOR_EACH (DialogList::const_iterator, it, instances)
- {
- if (((*it) != nullptr) && (*it)->isInputFocused())
- return true;
- }
-
- return false;
-}
-
-void NpcDialog::integerRequest(const int defaultValue, const int min,
- const int max)
-{
- mActionState = NpcActionState::INPUT;
- mInputState = NpcInputState::INTEGER;
- mDefaultInt = defaultValue;
- mIntField->setRange(min, max);
- mIntField->setValue(defaultValue);
- buildLayout();
-}
-
-void NpcDialog::itemRequest(const int size)
-{
- mActionState = NpcActionState::INPUT;
- mInputState = NpcInputState::ITEM;
- mInventory->resize(size);
- buildLayout();
-}
-
-void NpcDialog::itemIndexRequest(const int size)
-{
- mActionState = NpcActionState::INPUT;
- mInputState = NpcInputState::ITEM_INDEX;
- mInventory->resize(size);
- buildLayout();
-}
-
-void NpcDialog::itemCraftRequest(const int size)
-{
- mActionState = NpcActionState::INPUT;
- mInputState = NpcInputState::ITEM_CRAFT;
- mComplexInventory->resize(size);
- buildLayout();
-}
-
-void NpcDialog::move(const int amount)
-{
- if (mActionState != NpcActionState::INPUT)
- return;
-
- switch (mInputState)
- {
- case NpcInputState::INTEGER:
- mIntField->setValue(mIntField->getValue() + amount);
- break;
- case NpcInputState::LIST:
- mItemList->setSelected(mItemList->getSelected() - amount);
- break;
- case NpcInputState::NONE:
- case NpcInputState::STRING:
- case NpcInputState::ITEM:
- case NpcInputState::ITEM_INDEX:
- case NpcInputState::ITEM_CRAFT:
- default:
- break;
- }
-}
-
-void NpcDialog::setVisible(Visible visible)
-{
- Window::setVisible(visible);
-
- if (visible == Visible_false)
- scheduleDelete();
-}
-
-void NpcDialog::optionChanged(const std::string &name)
-{
- if (name == "logNpcInGui")
- mLogInteraction = config.getBoolValue("logNpcInGui");
-}
-
-NpcDialog *NpcDialog::getActive()
-{
- if (instances.size() == 1)
- return instances.front();
-
- FOR_EACH (DialogList::const_iterator, it, instances)
- {
- if (((*it) != nullptr) && (*it)->isFocused())
- return (*it);
- }
-
- return nullptr;
-}
-
-void NpcDialog::closeAll()
-{
- FOR_EACH (DialogList::const_iterator, it, instances)
- {
- if (*it != nullptr)
- (*it)->close();
- }
-}
-
-void NpcDialog::placeNormalControls()
-{
- if (mShowAvatar)
- {
- place(0, 0, mPlayerBox);
- place(1, 0, mScrollArea, 5, 3);
- place(4, 3, mClearButton);
- place(5, 3, mButton);
- }
- else
- {
- place(0, 0, mScrollArea, 5, 3);
- place(3, 3, mClearButton);
- place(4, 3, mButton);
- }
-}
-
-void NpcDialog::placeMenuControls()
-{
- if (mShowAvatar)
- {
- place(0, 0, mPlayerBox);
- place(1, 0, mScrollArea, 6, 3);
- place(0, 3, mListScrollArea, 7, 3);
- place(1, 6, mButton2, 2);
- place(3, 6, mClearButton, 2);
- place(5, 6, mButton, 2);
- }
- else
- {
- place(0, 0, mScrollArea, 6, 3);
- place(0, 3, mListScrollArea, 6, 3);
- place(0, 6, mButton2, 2);
- place(2, 6, mClearButton, 2);
- place(4, 6, mButton, 2);
- }
-}
-
-void NpcDialog::placeSkinControls()
-{
- createSkinControls();
- if ((mDialogInfo != nullptr) && mDialogInfo->hideText)
- {
- if (mShowAvatar)
- {
- place(0, 0, mPlayerBox);
- place(1, 0, mSkinScrollArea, 7, 3);
- place(1, 3, mButton2, 2);
- }
- else
- {
- place(0, 0, mSkinScrollArea, 6, 3);
- place(0, 3, mButton2, 2);
- }
- }
- else
- {
- if (mShowAvatar)
- {
- place(0, 0, mPlayerBox);
- place(1, 0, mScrollArea, 6, 3);
- place(0, 3, mSkinScrollArea, 7, 3);
- place(1, 6, mButton2, 2);
- }
- else
- {
- place(0, 0, mScrollArea, 6, 3);
- place(0, 3, mSkinScrollArea, 6, 3);
- place(0, 6, mButton2, 2);
- }
- }
-}
-
-void NpcDialog::placeTextInputControls()
-{
- if (mShowAvatar)
- {
- place(0, 0, mPlayerBox);
- place(1, 0, mScrollArea, 6, 3);
- place(1, 3, mTextField, 6);
- place(1, 4, mResetButton, 2);
- place(3, 4, mClearButton, 2);
- place(5, 4, mButton, 2);
- }
- else
- {
- place(0, 0, mScrollArea, 6, 3);
- place(0, 3, mTextField, 6);
- place(0, 4, mResetButton, 2);
- place(2, 4, mClearButton, 2);
- place(4, 4, mButton, 2);
- }
-}
-
-void NpcDialog::placeIntInputControls()
-{
- if (mShowAvatar)
- {
- place(0, 0, mPlayerBox);
- place(1, 0, mScrollArea, 6, 3);
- place(1, 3, mMinusButton, 1);
- place(2, 3, mIntField, 4);
- place(6, 3, mPlusButton, 1);
- place(1, 4, mResetButton, 2);
- place(3, 4, mClearButton, 2);
- place(5, 4, mButton, 2);
- }
- else
- {
- place(0, 0, mScrollArea, 6, 3);
- place(0, 3, mMinusButton, 1);
- place(1, 3, mIntField, 4);
- place(5, 3, mPlusButton, 1);
- place(0, 4, mResetButton, 2);
- place(2, 4, mClearButton, 2);
- place(4, 4, mButton, 2);
- }
-}
-
-void NpcDialog::placeItemInputControls()
-{
- if (mDialogInfo != nullptr)
- {
- mItemContainer->setCellBackgroundImage(mDialogInfo->inventory.cell);
- mItemContainer->setMaxColumns(mDialogInfo->inventory.columns);
- }
- else
- {
- mItemContainer->setCellBackgroundImage("inventory_cell.xml");
- mItemContainer->setMaxColumns(10000);
- }
-
- if (mInputState == NpcInputState::ITEM_CRAFT)
- mItemContainer->setInventory(mComplexInventory);
- else
- mItemContainer->setInventory(mInventory);
-
- if ((mDialogInfo != nullptr) && mDialogInfo->hideText)
- {
- if (mShowAvatar)
- {
- place(0, 0, mPlayerBox);
- place(1, 0, mItemScrollArea, 7, 3);
- place(1, 3, mButton3, 2);
- place(3, 3, mClearButton, 2);
- place(5, 3, mButton, 2);
- }
- else
- {
- place(0, 0, mItemScrollArea, 6, 3);
- place(0, 3, mButton3, 2);
- place(2, 3, mClearButton, 2);
- place(4, 3, mButton, 2);
- }
- }
- else
- {
- if (mShowAvatar)
- {
- place(0, 0, mPlayerBox);
- place(1, 0, mScrollArea, 6, 3);
- place(0, 3, mItemScrollArea, 7, 3);
- place(1, 6, mButton3, 2);
- place(3, 6, mClearButton, 2);
- place(5, 6, mButton, 2);
- }
- else
- {
- place(0, 0, mScrollArea, 6, 3);
- place(0, 3, mItemScrollArea, 6, 3);
- place(0, 6, mButton3, 2);
- place(2, 6, mClearButton, 2);
- place(4, 6, mButton, 2);
- }
- }
-}
-
-void NpcDialog::buildLayout()
-{
- clearLayout();
-
- if (mActionState != NpcActionState::INPUT)
- {
- if (mActionState == NpcActionState::WAIT)
- mButton->setCaption(CAPTION_WAITING);
- else if (mActionState == NpcActionState::NEXT)
- mButton->setCaption(CAPTION_NEXT);
- else if (mActionState == NpcActionState::CLOSE)
- mButton->setCaption(CAPTION_CLOSE);
- placeNormalControls();
- }
- else if (mInputState != NpcInputState::NONE)
- {
- mButton->setCaption(CAPTION_SUBMIT);
- switch (mInputState)
- {
- case NpcInputState::LIST:
- if (mDialogInfo == nullptr)
- placeMenuControls();
- else
- placeSkinControls();
- mItemList->setSelected(-1);
- break;
-
- case NpcInputState::STRING:
- placeTextInputControls();
- break;
-
- case NpcInputState::INTEGER:
- placeIntInputControls();
- break;
-
- case NpcInputState::ITEM:
- case NpcInputState::ITEM_INDEX:
- case NpcInputState::ITEM_CRAFT:
- placeItemInputControls();
- break;
-
- case NpcInputState::NONE:
- default:
- break;
- }
- }
-
- Layout &layout = getLayout();
- layout.setRowHeight(1, LayoutType::SET);
- redraw();
- mScrollArea->setVerticalScrollAmount(mScrollArea->getVerticalMaxScroll());
-}
-
-void NpcDialog::saveCamera()
-{
- if ((viewport == nullptr) || mCameraMode >= 0)
- return;
-
- mCameraMode = CAST_S32(settings.cameraMode);
- mCameraX = viewport->getCameraRelativeX();
- mCameraY = viewport->getCameraRelativeY();
-}
-
-void NpcDialog::restoreCamera()
-{
- if ((viewport == nullptr) || mCameraMode == -1)
- return;
-
- if (CAST_S32(settings.cameraMode) != mCameraMode)
- viewport->toggleCameraMode();
- if (mCameraMode != 0)
- {
- viewport->setCameraRelativeX(mCameraX);
- viewport->setCameraRelativeY(mCameraY);
- }
- mCameraMode = -1;
-}
-
-void NpcDialog::showAvatar(const BeingTypeId avatarId)
-{
- const bool needShow = (avatarId != BeingTypeId_zero);
- if (needShow)
- {
- delete mAvatarBeing;
- mAvatarBeing = Being::createBeing(BeingId_zero,
- ActorType::Avatar,
- avatarId,
- nullptr);
- mPlayerBox->setPlayer(mAvatarBeing);
- if (!mAvatarBeing->mSprites.empty())
- {
- mAvatarBeing->logic();
- const BeingInfo *const info = AvatarDB::get(avatarId);
- const int pad2 = 2 * mPadding;
- int width = 0;
- if (info != nullptr)
- {
- width = info->getWidth();
- mPlayerBox->setWidth(width + pad2);
- mPlayerBox->setHeight(info->getHeight() + pad2);
- }
- const Sprite *const sprite = mAvatarBeing->mSprites[0];
- if ((sprite != nullptr) && (width == 0))
- {
- mPlayerBox->setWidth(sprite->getWidth() + pad2);
- mPlayerBox->setHeight(sprite->getHeight() + pad2);
- }
- }
- }
- else
- {
- delete2(mAvatarBeing)
- mPlayerBox->setPlayer(nullptr);
- }
- if (needShow != mShowAvatar)
- {
- mShowAvatar = needShow;
- buildLayout();
- }
- else
- {
- mShowAvatar = needShow;
- }
-}
-
-void NpcDialog::setAvatarDirection(const uint8_t direction)
-{
- Being *const being = mPlayerBox->getBeing();
- if (being != nullptr)
- being->setDirection(direction);
-}
-
-void NpcDialog::setAvatarAction(const int actionId)
-{
- Being *const being = mPlayerBox->getBeing();
- if (being != nullptr)
- being->setAction(static_cast<BeingActionT>(actionId), 0);
-}
-
-void NpcDialog::logic()
-{
- BLOCK_START("NpcDialog::logic")
- Window::logic();
- if (mShowAvatar && (mAvatarBeing != nullptr))
- {
- mAvatarBeing->logic();
- if (mPlayerBox->getWidth() < CAST_S32(3 * getPadding()))
- {
- const Sprite *const sprite = mAvatarBeing->mSprites[0];
- if (sprite != nullptr)
- {
- mPlayerBox->setWidth(sprite->getWidth() + 2 * getPadding());
- mPlayerBox->setHeight(sprite->getHeight() + 2 * getPadding());
- buildLayout();
- }
- }
- }
- BLOCK_END("NpcDialog::logic")
-}
-
-void NpcDialog::clearRows()
-{
- mTextBox->clearRows();
-}
-
-void NpcDialog::clearDialogs()
-{
- NpcDialogs::iterator it = mNpcDialogs.begin();
- const NpcDialogs::iterator it_end = mNpcDialogs.end();
- while (it != it_end)
- {
- delete (*it).second;
- ++ it;
- }
- mNpcDialogs.clear();
-}
-
-void NpcDialog::mousePressed(MouseEvent &event)
-{
- Window::mousePressed(event);
- if (event.getButton() == MouseButton::RIGHT
- && event.getSource() == mTextBox)
- {
- event.consume();
- if (popupMenu != nullptr)
- {
- popupMenu->showNpcDialogPopup(mNpcId,
- viewport->mMouseX,
- viewport->mMouseY);
- }
- }
-}
-
-void NpcDialog::copyToClipboard(const int x, const int y) const
-{
- std::string str = mTextBox->getTextAtPos(x, y);
- sendBuffer(str);
-}
-
-void NpcDialog::setSkin(const std::string &skin)
-{
- if (skin.empty())
- {
- mSkinName = skin;
- mDialogInfo = nullptr;
- return;
- }
- const NpcDialogInfo *const dialog = NpcDialogDB::getDialog(skin);
- if (dialog == nullptr)
- {
- logger->log("Error: creating controls for not existing npc dialog %s",
- skin.c_str());
- return;
- }
- mSkinName = skin;
- mDialogInfo = dialog;
-}
-
-void NpcDialog::deleteSkinControls()
-{
- mSkinContainer->removeControls();
-}
-
-void NpcDialog::createSkinControls()
-{
- deleteSkinControls();
-
- if (mDialogInfo == nullptr)
- return;
-
- FOR_EACH (STD_VECTOR<NpcImageInfo*>::const_iterator,
- it,
- mDialogInfo->menu.images)
- {
- const NpcImageInfo *const info = *it;
- Image *const image = Theme::getImageFromTheme(info->name);
- if (image != nullptr)
- {
- Icon *const icon = new Icon(this, image, AutoRelease_true);
- icon->setPosition(info->x, info->y);
- mSkinContainer->add(icon);
- }
- }
- FOR_EACH (STD_VECTOR<NpcTextInfo*>::const_iterator,
- it,
- mDialogInfo->menu.texts)
- {
- const NpcTextInfo *const info = *it;
- BrowserBox *box = new BrowserBox(this,
- Opaque_true,
- "browserbox.xml");
- box->setOpaque(Opaque_false);
- box->setMaxRow(config.getIntValue("ChatLogLength"));
- box->setLinkHandler(mItemLinkHandler);
- box->setProcessVars(true);
- box->setFont(gui->getNpcFont());
- box->setEnableKeys(true);
- box->setEnableTabs(true);
- box->setPosition(info->x, info->y);
- mSkinContainer->add(box);
- box->setWidth(info->width);
- box->setHeight(info->height);
- StringVect parts;
- splitToStringVector(parts, info->text, '\n');
- FOR_EACH (StringVectCIter, it2, parts)
- {
- box->addRow(*it2);
- }
- }
- FOR_EACH (STD_VECTOR<NpcButtonInfo*>::const_iterator,
- it,
- mDialogInfo->menu.buttons)
- {
- const NpcButtonInfo *const info = *it;
- Button *const button = new Button(this);
- button->setCaption(info->name);
- button->setActionEventId("skin_" + info->value);
- button->addActionListener(this);
- button->setPosition(info->x, info->y);
- if (!info->image.empty())
- {
- button->setImageWidth(info->imageWidth);
- button->setImageHeight(info->imageHeight);
- button->loadImageSet(info->image);
- }
- mSkinContainer->add(button);
- button->adjustSize();
- }
-}
-
-void NpcDialog::restoreVirtuals()
-{
- Inventory *const inventory = PlayerInfo::getInventory();
- if (inventory != nullptr)
- inventory->restoreVirtuals();
-}
-
-std::string NpcDialog::complexItemToStr(const ComplexItem *const item)
-{
- std::string str;
- if (item != nullptr)
- {
- const STD_VECTOR<Item*> &items = item->getChilds();
- const size_t sz = items.size();
- if (sz == 0u)
- return str;
-
- const Item *item2 = items[0];
-
- str = strprintf("%d,%d",
- item2->getInvIndex(),
- item2->getQuantity());
- for (size_t f = 1; f < sz; f ++)
- {
- str.append(";");
- item2 = items[f];
- str.append(strprintf("%d,%d",
- item2->getInvIndex(),
- item2->getQuantity()));
- }
- }
- else
- {
- str.clear();
- }
- return str;
-}
-
-void NpcDialog::addCraftItem(Item *const item,
- const int amount,
- const int slot)
-{
- if (mInputState != NpcInputState::ITEM_CRAFT)
- return;
-
- Inventory *const inventory = PlayerInfo::getInventory();
-
- if (inventory == nullptr)
- return;
-
- if (mComplexInventory->addVirtualItem(
- item,
- slot,
- amount))
- {
- inventory->virtualRemove(item, amount);
- }
-}
diff --git a/src/gui/windows/npcdialog.h b/src/gui/windows/npcdialog.h
deleted file mode 100644
index 4680d774d..000000000
--- a/src/gui/windows/npcdialog.h
+++ /dev/null
@@ -1,324 +0,0 @@
-/*
- * The ManaPlus Client
- * Copyright (C) 2004-2009 The Mana World Development Team
- * Copyright (C) 2009-2010 The Mana Developers
- * Copyright (C) 2011-2017 The ManaPlus Developers
- *
- * This file is part of The ManaPlus Client.
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-#ifndef GUI_WINDOWS_NPCDIALOG_H
-#define GUI_WINDOWS_NPCDIALOG_H
-
-#include "enums/simpletypes/beingid.h"
-#include "enums/simpletypes/beingtypeid.h"
-
-#include "enums/gui/npcactionstate.h"
-#include "enums/gui/npcinputstate.h"
-
-#include "gui/models/extendedlistmodel.h"
-
-#include "gui/widgets/window.h"
-
-#include "listeners/actionlistener.h"
-
-class Being;
-class Button;
-class BrowserBox;
-class ComplexInventory;
-class ComplexItem;
-class Container;
-class ExtendedListBox;
-class Item;
-class ItemLinkHandler;
-class Inventory;
-class IntTextField;
-class ItemContainer;
-class NpcDialog;
-class PlayerBox;
-class ScrollArea;
-class TextField;
-
-struct NpcDialogInfo;
-
-typedef std::map<BeingId, NpcDialog*> NpcDialogs;
-
-/**
- * The npc dialog.
- *
- * \ingroup Interface
- */
-class NpcDialog final : public Window,
- public ActionListener,
- public ExtendedListModel,
- public ConfigListener
-{
- public:
- /**
- * Constructor.
- *
- * @see Window::Window
- */
- explicit NpcDialog(const BeingId npcId);
-
- A_DELETE_COPY(NpcDialog)
-
- ~NpcDialog();
-
- void postInit() override final;
-
- /**
- * Called when receiving actions from the widgets.
- */
- void action(const ActionEvent &event) override final;
-
- /**
- * Sets the text shows in the dialog.
- *
- * @param string The new text.
- */
-// void setText(const std::string &string);
-
- /**
- * Adds the text to the text shows in the dialog. Also adds a newline
- * to the end.
- *
- * @param string The text to add.
- */
- void addText(const std::string &string, const bool save = true);
-
- /**
- * When called, the widget will show a "Next" button.
- */
- void showNextButton();
-
- /**
- * When called, the widget will show a "Close" button and will close
- * the dialog when clicked.
- */
- void showCloseButton();
-
- /**
- * Notifies the server that client has performed a next action.
- */
- void nextDialog();
-
- /**
- * Notifies the server that the client has performed a close action.
- */
- void closeDialog();
-
- /**
- * Returns the number of items in the choices list.
- */
- int getNumberOfElements() override final A_WARN_UNUSED;
-
- /**
- * Returns the name of item number i of the choices list.
- */
- std::string getElementAt(int i) override final A_WARN_UNUSED;
-
- /**
- * Returns the image of item number i of the choices list.
- */
- const Image *getImageAt(int i) override final A_WARN_UNUSED;
-
- /**
- * Makes this dialog request a choice selection from the user.
- */
- void choiceRequest();
-
- /**
- * Adds a choice to the list box.
- */
- void addChoice(const std::string &);
-
- /**
- * Fills the options list for an NPC dialog.
- *
- * @param itemString A string with the options separated with colons.
- */
- void parseListItems(const std::string &itemString);
-
- /**
- * Requests a text string from the user.
- */
- void textRequest(const std::string &defaultText = "");
-
- bool isInputFocused() const A_WARN_UNUSED;
-
- bool isTextInputFocused() const A_WARN_UNUSED;
-
- static bool isAnyInputFocused() A_WARN_UNUSED;
-
- /**
- * Requests a interger from the user.
- */
- void integerRequest(const int defaultValue = 0, const int min = 0,
- const int max = 2147483647);
-
- void itemRequest(const int size);
-
- void itemIndexRequest(const int size);
-
- void itemCraftRequest(const int size);
-
- void move(const int amount);
-
- void setVisible(Visible visible) override final;
-
- void optionChanged(const std::string &name) override final;
-
- /**
- * Returns true if any instances exist.
- */
- static bool isActive() A_WARN_UNUSED
- { return !instances.empty(); }
-
- /**
- * Returns the first active instance. Useful for pushing user
- * interaction.
- */
- static NpcDialog *getActive() A_WARN_UNUSED;
-
- /**
- * Closes all instances.
- */
- static void closeAll();
-
- /**
- * Closes all instances and destroy also net handler dialogs.
- */
- static void destroyAll();
-
- void saveCamera();
-
- void restoreCamera();
-
- void refocus();
-
- void showAvatar(const BeingTypeId avatarId);
-
- void setAvatarDirection(const uint8_t direction);
-
- void setAvatarAction(const int actionId);
-
- void logic() override final;
-
- void clearRows();
-
- void mousePressed(MouseEvent &event) override final;
-
- int isCloseState() const
- { return static_cast<int>(mActionState == NpcActionState::CLOSE); }
-
- void setSkin(const std::string &skin);
-
- void addCraftItem(Item *const item,
- const int amount,
- const int slot);
-
- NpcInputStateT getInputState()
- { return mInputState; }
-
- void copyToClipboard(const int x, const int y) const;
-
- static NpcDialogs mNpcDialogs;
-
- static void clearDialogs();
-
- private:
- typedef std::list<NpcDialog*> DialogList;
- static DialogList instances;
-
- void buildLayout();
-
- void placeNormalControls();
-
- void placeMenuControls();
-
- void placeSkinControls();
-
- void placeTextInputControls();
-
- void placeIntInputControls();
-
- void placeItemInputControls();
-
- void createSkinControls();
-
- void deleteSkinControls();
-
- void restoreVirtuals();
-
- std::string complexItemToStr(const ComplexItem *const item);
-
- BeingId mNpcId;
-
- int mDefaultInt;
- std::string mDefaultString;
-
- // Used for the main input area
- BrowserBox *mTextBox A_NONNULLPOINTER;
- ScrollArea *mScrollArea A_NONNULLPOINTER;
- std::string mText;
- std::string mNewText;
-
- // Used for choice input
- StringVect mItems;
- STD_VECTOR<Image *> mImages;
- ExtendedListBox *mItemList A_NONNULLPOINTER;
- ScrollArea *mListScrollArea A_NONNULLPOINTER;
- Container *mSkinContainer A_NONNULLPOINTER;
- ScrollArea *mSkinScrollArea A_NONNULLPOINTER;
- ItemLinkHandler *mItemLinkHandler A_NONNULLPOINTER;
-
- // Used for string and integer input
- TextField *mTextField A_NONNULLPOINTER;
- IntTextField *mIntField A_NONNULLPOINTER;
- Button *mPlusButton A_NONNULLPOINTER;
- Button *mMinusButton A_NONNULLPOINTER;
- Button *mClearButton A_NONNULLPOINTER;
-
- // Used for the button
- Button *mButton A_NONNULLPOINTER;
- Button *mButton2 A_NONNULLPOINTER;
- Button *mButton3 A_NONNULLPOINTER;
-
- // Will reset the text and integer input to the provided default
- Button *mResetButton A_NONNULLPOINTER;
-
- Inventory *mInventory A_NONNULLPOINTER;
- ComplexInventory *mComplexInventory A_NONNULLPOINTER;
- ItemContainer *mItemContainer A_NONNULLPOINTER;
- ScrollArea *mItemScrollArea A_NONNULLPOINTER;
-
- NpcInputStateT mInputState;
- NpcActionStateT mActionState;
- STD_VECTOR<Widget*> mSkinControls;
- std::string mSkinName;
- PlayerBox *mPlayerBox A_NONNULLPOINTER;
- Being *mAvatarBeing;
- const NpcDialogInfo *mDialogInfo;
- int mLastNextTime;
- int mCameraMode;
- int mCameraX;
- int mCameraY;
- bool mShowAvatar;
- bool mLogInteraction;
-};
-
-#endif // GUI_WINDOWS_NPCDIALOG_H
diff --git a/src/gui/windows/npcselldialog.cpp b/src/gui/windows/npcselldialog.cpp
deleted file mode 100644
index c00edda6c..000000000
--- a/src/gui/windows/npcselldialog.cpp
+++ /dev/null
@@ -1,154 +0,0 @@
-/*
- * The ManaPlus Client
- * Copyright (C) 2004-2009 The Mana World Development Team
- * Copyright (C) 2009-2010 The Mana Developers
- * Copyright (C) 2011-2017 The ManaPlus Developers
- *
- * This file is part of The ManaPlus Client.
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-#include "gui/windows/npcselldialog.h"
-
-#include "being/playerinfo.h"
-
-#include "gui/windows/confirmdialog.h"
-
-#include "gui/models/shopitems.h"
-
-#include "gui/widgets/button.h"
-#include "gui/widgets/createwidget.h"
-#include "gui/widgets/shoplistbox.h"
-#include "gui/widgets/slider.h"
-
-#include "net/buysellhandler.h"
-#include "net/net.h"
-#include "net/npchandler.h"
-
-#include "resources/iteminfo.h"
-
-#include "utils/gettext.h"
-#include "utils/stringutils.h"
-
-#include "debug.h"
-
-NpcSellDialog::NpcSellDialog(const BeingId npcId) :
- SellDialog(IsSell_true,
- (Net::getNetworkType() != ServerType::TMWATHENA) ?
- Advanced_true : Advanced_false),
- mNpcId(npcId)
-{
-}
-
-void NpcSellDialog::sellAction(const ActionEvent &event)
-{
- const std::string &eventId = event.getId();
- const int selectedItem = mShopItemList->getSelected();
- const ShopItem *const item = mShopItems->at(selectedItem);
- if ((item == nullptr) || PlayerInfo::isItemProtected(item->getId()))
- return;
-
- if (eventId == "presell")
- {
- if (mAmountItems <= 0 || mAmountItems > mMaxItems)
- return;
-
- const ItemInfo &info = ItemDB::get(item->getId());
- if (info.isProtected())
- {
- ConfirmDialog *const dialog = CREATEWIDGETR(ConfirmDialog,
- // TRANSLATORS: sell confirmation header
- _("sell item"),
- // TRANSLATORS: sell confirmation message
- strprintf(_("Do you really want to sell %s?"),
- info.getName().c_str()),
- SOUND_REQUEST,
- false,
- Modal_true);
- dialog->addActionListener(this);
- return;
- }
- }
-
- if (mAdvanced == Advanced_true)
- sellManyItems(event.getId());
- else
- sellOneItem();
-}
-
-void NpcSellDialog::sellManyItems(const std::string &eventId)
-{
- if (eventId == "confirm")
- {
- npcHandler->sellItems(mShopItems->allItems());
- close();
- }
- else
- {
- const int selectedItem = mShopItemList->getSelected();
- ShopItem *const item = mShopItems->at(selectedItem);
- item->increaseUsedQuantity(mAmountItems);
- item->update();
- if (mConfirmButton != nullptr)
- mConfirmButton->setEnabled(true);
- }
-}
-
-void NpcSellDialog::sellOneItem()
-{
- if (mAmountItems <= 0 || mAmountItems > mMaxItems)
- return;
-
- const int selectedItem = mShopItemList->getSelected();
- ShopItem *const item = mShopItems->at(selectedItem);
- // Attempt sell
- mPlayerMoney += mAmountItems * mShopItems->at(selectedItem)->getPrice();
- mMaxItems -= mAmountItems;
- while (mAmountItems > 0)
- {
- // This order is important, item->getCurrentInvIndex() would
- // return the inventory index of the next Duplicate otherwise.
- const int itemIndex = item->getCurrentInvIndex();
- const int sellCount = item->sellCurrentDuplicate(mAmountItems);
- npcHandler->sellItem(mNpcId, itemIndex, sellCount);
- mAmountItems -= sellCount;
- }
-
- mPlayerMoney += mAmountItems * mShopItems->at(selectedItem)->getPrice();
- mAmountItems = 1;
- mSlider->setValue(0);
-
- if (mMaxItems != 0)
- {
- updateButtonsAndLabels();
- }
- else
- {
- // All were sold
- mShopItemList->setSelected(-1);
- mShopItems->del(selectedItem);
-
- Rect scroll;
- scroll.y = mShopItemList->getRowHeight() * (selectedItem + 1);
- scroll.height = mShopItemList->getRowHeight();
- mShopItemList->showPart(scroll);
- }
-}
-
-void NpcSellDialog::close()
-{
- buySellHandler->close();
- Window::close();
-}
diff --git a/src/gui/windows/npcselldialog.h b/src/gui/windows/npcselldialog.h
deleted file mode 100644
index 688932a1b..000000000
--- a/src/gui/windows/npcselldialog.h
+++ /dev/null
@@ -1,59 +0,0 @@
-/*
- * The ManaPlus Client
- * Copyright (C) 2004-2009 The Mana World Development Team
- * Copyright (C) 2009-2010 The Mana Developers
- * Copyright (C) 2011-2017 The ManaPlus Developers
- *
- * This file is part of The ManaPlus Client.
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-#ifndef GUI_WINDOWS_NPCSELLDIALOG_H
-#define GUI_WINDOWS_NPCSELLDIALOG_H
-
-#include "enums/simpletypes/beingid.h"
-
-#include "gui/widgets/selldialog.h"
-
-/**
- * The sell dialog.
- *
- * \ingroup Interface
- */
-class NpcSellDialog final : public SellDialog
-{
- public:
- /**
- * Constructor.
- *
- * @see Window::Window
- */
- explicit NpcSellDialog(const BeingId npcId);
-
- A_DELETE_COPY(NpcSellDialog)
-
- void close() override final;
-
- protected:
- void sellAction(const ActionEvent &event) override final;
-
- void sellOneItem();
-
- void sellManyItems(const std::string &eventId);
-
- BeingId mNpcId;
-};
-
-#endif // GUI_WINDOWS_NPCSELLDIALOG_H
diff --git a/src/gui/windows/okdialog.cpp b/src/gui/windows/okdialog.cpp
deleted file mode 100644
index 95ea9a641..000000000
--- a/src/gui/windows/okdialog.cpp
+++ /dev/null
@@ -1,94 +0,0 @@
-/*
- * The ManaPlus Client
- * Copyright (C) 2004-2009 The Mana World Development Team
- * Copyright (C) 2009-2010 The Mana Developers
- * Copyright (C) 2011-2017 The ManaPlus Developers
- *
- * This file is part of The ManaPlus Client.
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-#include "gui/windows/okdialog.h"
-
-#include "soundmanager.h"
-
-#include "const/sound.h"
-
-#include "gui/widgets/button.h"
-#include "gui/widgets/textbox.h"
-
-#include "gui/fonts/font.h"
-
-#include "debug.h"
-
-OkDialog::OkDialog(const std::string &restrict title,
- const std::string &restrict msg,
- const std::string &restrict button,
- const DialogTypeT soundEvent,
- const Modal modal,
- const ShowCenter showCenter,
- Window *const parent,
- const int minWidth) :
- Window(title, modal, parent, "ok.xml"),
- ActionListener(),
- mTextBox(new TextBox(this))
-{
- mTextBox->setEditable(false);
- mTextBox->setOpaque(Opaque_false);
- mTextBox->setTextWrapped(msg, minWidth);
-
- // TRANSLATORS: ok dialog button
- Button *const okButton = new Button(this, button, "ok", this);
-
- int width = getFont()->getWidth(title);
- if (width < mTextBox->getMinWidth())
- width = mTextBox->getMinWidth();
- if (width < okButton->getWidth())
- width = okButton->getWidth();
-
- if (mTextBox->getWidth() > width)
- width = mTextBox->getWidth();
- if (okButton->getWidth() > width)
- width = okButton->getWidth();
- setContentSize(width, mTextBox->getHeight() + okButton->getHeight()
- + getOption("buttonPadding", 8));
- mTextBox->setPosition((width - mTextBox->getWidth()) / 2, 0);
- okButton->setPosition((width - okButton->getWidth()) / 2,
- mTextBox->getHeight() + getOption("buttonPadding", 8));
-
- // +++ virtual method call
- add(mTextBox);
- add(okButton);
-
- if (showCenter == ShowCenter_true)
- center();
- else
- centerHorisontally();
- // +++ virtual method call
- setVisible(Visible_true);
- okButton->requestFocus();
-
- if (soundEvent == DialogType::OK)
- soundManager.playGuiSound(SOUND_INFO);
- else if (soundEvent == DialogType::ERROR)
- soundManager.playGuiSound(SOUND_ERROR);
-}
-
-void OkDialog::action(const ActionEvent &event)
-{
- setActionEventId(event.getId());
- distributeActionEvent();
- scheduleDelete();
-}
diff --git a/src/gui/windows/okdialog.h b/src/gui/windows/okdialog.h
deleted file mode 100644
index 1cd923e14..000000000
--- a/src/gui/windows/okdialog.h
+++ /dev/null
@@ -1,72 +0,0 @@
-/*
- * The ManaPlus Client
- * Copyright (C) 2004-2009 The Mana World Development Team
- * Copyright (C) 2009-2010 The Mana Developers
- * Copyright (C) 2011-2017 The ManaPlus Developers
- *
- * This file is part of The ManaPlus Client.
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-#ifndef GUI_WINDOWS_OKDIALOG_H
-#define GUI_WINDOWS_OKDIALOG_H
-
-#include "gui/widgets/window.h"
-
-#include "enums/gui/dialogtype.h"
-
-#include "enums/simpletypes/showcenter.h"
-
-#include "listeners/actionlistener.h"
-
-#include "localconsts.h"
-
-class TextBox;
-
-/**
- * An 'Ok' button dialog.
- *
- * \ingroup GUI
- */
-class OkDialog final : public Window,
- public ActionListener
-{
- public:
- /**
- * Constructor.
- *
- * @see Window::Window
- */
- OkDialog(const std::string &restrict title,
- const std::string &restrict msg,
- const std::string &restrict button,
- const DialogTypeT soundEvent,
- const Modal modal,
- const ShowCenter showCenter,
- Window *const parent,
- const int minWidth);
-
- A_DELETE_COPY(OkDialog)
-
- /**
- * Called when receiving actions from the widgets.
- */
- void action(const ActionEvent &event) override final;
-
- private:
- TextBox *mTextBox;
-};
-
-#endif // GUI_WINDOWS_OKDIALOG_H
diff --git a/src/gui/windows/outfitwindow.cpp b/src/gui/windows/outfitwindow.cpp
deleted file mode 100644
index fa288c7d9..000000000
--- a/src/gui/windows/outfitwindow.cpp
+++ /dev/null
@@ -1,749 +0,0 @@
-/*
- * The ManaPlus Client
- * Copyright (C) 2007-2009 The Mana World Development Team
- * Copyright (C) 2009-2010 The Mana Developers
- * Copyright (C) 2011-2017 The ManaPlus Developers
- *
- * This file is part of The ManaPlus Client.
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-#include "gui/windows/outfitwindow.h"
-
-#include "configuration.h"
-#include "dragdrop.h"
-#include "game.h"
-
-#include "being/playerinfo.h"
-
-#include "const/emoteshortcut.h"
-
-#include "enums/gui/layouttype.h"
-
-#include "input/inputactionoperators.h"
-#include "input/inputmanager.h"
-
-#include "gui/viewport.h"
-
-#include "gui/popups/popupmenu.h"
-
-#include "gui/windows/setupwindow.h"
-
-#include "gui/widgets/button.h"
-#include "gui/widgets/checkbox.h"
-#include "gui/widgets/label.h"
-#include "gui/widgets/layout.h"
-
-#include "utils/gettext.h"
-
-#include "resources/inventory/inventory.h"
-
-#include <sstream>
-
-#include "debug.h"
-
-OutfitWindow *outfitWindow = nullptr;
-
-OutfitWindow::OutfitWindow() :
- // TRANSLATORS: outfits window name
- Window(_("Outfits"), Modal_false, nullptr, "outfits.xml"),
- ActionListener(),
- // TRANSLATORS: outfits window button
- mPreviousButton(new Button(this, _("<"), "previous", this)),
- // TRANSLATORS: outfits window button
- mNextButton(new Button(this, _(">"), "next", this)),
- // TRANSLATORS: outfits window button
- mEquipBottom(new Button(this, _("Equip"), "equip", this)),
- // TRANSLATORS: outfits window label
- mCurrentLabel(new Label(this, strprintf(_("Outfit: %d"), 1))),
- // TRANSLATORS: outfits window checkbox
- mUnequipCheck(new CheckBox(this, _("Unequip first"),
- serverConfig.getValueBool("OutfitUnequip0", true))),
- // TRANSLATORS: outfits window checkbox
- mAwayOutfitCheck(new CheckBox(this, _("Away outfit"),
- serverConfig.getValue("OutfitAwayIndex", OUTFITS_COUNT - 1) != 0u)),
- // TRANSLATORS: outfits window label
- mKeyLabel(new Label(this, strprintf(_("Key: %s"),
- keyName(0).c_str()))),
- mBorderColor(getThemeColor(ThemeColorId::BORDER, 64)),
- mCurrentOutfit(0),
- mBoxWidth(33),
- mBoxHeight(33),
- mGridWidth(4),
- mGridHeight(4),
- mItems(),
- mAwayOutfit(0),
- mItemColors(),
- mItemClicked(false),
- mItemsUnequip()
-{
- setWindowName("Outfits");
- setResizable(true);
- setCloseButton(true);
- setStickyButtonLock(true);
-
- mBackgroundColor = getThemeColor(ThemeColorId::BACKGROUND, 32);
-
- setDefaultSize(250, 400, 150, 290);
- setMinWidth(145);
- setMinHeight(220);
-
- if (setupWindow != nullptr)
- setupWindow->registerWindowForReset(this);
-
- mCurrentLabel->setAlignment(Graphics::CENTER);
- mKeyLabel->setAlignment(Graphics::CENTER);
-
- mUnequipCheck->setActionEventId("unequip");
- mUnequipCheck->addActionListener(this);
-
- mAwayOutfitCheck->setActionEventId("away");
- mAwayOutfitCheck->addActionListener(this);
-
- place(1, 3, mEquipBottom, 2);
- place(0, 4, mKeyLabel, 4);
- place(0, 5, mPreviousButton, 1);
- place(1, 5, mCurrentLabel, 2);
- place(3, 5, mNextButton, 1);
- place(0, 6, mUnequipCheck, 4);
- place(0, 7, mAwayOutfitCheck, 4);
-
- Layout &layout = getLayout();
- layout.setRowHeight(0, LayoutType::SET);
- layout.setColWidth(4, Layout::CENTER);
-
- loadWindowState();
-
- enableVisibleSound(true);
- load();
-}
-
-OutfitWindow::~OutfitWindow()
-{
- save();
-}
-
-void OutfitWindow::load()
-{
- const Configuration *cfg = &serverConfig;
-
- memset(mItems, -1, sizeof(mItems));
- memset(mItemColors, 1, sizeof(mItemColors));
-
- for (unsigned o = 0; o < OUTFITS_COUNT; o++)
- {
- std::string outfit = cfg->getValue("Outfit" + toString(o), "-1");
- std::string buf;
- std::stringstream ss(outfit);
-
- STD_VECTOR<int> tokens;
-
- while (ss >> buf)
- tokens.push_back(atoi(buf.c_str()));
-
- for (size_t i = 0, sz = tokens.size();
- i < sz && i < OUTFIT_ITEM_COUNT; i++)
- {
- mItems[o][i] = tokens[i];
- }
-
- outfit = cfg->getValue("OutfitColor" + toString(o), "1");
- std::stringstream ss2(outfit);
-
- tokens.clear();
-
- STD_VECTOR<unsigned char> tokens2;
- while (ss2 >> buf)
- tokens2.push_back(CAST_U8(atoi(buf.c_str())));
-
- for (size_t i = 0, sz = tokens2.size();
- i < sz && i < OUTFIT_ITEM_COUNT; i++)
- {
- mItemColors[o][i] = fromInt(tokens2[i], ItemColor);
- }
-
- mItemsUnequip[o] = cfg->getValueBool("OutfitUnequip" + toString(o),
- true);
- }
- mAwayOutfit = cfg->getValue("OutfitAwayIndex", OUTFITS_COUNT - 1);
- if (mAwayOutfit >= CAST_S32(OUTFITS_COUNT))
- mAwayOutfit = CAST_S32(OUTFITS_COUNT) - 1;
-
- if (mAwayOutfitCheck != nullptr)
- mAwayOutfitCheck->setSelected(mAwayOutfit == mCurrentOutfit);
-}
-
-void OutfitWindow::save() const
-{
- std::string outfitStr;
- std::string outfitColorsStr;
- for (unsigned o = 0; o < OUTFITS_COUNT; o++)
- {
- bool good = false;
- for (unsigned i = 0; i < OUTFIT_ITEM_COUNT; i++)
- {
- const int val = mItems[o][i];
- const int res = val != 0 ? val : -1;
- if (res != -1)
- good = true;
- outfitStr.append(toString(res));
- if (i < OUTFIT_ITEM_COUNT - 1)
- outfitStr.append(" ");
- outfitColorsStr.append(toString(CAST_S32(
- toInt(mItemColors[o][i], int))));
- if (i < OUTFIT_ITEM_COUNT - 1)
- outfitColorsStr.append(" ");
- }
- if (good)
- {
- serverConfig.setValue("Outfit" + toString(o), outfitStr);
- serverConfig.setValue("OutfitColor" + toString(o),
- outfitColorsStr);
- }
- else
- {
- serverConfig.deleteKey("Outfit" + toString(o));
- serverConfig.deleteKey("OutfitColor" + toString(o));
- }
-
- if (mItemsUnequip[o])
- {
- serverConfig.deleteKey("OutfitUnequip" + toString(o));
- }
- else
- {
- serverConfig.setValue("OutfitUnequip" + toString(o),
- mItemsUnequip[o]);
- }
- outfitStr.clear();
- outfitColorsStr.clear();
- }
- serverConfig.setValue("OutfitAwayIndex", mAwayOutfit);
-}
-
-void OutfitWindow::action(const ActionEvent &event)
-{
- const std::string &eventId = event.getId();
- if (eventId == "next")
- {
- next();
- }
- else if (eventId == "previous")
- {
- previous();
- }
- else if (eventId == "unequip")
- {
- if (mCurrentOutfit >= 0 && mCurrentOutfit < CAST_S32(
- OUTFITS_COUNT))
- {
- mItemsUnequip[mCurrentOutfit] = mUnequipCheck->isSelected();
- }
- }
- else if (eventId == "equip")
- {
- wearOutfit(mCurrentOutfit);
- if (Game::instance() != nullptr)
- Game::instance()->setValidSpeed();
- }
- else if (eventId == "away")
- {
- mAwayOutfit = mCurrentOutfit;
- if (!mAwayOutfitCheck->isSelected())
- mAwayOutfitCheck->setSelected(true);
- }
-}
-
-void OutfitWindow::wearOutfit(const int outfit, const bool unwearEmpty,
- const bool select)
-{
- bool isEmpty = true;
-
- if (outfit < 0 || outfit > CAST_S32(OUTFITS_COUNT))
- return;
-
- for (unsigned i = 0; i < OUTFIT_ITEM_COUNT; i++)
- {
- const Item *const item = PlayerInfo::getInventory()->findItem(
- mItems[outfit][i],
- mItemColors[outfit][i]);
- if ((item != nullptr)
- && item->isEquipped() == Equipped_false
- && (item->getQuantity() != 0))
- {
- if (item->isEquipment() == Equipm_true)
- {
- PlayerInfo::equipItem(item, Sfx_false);
- isEmpty = false;
- }
- }
- }
-
- if ((!isEmpty || unwearEmpty) && outfit < CAST_S32(OUTFITS_COUNT)
- && mItemsUnequip[outfit])
- {
- unequipNotInOutfit(outfit);
- }
- if (select)
- {
- mCurrentOutfit = outfit;
- showCurrentOutfit();
- }
-}
-
-void OutfitWindow::copyOutfit(const int outfit)
-{
- copyOutfit(outfit, mCurrentOutfit);
-}
-
-void OutfitWindow::copyOutfit(const int src, const int dst)
-{
- if (src < 0 || src > CAST_S32(OUTFITS_COUNT)
- || dst < 0 || dst > CAST_S32(OUTFITS_COUNT))
- {
- return;
- }
-
- for (unsigned int i = 0; i < OUTFIT_ITEM_COUNT; i++)
- mItems[dst][i] = mItems[src][i];
- save();
-}
-
-void OutfitWindow::draw(Graphics *const graphics)
-{
- BLOCK_START("OutfitWindow::draw")
- Window::draw(graphics);
-
- if (mCurrentOutfit < 0 || mCurrentOutfit
- >= static_cast<signed int>(OUTFITS_COUNT))
- {
- return;
- }
-
- for (unsigned int i = 0; i < OUTFIT_ITEM_COUNT; i++)
- {
- const int itemX = mPadding + ((i % mGridWidth) * mBoxWidth);
- const int itemY = mPadding + mTitleBarHeight
- + ((i / CAST_U32(mGridWidth)) * mBoxHeight);
-
- graphics->setColor(mBorderColor);
- graphics->drawRectangle(Rect(itemX, itemY, 32, 32));
- graphics->setColor(mBackgroundColor);
- graphics->fillRectangle(Rect(itemX, itemY, 32, 32));
-
- if (mItems[mCurrentOutfit][i] < 0)
- continue;
-
- bool foundItem = false;
- const Inventory *const inv = PlayerInfo::getInventory();
- if (inv != nullptr)
- {
- const Item *const item = inv->findItem(mItems[mCurrentOutfit][i],
- mItemColors[mCurrentOutfit][i]);
- if (item != nullptr)
- {
- // Draw item icon.
- const Image *const image = item->getImage();
- if (image != nullptr)
- {
- graphics->drawImage(image, itemX, itemY);
- foundItem = true;
- }
- }
- }
- if (!foundItem)
- {
- Image *const image = Item::getImage(mItems[mCurrentOutfit][i],
- mItemColors[mCurrentOutfit][i]);
- if (image != nullptr)
- {
- graphics->drawImage(image, itemX, itemY);
- image->decRef();
- }
- }
- }
- BLOCK_END("OutfitWindow::draw")
-}
-
-void OutfitWindow::safeDraw(Graphics *const graphics)
-{
- BLOCK_START("OutfitWindow::draw")
- Window::safeDraw(graphics);
-
- if (mCurrentOutfit < 0 || mCurrentOutfit
- >= static_cast<signed int>(OUTFITS_COUNT))
- {
- return;
- }
-
- for (unsigned int i = 0; i < OUTFIT_ITEM_COUNT; i++)
- {
- const int itemX = mPadding + ((i % mGridWidth) * mBoxWidth);
- const int itemY = mPadding + mTitleBarHeight
- + ((i / CAST_U32(mGridWidth)) * mBoxHeight);
-
- graphics->setColor(mBorderColor);
- graphics->drawRectangle(Rect(itemX, itemY, 32, 32));
- graphics->setColor(mBackgroundColor);
- graphics->fillRectangle(Rect(itemX, itemY, 32, 32));
-
- if (mItems[mCurrentOutfit][i] < 0)
- continue;
-
- bool foundItem = false;
- const Inventory *const inv = PlayerInfo::getInventory();
- if (inv != nullptr)
- {
- const Item *const item = inv->findItem(mItems[mCurrentOutfit][i],
- mItemColors[mCurrentOutfit][i]);
- if (item != nullptr)
- {
- // Draw item icon.
- const Image *const image = item->getImage();
- if (image != nullptr)
- {
- graphics->drawImage(image, itemX, itemY);
- foundItem = true;
- }
- }
- }
- if (!foundItem)
- {
- Image *const image = Item::getImage(mItems[mCurrentOutfit][i],
- mItemColors[mCurrentOutfit][i]);
- if (image != nullptr)
- {
- graphics->drawImage(image, itemX, itemY);
- image->decRef();
- }
- }
- }
- BLOCK_END("OutfitWindow::draw")
-}
-
-void OutfitWindow::mouseDragged(MouseEvent &event)
-{
- if (event.getButton() == MouseButton::LEFT)
- {
- if (dragDrop.isEmpty() && mItemClicked)
- {
- if (mCurrentOutfit < 0 || mCurrentOutfit
- >= static_cast<signed int>(OUTFITS_COUNT))
- {
- Window::mouseDragged(event);
- return;
- }
-
- const int index = getIndexFromGrid(event.getX(), event.getY());
- if (index == -1)
- {
- Window::mouseDragged(event);
- return;
- }
- const int itemId = mItems[mCurrentOutfit][index];
- const ItemColor itemColor = mItemColors[mCurrentOutfit][index];
- if (itemId < 0)
- {
- Window::mouseDragged(event);
- return;
- }
- mMoved = false;
- event.consume();
- const Inventory *const inv = PlayerInfo::getInventory();
- if (inv != nullptr)
- {
- Item *const item = inv->findItem(itemId, itemColor);
- if (item != nullptr)
- dragDrop.dragItem(item, DragDropSource::Outfit);
- else
- dragDrop.clear();
- mItems[mCurrentOutfit][index] = -1;
- }
- }
- }
- Window::mouseDragged(event);
-}
-
-void OutfitWindow::mousePressed(MouseEvent &event)
-{
- const int index = getIndexFromGrid(event.getX(), event.getY());
- if (event.getButton() == MouseButton::RIGHT && (popupMenu != nullptr))
- {
- popupMenu->showOutfitsWindowPopup(viewport->mMouseX,
- viewport->mMouseY);
- event.consume();
- return;
- }
- else if (index == -1)
- {
- Window::mousePressed(event);
- return;
- }
- mMoved = false;
- event.consume();
-
- if (mItems[mCurrentOutfit][index] > 0)
- {
- mItemClicked = true;
- }
- else
- {
- if (dragDrop.isSelected())
- {
- mItems[mCurrentOutfit][index] = dragDrop.getSelected();
- mItemColors[mCurrentOutfit][index] = dragDrop.getSelectedColor();
- dragDrop.deselect();
- save();
- }
- }
-
- Window::mousePressed(event);
-}
-
-void OutfitWindow::mouseReleased(MouseEvent &event)
-{
- if (event.getButton() == MouseButton::LEFT)
- {
- if (mCurrentOutfit < 0 || mCurrentOutfit
- >= static_cast<signed int>(OUTFITS_COUNT))
- {
- return;
- }
- const int index = getIndexFromGrid(event.getX(), event.getY());
- if (index == -1)
- {
- dragDrop.clear();
- Window::mouseReleased(event);
- return;
- }
- mMoved = false;
- event.consume();
- if (!dragDrop.isEmpty())
- {
- if (dragDrop.isSourceItemContainer())
- {
- mItems[mCurrentOutfit][index] = dragDrop.getItem();
- mItemColors[mCurrentOutfit][index] = dragDrop.getItemColor();
- dragDrop.clear();
- dragDrop.deselect();
- save();
- }
- }
- if (mItemClicked)
- mItemClicked = false;
- }
- Window::mouseReleased(event);
-}
-
-int OutfitWindow::getIndexFromGrid(const int pointX, const int pointY) const
-{
- const Rect tRect = Rect(mPadding, mTitleBarHeight,
- mGridWidth * mBoxWidth, mGridHeight * mBoxHeight);
- if (!tRect.isPointInRect(pointX, pointY))
- return -1;
- const int index = (((pointY - mTitleBarHeight) / mBoxHeight) * mGridWidth)
- + (pointX - mPadding) / mBoxWidth;
- if (index >= CAST_S32(OUTFIT_ITEM_COUNT) || index < 0)
- return -1;
- return index;
-}
-
-void OutfitWindow::unequipNotInOutfit(const int outfit) const
-{
- // here we think that outfit is correct index
-
- const Inventory *const inventory = PlayerInfo::getInventory();
- if (inventory == nullptr)
- return;
-
- const unsigned int invSize = inventory->getSize();
- for (unsigned i = 0; i < invSize; i++)
- {
- const Item *const item = inventory->getItem(i);
- if ((item != nullptr) && item->isEquipped() == Equipped_true)
- {
- bool found = false;
- for (unsigned f = 0; f < OUTFIT_ITEM_COUNT; f++)
- {
- if (item->getId() == mItems[outfit][f])
- {
- found = true;
- break;
- }
- }
- if (!found)
- PlayerInfo::unequipItem(item, Sfx_false);
- }
- }
-}
-
-std::string OutfitWindow::keyName(const int number)
-{
- if (number < 0 || number >= SHORTCUT_EMOTES)
- return "";
- return inputManager.getKeyStringLong(InputAction::OUTFIT_1 + number);
-}
-
-void OutfitWindow::next()
-{
- if (mCurrentOutfit < (CAST_S32(OUTFITS_COUNT) - 1))
- mCurrentOutfit++;
- else
- mCurrentOutfit = 0;
- showCurrentOutfit();
-}
-
-void OutfitWindow::previous()
-{
- if (mCurrentOutfit > 0)
- mCurrentOutfit--;
- else
- mCurrentOutfit = OUTFITS_COUNT - 1;
- showCurrentOutfit();
-}
-
-void OutfitWindow::showCurrentOutfit()
-{
- // TRANSLATORS: outfits window label
- mCurrentLabel->setCaption(strprintf(_("Outfit: %d"), mCurrentOutfit + 1));
- if (mCurrentOutfit < CAST_S32(OUTFITS_COUNT))
- mUnequipCheck->setSelected(mItemsUnequip[mCurrentOutfit]);
- else
- mUnequipCheck->setSelected(false);
- // TRANSLATORS: outfits window label
- mKeyLabel->setCaption(strprintf(_("Key: %s"),
- keyName(mCurrentOutfit).c_str()));
- mAwayOutfitCheck->setSelected(mAwayOutfit == mCurrentOutfit);
-}
-
-void OutfitWindow::wearNextOutfit(const bool all)
-{
- next();
- if (!all && mCurrentOutfit >= 0 && mCurrentOutfit
- < CAST_S32(OUTFITS_COUNT))
- {
- bool fromStart = false;
- while (!mItemsUnequip[mCurrentOutfit])
- {
- next();
- if (mCurrentOutfit == 0)
- {
- if (!fromStart)
- fromStart = true;
- else
- return;
- }
- }
- }
- wearOutfit(mCurrentOutfit);
-}
-
-void OutfitWindow::wearPreviousOutfit(const bool all)
-{
- previous();
- if (!all && mCurrentOutfit >= 0 && mCurrentOutfit
- < CAST_S32(OUTFITS_COUNT))
- {
- bool fromStart = false;
- while (!mItemsUnequip[mCurrentOutfit])
- {
- previous();
- if (mCurrentOutfit == 0)
- {
- if (!fromStart)
- fromStart = true;
- else
- return;
- }
- }
- }
- wearOutfit(mCurrentOutfit);
-}
-
-void OutfitWindow::copyFromEquiped()
-{
- copyFromEquiped(mCurrentOutfit);
-}
-
-void OutfitWindow::copyFromEquiped(const int dst)
-{
- const Inventory *const inventory = PlayerInfo::getInventory();
- if (inventory == nullptr)
- return;
-
- int outfitCell = 0;
- for (unsigned i = 0, sz = inventory->getSize(); i < sz; i++)
- {
- const Item *const item = inventory->getItem(i);
- if ((item != nullptr) && item->isEquipped() == Equipped_true)
- {
- mItems[dst][outfitCell] = item->getId();
- mItemColors[dst][outfitCell++] = item->getColor();
- if (outfitCell >= CAST_S32(OUTFIT_ITEM_COUNT))
- break;
- }
- }
- save();
-}
-
-void OutfitWindow::wearAwayOutfit()
-{
- copyFromEquiped(OUTFITS_COUNT);
- wearOutfit(mAwayOutfit, false);
-}
-
-void OutfitWindow::unwearAwayOutfit()
-{
- wearOutfit(OUTFITS_COUNT);
-}
-
-void OutfitWindow::clearCurrentOutfit()
-{
- if (mCurrentOutfit < 0 || mCurrentOutfit
- >= static_cast<signed int>(OUTFITS_COUNT))
- {
- return;
- }
- for (unsigned f = 0; f < OUTFIT_ITEM_COUNT; f++)
- {
- mItems[mCurrentOutfit][f] = -1;
- mItemColors[mCurrentOutfit][f] = ItemColor_one;
- }
- save();
-}
-
-std::string OutfitWindow::getOutfitString() const
-{
- std::string str;
- for (unsigned int i = 0; i < OUTFIT_ITEM_COUNT; i++)
- {
- const int id = mItems[mCurrentOutfit][i];
- if (id < 0)
- continue;
-
- const ItemColor color = mItemColors[mCurrentOutfit][i];
- STD_VECTOR<int> ids;
- ids.push_back(id);
- ids.push_back(CAST_S32(color));
-
- const std::string name = ItemDB::getNamesStr(ids);
- if (name.empty())
- continue;
- str.append("[");
- str.append(name);
- str.append("] ");
- }
- return str;
-}
diff --git a/src/gui/windows/outfitwindow.h b/src/gui/windows/outfitwindow.h
deleted file mode 100644
index cf2799d2b..000000000
--- a/src/gui/windows/outfitwindow.h
+++ /dev/null
@@ -1,133 +0,0 @@
-/*
- * The ManaPlus Client
- * Copyright (C) 2007-2009 The Mana World Development Team
- * Copyright (C) 2009-2010 The Mana Developers
- * Copyright (C) 2011-2017 The ManaPlus Developers
- *
- * This file is part of The ManaPlus Client.
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-#ifndef GUI_WINDOWS_OUTFITWINDOW_H
-#define GUI_WINDOWS_OUTFITWINDOW_H
-
-#include "enums/simpletypes/itemcolor.h"
-
-#include "gui/widgets/window.h"
-
-#include "listeners/actionlistener.h"
-
-const unsigned int OUTFITS_COUNT = 100;
-const unsigned int OUTFIT_ITEM_COUNT = 16;
-
-class Button;
-class CheckBox;
-class Label;
-
-class OutfitWindow final : public Window,
- private ActionListener
-{
- public:
- /**
- * Constructor.
- */
- OutfitWindow();
-
- A_DELETE_COPY(OutfitWindow)
-
- /**
- * Destructor.
- */
- ~OutfitWindow();
-
- void action(const ActionEvent &event) override final;
-
- void draw(Graphics *const graphics) override final A_NONNULL(2);
-
- void safeDraw(Graphics *const graphics) override final A_NONNULL(2);
-
- void mousePressed(MouseEvent &event) override final;
-
- void mouseDragged(MouseEvent &event) override final;
-
- void mouseReleased(MouseEvent &event) override final;
-
- void load();
-
- void wearOutfit(const int outfit, const bool unwearEmpty = true,
- const bool select = false);
-
- void copyOutfit(const int outfit);
-
- void copyOutfit(const int src, const int dst);
-
- void copyFromEquiped();
-
- void copyFromEquiped(const int dst);
-
- void unequipNotInOutfit(const int outfit) const;
-
- void next();
-
- void previous();
-
- void wearNextOutfit(const bool all = false);
-
- void wearPreviousOutfit(const bool all = false);
-
- void wearAwayOutfit();
-
- void unwearAwayOutfit();
-
- void showCurrentOutfit();
-
- static std::string keyName(const int number) A_WARN_UNUSED;
-
- void clearCurrentOutfit();
-
- std::string getOutfitString() const;
-
- private:
- int getIndexFromGrid(const int pointX,
- const int pointY) const A_WARN_UNUSED;
- void save() const;
-
- Button *mPreviousButton A_NONNULLPOINTER;
- Button *mNextButton A_NONNULLPOINTER;
- Button *mEquipBottom A_NONNULLPOINTER;
- Label *mCurrentLabel A_NONNULLPOINTER;
- CheckBox *mUnequipCheck A_NONNULLPOINTER;
- CheckBox *mAwayOutfitCheck A_NONNULLPOINTER;
- Label *mKeyLabel A_NONNULLPOINTER;
-
- Color mBorderColor;
-
- int mCurrentOutfit;
- int mBoxWidth;
- int mBoxHeight;
- int mGridWidth;
- int mGridHeight;
-
- int mItems[OUTFITS_COUNT + 1][OUTFIT_ITEM_COUNT];
- int mAwayOutfit;
-
- ItemColor mItemColors[OUTFITS_COUNT + 1][OUTFIT_ITEM_COUNT];
- bool mItemClicked;
- bool mItemsUnequip[OUTFITS_COUNT];
-};
-
-extern OutfitWindow *outfitWindow;
-
-#endif // GUI_WINDOWS_OUTFITWINDOW_H
diff --git a/src/gui/windows/questswindow.cpp b/src/gui/windows/questswindow.cpp
deleted file mode 100644
index 269f2aab9..000000000
--- a/src/gui/windows/questswindow.cpp
+++ /dev/null
@@ -1,483 +0,0 @@
-/*
- * The ManaPlus Client
- * Copyright (C) 2012-2017 The ManaPlus Developers
- *
- * This file is part of The ManaPlus Client.
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-#include "gui/windows/questswindow.h"
-
-#include "actormanager.h"
-#include "configuration.h"
-#include "effectmanager.h"
-
-#include "being/localplayer.h"
-
-#include "enums/gui/layouttype.h"
-
-#include "gui/gui.h"
-
-#include "gui/fonts/font.h"
-
-#include "gui/models/questsmodel.h"
-
-#include "gui/windows/setupwindow.h"
-
-#include "gui/widgets/button.h"
-#include "gui/widgets/browserbox.h"
-#include "gui/widgets/containerplacer.h"
-#include "gui/widgets/createwidget.h"
-#include "gui/widgets/layout.h"
-#include "gui/widgets/extendedlistbox.h"
-#include "gui/widgets/itemlinkhandler.h"
-#include "gui/widgets/scrollarea.h"
-
-#include "utils/delete2.h"
-#include "utils/foreach.h"
-#include "utils/gettext.h"
-
-#include "resources/questeffect.h"
-#include "resources/questitem.h"
-
-#include "resources/db/questdb.h"
-
-#include "resources/map/map.h"
-
-#include "debug.h"
-
-QuestsWindow *questsWindow = nullptr;
-
-QuestsWindow::QuestsWindow() :
- // TRANSLATORS: quests window name
- Window(_("Quests"), Modal_false, nullptr, "quests.xml"),
- ActionListener(),
- mQuestsModel(new QuestsModel),
- mQuestsListBox(CREATEWIDGETR(ExtendedListBox,
- this, mQuestsModel, "extendedlistbox.xml")),
- mQuestScrollArea(new ScrollArea(this, mQuestsListBox,
- fromBool(getOptionBool("showlistbackground"), Opaque),
- "quests_list_background.xml")),
- mItemLinkHandler(new ItemLinkHandler),
- mText(new BrowserBox(this, Opaque_true,
- "browserbox.xml")),
- mTextScrollArea(new ScrollArea(this, mText,
- fromBool(getOptionBool("showtextbackground"), Opaque),
- "quests_text_background.xml")),
- // TRANSLATORS: quests window button
- mCloseButton(new Button(this, _("Close"), "close", this)),
- mCompleteIcon(Theme::getImageFromThemeXml("complete_icon.xml", "")),
- mIncompleteIcon(Theme::getImageFromThemeXml("incomplete_icon.xml", "")),
- mMapEffects(),
- mVars(nullptr),
- mQuests(nullptr),
- mAllEffects(nullptr),
- mNpcEffects(),
- mQuestLinks(),
- mQuestReverseLinks(),
- mNewQuestEffectId(paths.getIntValue("newQuestEffectId")),
- mCompleteQuestEffectId(paths.getIntValue("completeQuestEffectId")),
- mMap(nullptr)
-{
- setWindowName("Quests");
- setResizable(true);
- setCloseButton(true);
- setStickyButtonLock(true);
- setSaveVisible(true);
-
- setDefaultSize(400, 350, ImagePosition::RIGHT);
- setMinWidth(310);
- setMinHeight(220);
-
- if (setupWindow != nullptr)
- setupWindow->registerWindowForReset(this);
-
- mQuestsListBox->setActionEventId("select");
- mQuestsListBox->addActionListener(this);
-
- mQuestScrollArea->setHorizontalScrollPolicy(ScrollArea::SHOW_NEVER);
- mText->setOpaque(Opaque_false);
- mText->setLinkHandler(mItemLinkHandler);
- mTextScrollArea->setHorizontalScrollPolicy(ScrollArea::SHOW_NEVER);
- mQuestsListBox->setWidth(500);
- if ((gui == nullptr) || gui->getNpcFont()->getHeight() < 20)
- mQuestsListBox->setRowHeight(20);
- else
- mQuestsListBox->setRowHeight(gui->getNpcFont()->getHeight());
-
- ContainerPlacer placer;
- placer = getPlacer(0, 0);
-
- placer(0, 0, mQuestScrollArea, 4, 3).setPadding(3);
- placer(4, 0, mTextScrollArea, 4, 3).setPadding(3);
- placer(7, 3, mCloseButton);
-
- Layout &layout = getLayout();
- layout.setRowHeight(0, LayoutType::SET);
-
- loadWindowState();
- enableVisibleSound(true);
- QuestDb::load();
- mVars = QuestDb::getVars();
- mQuests = QuestDb::getQuests();
- mAllEffects = QuestDb::getAllEffects();
-}
-
-QuestsWindow::~QuestsWindow()
-{
- delete2(mQuestsModel);
-
- QuestDb::unload();
-
- delete2(mItemLinkHandler);
- mQuestLinks.clear();
- mQuestReverseLinks.clear();
- if (mCompleteIcon != nullptr)
- {
- mCompleteIcon->decRef();
- mCompleteIcon = nullptr;
- }
- if (mIncompleteIcon != nullptr)
- {
- mIncompleteIcon->decRef();
- mIncompleteIcon = nullptr;
- }
-}
-
-void QuestsWindow::action(const ActionEvent &event)
-{
- const std::string &eventId = event.getId();
- if (eventId == "select")
- {
- const int id = mQuestsListBox->getSelected();
- if (id < 0)
- return;
- showQuest(mQuestLinks[id]);
- }
- else if (eventId == "close")
- {
- setVisible(Visible_false);
- }
-}
-
-void QuestsWindow::updateQuest(const int var,
- const int val1,
- const int val2,
- const int val3,
- const int time1)
-{
- (*mVars)[var] = QuestVar(val1, val2, val3, time1);
-}
-
-void QuestsWindow::rebuild(const bool playSound)
-{
- mQuestsModel->clear();
- mQuestLinks.clear();
- mQuestReverseLinks.clear();
- StringVect &names = mQuestsModel->getNames();
- STD_VECTOR<Image*> &images = mQuestsModel->getImages();
- STD_VECTOR<QuestItem*> complete;
- STD_VECTOR<QuestItem*> incomplete;
- STD_VECTOR<QuestItem*> hidden;
- int updatedQuest = -1;
- int newCompleteStatus = -1;
-
- FOR_EACHP (NpcQuestVarMapCIter, it, mVars)
- {
- const int var = (*it).first;
- const QuestVar &val = (*it).second;
- const STD_VECTOR<QuestItem*> &quests = (*mQuests)[var];
- FOR_EACH (STD_VECTOR<QuestItem*>::const_iterator, it2, quests)
- {
- if (*it2 == nullptr)
- continue;
- QuestItem *const quest = *it2;
- // complete quest
- if (quest->complete.find(val.var1) != quest->complete.end())
- {
- complete.push_back(quest);
- }
- // incomplete quest
- else if (quest->incomplete.find(val.var1) !=
- quest->incomplete.end())
- {
- incomplete.push_back(quest);
- }
- // hidden quest
- else
- {
- hidden.push_back(quest);
- }
- }
- }
-
- int k = 0;
-
- for (STD_VECTOR<QuestItem*>::const_iterator it = complete.begin(),
- it_end = complete.end(); it != it_end; ++ it, k ++)
- {
- QuestItem *const quest = *it;
- if (quest->completeFlag == 0 || (quest->broken
- && quest->completeFlag == -1))
- {
- updatedQuest = k;
- newCompleteStatus = 1;
- }
- quest->completeFlag = 1;
- mQuestLinks.push_back(quest);
- mQuestReverseLinks[quest->var] = k;
- names.push_back(quest->name);
- if (mCompleteIcon != nullptr)
- {
- mCompleteIcon->incRef();
- images.push_back(mCompleteIcon);
- }
- else
- {
- images.push_back(nullptr);
- }
- }
-
- for (STD_VECTOR<QuestItem*>::const_iterator it = incomplete.begin(),
- it_end = incomplete.end(); it != it_end; ++ it, k ++)
- {
- QuestItem *const quest = *it;
- if (quest->completeFlag == -1)
- {
- updatedQuest = k;
- newCompleteStatus = 0;
- }
- quest->completeFlag = 0;
- mQuestLinks.push_back(quest);
- mQuestReverseLinks[quest->var] = k;
- names.push_back(quest->name);
- if (mIncompleteIcon != nullptr)
- {
- mIncompleteIcon->incRef();
- images.push_back(mIncompleteIcon);
- }
- else
- {
- images.push_back(nullptr);
- }
- }
-
- FOR_EACH (STD_VECTOR<QuestItem*>::const_iterator, it, hidden)
- (*it)->completeFlag = -1;
-
- if (updatedQuest == -1 || updatedQuest >= CAST_S32(
- mQuestLinks.size()))
- {
- updatedQuest = CAST_S32(mQuestLinks.size() - 1);
- }
- if (updatedQuest >= 0)
- {
- mQuestsListBox->setSelected(updatedQuest);
- showQuest(mQuestLinks[updatedQuest]);
- if (playSound && (effectManager != nullptr))
- {
- switch (newCompleteStatus)
- {
- case 0:
- effectManager->trigger(mNewQuestEffectId, localPlayer);
- break;
- case 1:
- effectManager->trigger(mCompleteQuestEffectId,
- localPlayer);
- break;
- default:
- break;
- }
- }
- }
- updateEffects();
-}
-
-void QuestsWindow::showQuest(const QuestItem *const quest)
-{
- if (quest == nullptr)
- return;
-
- const STD_VECTOR<QuestItemText> &texts = quest->texts;
- const QuestVar &var = (*mVars)[quest->var];
- const std::string var1 = toString(var.var1);
- const std::string var2 = toString(var.var2);
- const std::string var3 = toString(var.var3);
- const std::string timeStr = timeDiffToString(var.time1);
- mText->clearRows();
- FOR_EACH (STD_VECTOR<QuestItemText>::const_iterator, it, texts)
- {
- const QuestItemText &data = *it;
- std::string text = data.text;
- replaceAll(text, "{@@var1}", var1);
- replaceAll(text, "{@@var2}", var2);
- replaceAll(text, "{@@var3}", var3);
- replaceAll(text, "{@@time}", timeStr);
- switch (data.type)
- {
- case QuestType::TEXT:
- default:
- mText->addRow(text);
- break;
- case QuestType::NAME:
- mText->addRow(std::string("[").append(text).append("]"));
- break;
- case QuestType::REWARD:
- mText->addRow(std::string(
- // TRANSLATORS: quest reward
- _("Reward:")).append(
- " ").append(
- text));
- break;
- case QuestType::GIVER:
- mText->addRow(std::string(
- // TRANSLATORS: quest giver name
- _("Quest Giver:")).append(
- " ").append(
- text));
- break;
- case QuestType::NPC:
- mText->addRow(std::string(
- // TRANSLATORS: quest npc name
- _("Npc:")).append(
- " ").append(
- text));
- break;
- case QuestType::COORDINATES:
- mText->addRow(std::string(
- strprintf("%s [@@=navigate %s %s|%s@@]",
- // TRANSLATORS: quest coordinates
- _("Coordinates:"),
- data.data1.c_str(),
- data.data2.c_str(),
- text.c_str())));
- break;
- }
- }
- mText->updateHeight();
-}
-
-void QuestsWindow::setMap(const Map *const map)
-{
- if (mMap != map)
- {
- mMap = map;
- mMapEffects.clear();
- if (mMap == nullptr)
- return;
-
- const std::string name = mMap->getProperty("shortName");
- FOR_EACHP (STD_VECTOR<QuestEffect*>::const_iterator, it, mAllEffects)
- {
- const QuestEffect *const effect = *it;
- if ((effect != nullptr) && name == effect->map)
- mMapEffects.push_back(effect);
- }
- updateEffects();
- }
-}
-
-void QuestsWindow::updateEffects()
-{
- NpcQuestEffectMap oldNpc = mNpcEffects;
- mNpcEffects.clear();
-
- FOR_EACH (STD_VECTOR<const QuestEffect*>::const_iterator,
- it, mMapEffects)
- {
- const QuestEffect *const effect = *it;
- if (effect != nullptr)
- {
- const NpcQuestVarMapCIter varIt = mVars->find(effect->var);
- if (varIt != mVars->end())
- {
- const std::set<int> &vals = effect->values;
- if (vals.find((*mVars)[effect->var].var1) != vals.end())
- mNpcEffects[effect->id] = effect;
- }
- }
- }
- if (actorManager == nullptr)
- return;
-
- std::set<BeingTypeId> removeEffects;
- std::map<BeingTypeId, int> addEffects;
-
- // for old effects
- FOR_EACH (NpcQuestEffectMapCIter, it, oldNpc)
- {
- const BeingTypeId id = (*it).first;
- const QuestEffect *const effect = (*it).second;
-
- const NpcQuestEffectMapCIter itNew = mNpcEffects.find(id);
- if (itNew == mNpcEffects.end())
- { // in new list no effect for this npc
- removeEffects.insert(id);
- }
- else
- { // in new list exists effect for this npc
- const QuestEffect *const newEffect = (*itNew).second;
- if (effect != newEffect)
- { // new effects is not equal to old effect
- addEffects[id] = newEffect->effectId;
- removeEffects.insert(id);
- }
- }
- }
-
- // for new effects
- FOR_EACH (NpcQuestEffectMapCIter, it, mNpcEffects)
- {
- const BeingTypeId id = (*it).first;
- const QuestEffect *const effect = (*it).second;
-
- const NpcQuestEffectMapCIter itNew = oldNpc.find(id);
- // check if old effect was not present
- if (itNew == oldNpc.end())
- addEffects[id] = effect->effectId;
- }
- if (!removeEffects.empty() || !addEffects.empty())
- actorManager->updateEffects(addEffects, removeEffects);
-}
-
-void QuestsWindow::addEffect(Being *const being)
-{
- if (being == nullptr)
- return;
- const BeingTypeId id = being->getSubType();
- const std::map<BeingTypeId, const QuestEffect*>::const_iterator
- it = mNpcEffects.find(id);
- if (it != mNpcEffects.end())
- {
- const QuestEffect *const effect = (*it).second;
- if (effect != nullptr)
- being->addSpecialEffect(effect->effectId);
- }
-}
-
-void QuestsWindow::selectQuest(const int varId)
-{
- std::map<int, int>::const_iterator it = mQuestReverseLinks.find(varId);
- if (it == mQuestReverseLinks.end())
- return;
- if (mVisible == Visible_false)
- setVisible(Visible_true);
- const int listPos = (*it).second;
- if (listPos < 0)
- return;
- showQuest(mQuestLinks[listPos]);
- mQuestsListBox->setSelected(listPos);
- requestMoveToTop();
-}
diff --git a/src/gui/windows/questswindow.h b/src/gui/windows/questswindow.h
deleted file mode 100644
index fd4175754..000000000
--- a/src/gui/windows/questswindow.h
+++ /dev/null
@@ -1,105 +0,0 @@
-/*
- * The ManaPlus Client
- * Copyright (C) 2012-2017 The ManaPlus Developers
- *
- * This file is part of The ManaPlus Client.
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-#ifndef GUI_WINDOWS_QUESTSWINDOW_H
-#define GUI_WINDOWS_QUESTSWINDOW_H
-
-#include "localconsts.h"
-
-#include "enums/simpletypes/beingtypeid.h"
-
-#include "gui/widgets/window.h"
-
-#include "listeners/actionlistener.h"
-
-#include "resources/questvar.h"
-
-class Being;
-class BrowserBox;
-class Button;
-class ExtendedListBox;
-class ItemLinkHandler;
-class Map;
-class ScrollArea;
-class QuestsModel;
-
-struct QuestEffect;
-struct QuestItem;
-
-typedef std::map<BeingTypeId, const QuestEffect*> NpcQuestEffectMap;
-typedef NpcQuestEffectMap::const_iterator NpcQuestEffectMapCIter;
-
-class QuestsWindow final : public Window,
- public ActionListener
-{
- public:
- QuestsWindow();
-
- A_DELETE_COPY(QuestsWindow)
-
- ~QuestsWindow();
-
- void action(const ActionEvent &event) override final;
-
- void updateQuest(const int var,
- const int val1,
- const int val2,
- const int val3,
- const int time1);
-
- void rebuild(const bool playSound);
-
- void showQuest(const QuestItem *const quest);
-
- void setMap(const Map *const map);
-
- void updateEffects();
-
- void addEffect(Being *const being);
-
- void selectQuest(const int varId);
-
- private:
- QuestsModel *mQuestsModel A_NONNULLPOINTER;
- ExtendedListBox *mQuestsListBox A_NONNULLPOINTER;
- ScrollArea *mQuestScrollArea A_NONNULLPOINTER;
- ItemLinkHandler *mItemLinkHandler A_NONNULLPOINTER;
- BrowserBox *mText A_NONNULLPOINTER;
- ScrollArea *mTextScrollArea A_NONNULLPOINTER;
- Button *mCloseButton A_NONNULLPOINTER;
- Image *mCompleteIcon;
- Image *mIncompleteIcon;
- STD_VECTOR<const QuestEffect*> mMapEffects;
- NpcQuestVarMap *mVars;
- std::map<int, STD_VECTOR<QuestItem*> > *mQuests;
- STD_VECTOR<QuestEffect*> *mAllEffects;
-
- // npc effects for current map and values: npc, effect
- NpcQuestEffectMap mNpcEffects;
- STD_VECTOR<QuestItem*> mQuestLinks;
- std::map<int, int> mQuestReverseLinks;
- int mNewQuestEffectId;
- int mCompleteQuestEffectId;
- const Map *mMap;
-};
-
-extern QuestsWindow *questsWindow;
-
-#endif // GUI_WINDOWS_QUESTSWINDOW_H
diff --git a/src/gui/windows/quitdialog.cpp b/src/gui/windows/quitdialog.cpp
deleted file mode 100644
index b9ef417c3..000000000
--- a/src/gui/windows/quitdialog.cpp
+++ /dev/null
@@ -1,260 +0,0 @@
-/*
- * The ManaPlus Client
- * Copyright (C) 2004-2009 The Mana World Development Team
- * Copyright (C) 2009-2010 The Mana Developers
- * Copyright (C) 2011-2017 The ManaPlus Developers
- *
- * This file is part of The ManaPlus Client.
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-#include "gui/windows/quitdialog.h"
-
-#include "client.h"
-#include "configuration.h"
-#include "soundmanager.h"
-
-#include "const/sound.h"
-
-#include "gui/dialogsmanager.h"
-#include "gui/viewport.h"
-
-#include "gui/widgets/containerplacer.h"
-#include "gui/widgets/button.h"
-#include "gui/widgets/radiobutton.h"
-
-#include "net/charserverhandler.h"
-#include "net/gamehandler.h"
-
-#include "resources/map/map.h"
-
-#include "utils/delete2.h"
-#include "utils/gettext.h"
-#include "utils/process.h"
-
-#include "debug.h"
-
-QuitDialog::QuitDialog(QuitDialog **const pointerToMe) :
- // TRANSLATORS: quit dialog name
- Window(_("Quit"), Modal_true, nullptr, "quit.xml"),
- ActionListener(),
- KeyListener(),
- mOptions(),
- // TRANSLATORS: quit dialog button
- mLogoutQuit(new RadioButton(this, _("Quit"), "quitdialog")),
- // TRANSLATORS: quit dialog button
- mForceQuit(new RadioButton(this, _("Quit"), "quitdialog")),
- mSwitchAccountServer(new RadioButton(this,
- // TRANSLATORS: quit dialog button
- _("Switch server"), "quitdialog")),
- mSwitchCharacter(new RadioButton(this,
- // TRANSLATORS: quit dialog button
- _("Switch character"), "quitdialog")),
- mRate(nullptr),
- // TRANSLATORS: quit dialog button
- mOkButton(new Button(this, _("OK"), "ok", this)),
- // TRANSLATORS: quit dialog button
- mCancelButton(new Button(this, _("Cancel"), "cancel", this)),
- mMyPointer(pointerToMe),
- mNeedForceQuit(false)
-{
- addKeyListener(this);
-
- ContainerPlacer placer = getPlacer(0, 0);
- const StateT state = client->getState();
- mNeedForceQuit = (state == State::CHOOSE_SERVER
- || state == State::CONNECT_SERVER || state == State::LOGIN
- || state == State::PRE_LOGIN || state == State::LOGIN_ATTEMPT
- || state == State::UPDATE || state == State::LOAD_DATA);
-
- // All states, when we're not logged in to someone.
- if (mNeedForceQuit)
- {
- placeOption(placer, mForceQuit);
- }
- else
- {
- // Only added if we are connected to an accountserver or gameserver
- placeOption(placer, mLogoutQuit);
- placeOption(placer, mSwitchAccountServer);
-
- // Only added if we are connected to a gameserver
- if (state == State::GAME)
- placeOption(placer, mSwitchCharacter);
- }
-
-/*
-#ifdef ANDROID
- if (config.getBoolValue("rated") == false
- && config.getIntValue("gamecount") > 3)
- {
- // TRANSLATORS: rate button
- mRate = new RadioButton(this, _("Rate in google play"), "quitdialog");
- placeOption(placer, mRate);
- mOptions[mOptions.size() - 1]->setSelected(true);
- }
- else
-#endif
-*/
- {
- mOptions[0]->setSelected(true);
- }
-
- placer = getPlacer(0, 1);
- placer(1, 0, mOkButton, 1);
- placer(2, 0, mCancelButton, 1);
- reflowLayout(200, 0);
-}
-
-void QuitDialog::postInit()
-{
- Window::postInit();
- setLocationRelativeTo(getParent());
- setVisible(Visible_true);
- soundManager.playGuiSound(SOUND_SHOW_WINDOW);
- requestModalFocus();
- mOkButton->requestFocus();
-}
-
-QuitDialog::~QuitDialog()
-{
- if (mMyPointer != nullptr)
- *mMyPointer = nullptr;
- delete2(mForceQuit);
- delete2(mLogoutQuit);
- delete2(mSwitchAccountServer);
- delete2(mSwitchCharacter);
-}
-
-void QuitDialog::placeOption(ContainerPlacer &placer,
- RadioButton *const option)
-{
- placer(0, CAST_S32(mOptions.size()), option, 3);
- mOptions.push_back(option);
-}
-
-void QuitDialog::action(const ActionEvent &event)
-{
- soundManager.playGuiSound(SOUND_HIDE_WINDOW);
- if (event.getId() == "ok")
- {
- if (viewport != nullptr)
- {
- const Map *const map = viewport->getMap();
- if (map != nullptr)
- map->saveExtraLayer();
- }
-
- if (mForceQuit->isSelected())
- {
- client->setState(State::FORCE_QUIT);
- }
- else if (mLogoutQuit->isSelected())
- {
- DialogsManager::closeDialogs();
- client->setState(State::EXIT);
- }
- else if ((mRate != nullptr) && mRate->isSelected())
- {
- openBrowser("https://play.google.com/store/apps/details?"
- "id=org.evolonline.beta.manaplus");
- config.setValue("rated", true);
- if (mNeedForceQuit)
- {
- client->setState(State::FORCE_QUIT);
- }
- else
- {
- DialogsManager::closeDialogs();
- client->setState(State::EXIT);
- }
- }
- else if (gameHandler->isConnected()
- && mSwitchAccountServer->isSelected())
- {
- DialogsManager::closeDialogs();
- client->setState(State::SWITCH_SERVER);
- }
- else if (mSwitchCharacter->isSelected())
- {
- if (client->getState() == State::GAME)
- {
- charServerHandler->switchCharacter();
- DialogsManager::closeDialogs();
- serverConfig.write();
- }
- }
- }
- scheduleDelete();
-}
-
-void QuitDialog::keyPressed(KeyEvent &event)
-{
- const InputActionT actionId = event.getActionId();
- int dir = 0;
-
- PRAGMA45(GCC diagnostic push)
- PRAGMA45(GCC diagnostic ignored "-Wswitch-enum")
- switch (actionId)
- {
- case InputAction::GUI_SELECT:
- case InputAction::GUI_SELECT2:
- action(ActionEvent(nullptr, mOkButton->getActionEventId()));
- break;
- case InputAction::GUI_CANCEL:
- action(ActionEvent(nullptr, mCancelButton->getActionEventId()));
- break;
- case InputAction::GUI_UP:
- dir = -1;
- break;
- case InputAction::GUI_DOWN:
- dir = 1;
- break;
- default:
- break;
- }
- PRAGMA45(GCC diagnostic pop)
-
- if (dir != 0)
- {
- STD_VECTOR<RadioButton*>::const_iterator it = mOptions.begin();
- const STD_VECTOR<RadioButton*>::const_iterator
- it_end = mOptions.end();
-
- for (; it < it_end; ++it)
- {
- if ((*it)->isSelected())
- break;
- }
-
- if (it == mOptions.end())
- {
- if (mOptions[0] != nullptr)
- mOptions[0]->setSelected(true);
- return;
- }
- else if (it == mOptions.begin() && dir < 0)
- {
- it = mOptions.end();
- }
-
- it += dir;
-
- if (it == mOptions.end())
- it = mOptions.begin();
-
- (*it)->setSelected(true);
- }
-}
diff --git a/src/gui/windows/quitdialog.h b/src/gui/windows/quitdialog.h
deleted file mode 100644
index e12e13e7b..000000000
--- a/src/gui/windows/quitdialog.h
+++ /dev/null
@@ -1,84 +0,0 @@
-/*
- * The ManaPlus Client
- * Copyright (C) 2004-2009 The Mana World Development Team
- * Copyright (C) 2009-2010 The Mana Developers
- * Copyright (C) 2011-2017 The ManaPlus Developers
- *
- * This file is part of The ManaPlus Client.
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-#ifndef GUI_WINDOWS_QUITDIALOG_H
-#define GUI_WINDOWS_QUITDIALOG_H
-
-#include "gui/widgets/window.h"
-
-#include "listeners/actionlistener.h"
-#include "listeners/keylistener.h"
-
-class Button;
-class RadioButton;
-
-/**
- * The quit dialog.
- *
- * \ingroup Interface
- */
-class QuitDialog final : public Window,
- public ActionListener,
- public KeyListener
-{
- public:
- /**
- * Constructor
- *
- * @pointerToMe will be set to NULL when the QuitDialog is destroyed
- */
- explicit QuitDialog(QuitDialog **const pointerToMe) A_NONNULL(2);
-
- A_DELETE_COPY(QuitDialog)
-
- /**
- * Destructor
- */
- ~QuitDialog();
-
- void postInit() override final;
-
- /**
- * Called when receiving actions from the widgets.
- */
- void action(const ActionEvent &event) override final;
-
- void keyPressed(KeyEvent &event) override final;
-
- private:
- void placeOption(ContainerPlacer &placer,
- RadioButton *const option);
- STD_VECTOR<RadioButton*> mOptions;
-
- RadioButton *mLogoutQuit A_NONNULLPOINTER;
- RadioButton *mForceQuit A_NONNULLPOINTER;
- RadioButton *mSwitchAccountServer A_NONNULLPOINTER;
- RadioButton *mSwitchCharacter A_NONNULLPOINTER;
- RadioButton *mRate A_NONNULLPOINTER;
- Button *mOkButton A_NONNULLPOINTER;
- Button *mCancelButton A_NONNULLPOINTER;
-
- QuitDialog **mMyPointer A_NONNULLPOINTER;
- bool mNeedForceQuit;
-};
-
-#endif // GUI_WINDOWS_QUITDIALOG_H
diff --git a/src/gui/windows/registerdialog.cpp b/src/gui/windows/registerdialog.cpp
deleted file mode 100644
index 699023d93..000000000
--- a/src/gui/windows/registerdialog.cpp
+++ /dev/null
@@ -1,317 +0,0 @@
-/*
- * The ManaPlus Client
- * Copyright (C) 2004-2009 The Mana World Development Team
- * Copyright (C) 2009-2010 The Mana Developers
- * Copyright (C) 2011-2017 The ManaPlus Developers
- *
- * This file is part of The ManaPlus Client.
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-#include "gui/windows/registerdialog.h"
-
-#include "client.h"
-#include "configuration.h"
-
-#include "being/being.h"
-
-#include "gui/windows/okdialog.h"
-
-#include "gui/widgets/button.h"
-#include "gui/widgets/containerplacer.h"
-#include "gui/widgets/createwidget.h"
-#include "gui/widgets/label.h"
-#include "gui/widgets/layoutcell.h"
-#include "gui/widgets/passwordfield.h"
-#include "gui/widgets/radiobutton.h"
-
-#include "listeners/wrongdatanoticelistener.h"
-
-#include "net/logindata.h"
-#include "net/loginhandler.h"
-#include "net/serverfeatures.h"
-
-#include "utils/delete2.h"
-#include "utils/gettext.h"
-
-#include "debug.h"
-
-RegisterDialog::RegisterDialog(LoginData &data) :
- // TRANSLATORS: register dialog name
- Window(_("Register"), Modal_false, nullptr, "register.xml"),
- ActionListener(),
- KeyListener(),
- mLoginData(&data),
- mUserField(new TextField(this, mLoginData->username)),
- mPasswordField(new PasswordField(this, mLoginData->password)),
- mConfirmField(new PasswordField(this)),
- mEmailField(nullptr),
- // TRANSLATORS: register dialog. button.
- mRegisterButton(new Button(this, _("Register"), "register", this)),
- // TRANSLATORS: register dialog. button.
- mCancelButton(new Button(this, _("Cancel"), "cancel", this)),
- mMaleButton(nullptr),
- mFemaleButton(nullptr),
- mWrongDataNoticeListener(new WrongDataNoticeListener)
-{
- setCloseButton(true);
-
- // TRANSLATORS: register dialog. label.
- Label *const userLabel = new Label(this, _("Name:"));
- // TRANSLATORS: register dialog. label.
- Label *const passwordLabel = new Label(this, _("Password:"));
- // TRANSLATORS: register dialog. label.
- Label *const confirmLabel = new Label(this, _("Confirm:"));
-
- ContainerPlacer placer;
- placer = getPlacer(0, 0);
- placer(0, 0, userLabel);
- placer(0, 1, passwordLabel);
- placer(0, 2, confirmLabel);
-
- placer(1, 0, mUserField, 3).setPadding(2);
- placer(1, 1, mPasswordField, 3).setPadding(2);
- placer(1, 2, mConfirmField, 3).setPadding(2);
-
- int row = 3;
-
- if (features.getIntValue("forceAccountGender") == -1)
- {
- // TRANSLATORS: register dialog. button.
- mMaleButton = new RadioButton(this, _("Male"), "sex", true);
- // TRANSLATORS: register dialog. button.
- mFemaleButton = new RadioButton(this, _("Female"), "sex", false);
- placer(1, row, mMaleButton);
- placer(2, row, mFemaleButton);
-
- row++;
- }
-
- if (serverFeatures->haveEmailOnRegister())
- {
- // TRANSLATORS: register dialog. label.
- Label *const emailLabel = new Label(this, _("Email:"));
- mEmailField = new TextField(this);
- placer(0, row, emailLabel);
- placer(1, row, mEmailField, 3).setPadding(2);
- mEmailField->addKeyListener(this);
- mEmailField->setActionEventId("register");
- mEmailField->addActionListener(this);
-// row++;
- }
-
- placer = getPlacer(0, 2);
- placer(1, 0, mRegisterButton);
- placer(2, 0, mCancelButton);
- reflowLayout(250, 0);
-
- mUserField->addKeyListener(this);
- mPasswordField->addKeyListener(this);
- mConfirmField->addKeyListener(this);
-
- mUserField->setActionEventId("register");
- mPasswordField->setActionEventId("register");
- mConfirmField->setActionEventId("register");
-
- mUserField->addActionListener(this);
- mPasswordField->addActionListener(this);
- mConfirmField->addActionListener(this);
-
- center();
-}
-
-void RegisterDialog::postInit()
-{
- Window::postInit();
- setVisible(Visible_true);
- mUserField->requestFocus();
- mUserField->setCaretPosition(CAST_U32(
- mUserField->getText().length()));
-
- mRegisterButton->setEnabled(canSubmit());
-}
-
-RegisterDialog::~RegisterDialog()
-{
- delete2(mWrongDataNoticeListener);
-}
-
-void RegisterDialog::action(const ActionEvent &event)
-{
- const std::string &eventId = event.getId();
- if (eventId == "cancel")
- {
- close();
- }
- else if (eventId == "register" && canSubmit())
- {
- const std::string &user = mUserField->getText();
- logger->log("RegisterDialog::register Username is %s", user.c_str());
-
- std::string errorMsg;
- int error = 0;
-
- const unsigned int minUser = loginHandler->getMinUserNameLength();
- const unsigned int maxUser = loginHandler->getMaxUserNameLength();
- const unsigned int minPass = loginHandler->getMinPasswordLength();
- const unsigned int maxPass = loginHandler->getMaxPasswordLength();
-
- if (user.length() < minUser)
- {
- // Name too short
- errorMsg = strprintf
- // TRANSLATORS: error message
- (_("The username needs to be at least %u characters long."),
- minUser);
- error = 1;
- }
- else if (user.length() > maxUser - 1)
- {
- // Name too long
- errorMsg = strprintf
- // TRANSLATORS: error message
- (_("The username needs to be less than %u characters long."),
- maxUser);
- error = 1;
- }
- else if (mPasswordField->getText().length() < minPass)
- {
- // Pass too short
- errorMsg = strprintf
- // TRANSLATORS: error message
- (_("The password needs to be at least %u characters long."),
- minPass);
- error = 2;
- }
- else if (mPasswordField->getText().length() > maxPass)
- {
- // Pass too long
- errorMsg = strprintf
- // TRANSLATORS: error message
- (_("The password needs to be less than %u characters long."),
- maxPass);
- error = 2;
- }
- else if (mPasswordField->getText() != mConfirmField->getText())
- {
- // Password does not match with the confirmation one
- // TRANSLATORS: error message
- errorMsg = _("Passwords do not match.");
- error = 2;
- }
- else if ((mEmailField != nullptr) &&
- mEmailField->getText().find('@') == std::string::npos)
- {
- // TRANSLATORS: error message
- errorMsg = _("Incorrect email.");
- error = 1;
- }
- else if (mEmailField != nullptr &&
- mEmailField->getText().size() > 40)
- {
- // TRANSLATORS: error message
- errorMsg = _("Email too long.");
- error = 1;
- }
-
- if (error > 0)
- {
- if (error == 1)
- {
- mWrongDataNoticeListener->setTarget(this->mUserField);
- }
- else if (error == 2)
- {
- // Reset password confirmation
- mPasswordField->setText("");
- mConfirmField->setText("");
- mWrongDataNoticeListener->setTarget(this->mPasswordField);
- }
-
- OkDialog *const dlg = CREATEWIDGETR(OkDialog,
- // TRANSLATORS: error message
- _("Error"), errorMsg, _("OK"),
- DialogType::ERROR,
- Modal_true,
- ShowCenter_true,
- nullptr,
- 260);
- dlg->addActionListener(mWrongDataNoticeListener);
- }
- else
- {
- // No errors detected, register the new user.
- mRegisterButton->setEnabled(false);
- mLoginData->username = mUserField->getText();
- mLoginData->password = mPasswordField->getText();
- if (features.getIntValue("forceAccountGender") == -1)
- {
- if ((mFemaleButton != nullptr) && mFemaleButton->isSelected())
- mLoginData->gender = Gender::FEMALE;
- else
- mLoginData->gender = Gender::MALE;
- }
- else
- {
- mLoginData->gender = Being::intToGender(
- CAST_U8(features.getIntValue("forceAccountGender")));
- }
-
- if (mEmailField != nullptr)
- mLoginData->email = mEmailField->getText();
- mLoginData->registerLogin = true;
-
- client->setState(State::REGISTER_ATTEMPT);
- }
- }
-}
-
-void RegisterDialog::keyPressed(KeyEvent &event)
-{
- if (event.isConsumed())
- {
- mRegisterButton->setEnabled(canSubmit());
- return;
- }
- const InputActionT actionId = event.getActionId();
- if (actionId == InputAction::GUI_CANCEL)
- {
- action(ActionEvent(nullptr, mCancelButton->getActionEventId()));
- }
- else if (actionId == InputAction::GUI_SELECT ||
- actionId == InputAction::GUI_SELECT2)
- {
- action(ActionEvent(nullptr, mRegisterButton->getActionEventId()));
- }
- else
- {
- mRegisterButton->setEnabled(canSubmit());
- }
-}
-
-bool RegisterDialog::canSubmit() const
-{
- return !mUserField->getText().empty() &&
- !mPasswordField->getText().empty() &&
- !mConfirmField->getText().empty() &&
- client->getState() == State::REGISTER &&
- ((mEmailField == nullptr) || !mEmailField->getText().empty());
-}
-
-void RegisterDialog::close()
-{
- client->setState(State::LOGIN);
- Window::close();
-}
diff --git a/src/gui/windows/registerdialog.h b/src/gui/windows/registerdialog.h
deleted file mode 100644
index d0d0d821a..000000000
--- a/src/gui/windows/registerdialog.h
+++ /dev/null
@@ -1,95 +0,0 @@
-/*
- * The ManaPlus Client
- * Copyright (C) 2004-2009 The Mana World Development Team
- * Copyright (C) 2009-2010 The Mana Developers
- * Copyright (C) 2011-2017 The ManaPlus Developers
- *
- * This file is part of The ManaPlus Client.
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-#ifndef GUI_WINDOWS_REGISTERDIALOG_H
-#define GUI_WINDOWS_REGISTERDIALOG_H
-
-#include "gui/widgets/window.h"
-
-#include "listeners/actionlistener.h"
-#include "listeners/keylistener.h"
-
-class Button;
-class LoginData;
-class RadioButton;
-class TextField;
-class WrongDataNoticeListener;
-
-/**
- * The registration dialog.
- *
- * \ingroup Interface
- */
-class RegisterDialog final : public Window,
- public ActionListener,
- public KeyListener
-{
- public:
- /**
- * Constructor. Name, password and server fields will be initialized to
- * the information already present in the LoginData instance.
- *
- * @see Window::Window
- */
- explicit RegisterDialog(LoginData &loginData);
-
- A_DELETE_COPY(RegisterDialog)
-
- /**
- * Destructor
- */
- ~RegisterDialog();
-
- void postInit() override;
-
- /**
- * Called when receiving actions from the widgets.
- */
- void action(const ActionEvent &event) override;
-
- /**
- * Called when a key is pressed in one of the text fields.
- */
- void keyPressed(KeyEvent &event) override;
-
- void close() override;
-
- private:
- /**
- * Returns whether submit can be enabled. This is true in the register
- * state, when all necessary fields have some text.
- */
- bool canSubmit() const;
-
- LoginData *mLoginData A_NONNULLPOINTER;
- TextField *mUserField A_NONNULLPOINTER;
- TextField *mPasswordField A_NONNULLPOINTER;
- TextField *mConfirmField A_NONNULLPOINTER;
- TextField *mEmailField;
- Button *mRegisterButton A_NONNULLPOINTER;
- Button *mCancelButton A_NONNULLPOINTER;
- RadioButton *mMaleButton;
- RadioButton *mFemaleButton;
- WrongDataNoticeListener *mWrongDataNoticeListener A_NONNULLPOINTER;
-};
-
-#endif // GUI_WINDOWS_REGISTERDIALOG_H
diff --git a/src/gui/windows/serverdialog.cpp b/src/gui/windows/serverdialog.cpp
deleted file mode 100644
index ab630e960..000000000
--- a/src/gui/windows/serverdialog.cpp
+++ /dev/null
@@ -1,902 +0,0 @@
-/*
- * The ManaPlus Client
- * Copyright (C) 2004-2009 The Mana World Development Team
- * Copyright (C) 2009-2010 The Mana Developers
- * Copyright (C) 2011-2017 The ManaPlus Developers
- *
- * This file is part of The ManaPlus Client.
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-#include "gui/windows/serverdialog.h"
-
-#include "chatlogger.h"
-#include "client.h"
-#include "configuration.h"
-#include "main.h"
-#include "settings.h"
-
-#include "net/download.h"
-
-#include "fs/paths.h"
-
-#include "gui/widgets/checkbox.h"
-#include "gui/widgets/createwidget.h"
-#include "gui/widgets/desktop.h"
-#include "gui/windows/editserverdialog.h"
-#include "gui/windows/logindialog.h"
-#include "gui/windows/serverinfowindow.h"
-
-#include "gui/widgets/button.h"
-#include "gui/widgets/label.h"
-#include "gui/widgets/layout.h"
-#include "gui/widgets/serverslistbox.h"
-#include "gui/widgets/scrollarea.h"
-
-#include "utils/delete2.h"
-#include "utils/foreach.h"
-#include "utils/langs.h"
-
-#include "debug.h"
-
-#ifdef WIN32
-#undef ERROR
-#endif // WIN32
-
-static const int MAX_SERVERLIST = 15;
-
-static std::string serverTypeToString(const ServerTypeT type)
-{
- switch (type)
- {
- case ServerType::TMWATHENA:
-#ifdef TMWA_SUPPORT
- return "TmwAthena";
-#else // TMWA_SUPPORT
-
- return "";
-#endif // TMWA_SUPPORT
-
- case ServerType::EATHENA:
- return "eAthena";
- case ServerType::EVOL2:
- return "Evol2";
- default:
- case ServerType::UNKNOWN:
- return "";
- }
-}
-
-static uint16_t defaultPortForServerType(const ServerTypeT type)
-{
- switch (type)
- {
- default:
- case ServerType::EATHENA:
- case ServerType::EVOL2:
- return 6900;
- case ServerType::UNKNOWN:
- case ServerType::TMWATHENA:
- return 6901;
- }
-}
-
-ServerDialog::ServerDialog(ServerInfo *const serverInfo,
- const std::string &dir) :
- // TRANSLATORS: servers dialog name
- Window(_("Choose Your Server"), Modal_false, nullptr, "server.xml"),
- ActionListener(),
- KeyListener(),
- SelectionListener(),
- mMutex(),
- mServers(ServerInfos()),
- mDir(dir),
- mDescription(new Label(this, std::string())),
- // TRANSLATORS: servers dialog button
- mQuitButton(new Button(this, _("Quit"), "quit", this)),
- // TRANSLATORS: servers dialog button
- mConnectButton(new Button(this, _("Connect"), "connect", this)),
- // TRANSLATORS: servers dialog button
- mAddEntryButton(new Button(this, _("Add"), "addEntry", this)),
- // TRANSLATORS: servers dialog button
- mEditEntryButton(new Button(this, _("Edit"), "editEntry", this)),
- // TRANSLATORS: servers dialog button
- mDeleteButton(new Button(this, _("Delete"), "remove", this)),
- // TRANSLATORS: servers dialog button
- mLoadButton(new Button(this, _("Load"), "load", this)),
- // TRANSLATORS: servers dialog button
- mInfoButton(new Button(this, _("Info"), "info", this)),
- mServersListModel(new ServersListModel(&mServers, this)),
- mServersList(CREATEWIDGETR(ServersListBox, this, mServersListModel)),
- mDownload(nullptr),
- mServerInfo(serverInfo),
- mPersistentIPCheckBox(nullptr),
- mDownloadProgress(-1.0F),
- mDownloadStatus(ServerDialogDownloadStatus::UNKNOWN)
-{
- if (isSafeMode)
- {
- // TRANSLATORS: servers dialog name
- setCaption(_("Choose Your Server *** SAFE MODE ***"));
- }
-
- setWindowName("ServerDialog");
-
- setCloseButton(true);
-
- mPersistentIPCheckBox = new CheckBox(this,
- // TRANSLATORS: servers dialog checkbox
- _("Use same ip for game sub servers"),
- config.getBoolValue("usePersistentIP"),
- this, "persitent ip");
-
- loadCustomServers();
-
- mServersList->addMouseListener(this);
-
- ScrollArea *const usedScroll = new ScrollArea(this, mServersList,
- fromBool(getOptionBool("showbackground"), Opaque),
- "server_background.xml");
- usedScroll->setHorizontalScrollPolicy(ScrollArea::SHOW_NEVER);
-
- mServersList->addSelectionListener(this);
- usedScroll->setVerticalScrollAmount(0);
-
- place(0, 0, usedScroll, 8, 5).setPadding(3);
- place(0, 5, mDescription, 8);
- place(0, 6, mPersistentIPCheckBox, 8);
- place(0, 7, mInfoButton);
- place(1, 7, mAddEntryButton);
- place(2, 7, mEditEntryButton);
- place(3, 7, mLoadButton);
- place(4, 7, mDeleteButton);
- place(6, 7, mQuitButton);
- place(7, 7, mConnectButton);
-
- // Make sure the list has enough height
- getLayout().setRowHeight(0, 80);
-
- // Do this manually instead of calling reflowLayout so we can enforce a
- // minimum width.
- int width = 500;
- int height = 350;
-
- getLayout().reflow(width, height);
- setContentSize(width, height);
-
- setMinWidth(310);
- setMinHeight(220);
- setDefaultSize(getWidth(), getHeight(), ImagePosition::CENTER);
-
- setResizable(true);
- addKeyListener(this);
-
- loadWindowState();
-}
-
-void ServerDialog::postInit()
-{
- Window::postInit();
- setVisible(Visible_true);
-
- mConnectButton->requestFocus();
-
- loadServers(true);
-
- mServersList->setSelected(0); // Do this after for the Delete button
-
- if (needUpdateServers())
- downloadServerList();
- else
- logger->log("Skipping servers list update");
-}
-
-ServerDialog::~ServerDialog()
-{
- if (mDownload != nullptr)
- {
- mDownload->cancel();
- delete2(mDownload)
- }
- delete2(mServersListModel);
-}
-
-void ServerDialog::connectToSelectedServer()
-{
- if (client->getState() == State::CONNECT_SERVER)
- return;
-
- const int index = mServersList->getSelected();
- if (index < 0)
- return;
-
- if (mDownload != nullptr)
- mDownload->cancel();
-
- mQuitButton->setEnabled(false);
- mConnectButton->setEnabled(false);
- mLoadButton->setEnabled(false);
-
- ServerInfo server = mServers.at(index);
- mServerInfo->hostname = server.hostname;
- mServerInfo->althostname = server.althostname;
- mServerInfo->port = server.port;
- mServerInfo->type = server.type;
- mServerInfo->name = server.name;
- mServerInfo->description = server.description;
- mServerInfo->registerUrl = server.registerUrl;
- mServerInfo->onlineListUrl = server.onlineListUrl;
- mServerInfo->supportUrl = server.supportUrl;
- mServerInfo->defaultHostName = server.defaultHostName;
- mServerInfo->save = true;
- mServerInfo->persistentIp = server.persistentIp;
- mServerInfo->freeType = server.freeType;
- mServerInfo->updateMirrors = server.updateMirrors;
- mServerInfo->packetVersion = server.packetVersion;
- mServerInfo->updateHosts = server.updateHosts;
- mServerInfo->freeSources = server.freeSources;
- mServerInfo->nonFreeSources = server.nonFreeSources;
- mServerInfo->docs = server.docs;
- mServerInfo->serverUrl = server.serverUrl;
-
- settings.persistentIp = mServerInfo->persistentIp;
- settings.supportUrl = mServerInfo->supportUrl;
- settings.updateMirrors = mServerInfo->updateMirrors;
-
- if (chatLogger != nullptr)
- chatLogger->setServerName(mServerInfo->hostname);
-
- saveCustomServers(*mServerInfo);
-
- if (!LoginDialog::savedPasswordKey.empty())
- {
- if (mServerInfo->hostname != LoginDialog::savedPasswordKey)
- {
- LoginDialog::savedPassword.clear();
- if (desktop != nullptr)
- desktop->reloadWallpaper();
- }
- }
-
- config.setValue("usePersistentIP",
- mPersistentIPCheckBox->isSelected());
- client->setState(State::CONNECT_SERVER);
-}
-
-void ServerDialog::action(const ActionEvent &event)
-{
- const std::string &eventId = event.getId();
- if (eventId == "connect")
- {
- connectToSelectedServer();
- }
- else if (eventId == "quit")
- {
- close();
- }
- else if (eventId == "load")
- {
- downloadServerList();
- }
- else if (eventId == "addEntry")
- {
- CREATEWIDGET(EditServerDialog, this, ServerInfo(), -1);
- }
- else if (eventId == "editEntry")
- {
- const int index = mServersList->getSelected();
- if (index >= 0)
- {
- CREATEWIDGET(EditServerDialog,
- this,
- mServers.at(index),
- index);
- }
- }
- else if (eventId == "remove")
- {
- const int index = mServersList->getSelected();
- if (index >= 0)
- {
- mServersList->setSelected(0);
- mServers.erase(mServers.begin() + index);
- saveCustomServers();
- }
- }
- else if (eventId == "info")
- {
- const int index = mServersList->getSelected();
- if (index >= 0)
- {
- if (serverInfoWindow != nullptr)
- serverInfoWindow->scheduleDelete();
- serverInfoWindow = CREATEWIDGETR(ServerInfoWindow,
- mServers.at(index));
- }
- }
-}
-
-void ServerDialog::keyPressed(KeyEvent &event)
-{
- PRAGMA45(GCC diagnostic push)
- PRAGMA45(GCC diagnostic ignored "-Wswitch-enum")
- switch (event.getActionId())
- {
- case InputAction::GUI_CANCEL:
- event.consume();
- client->setState(State::EXIT);
- return;
-
- case InputAction::GUI_SELECT:
- case InputAction::GUI_SELECT2:
- event.consume();
- action(ActionEvent(nullptr,
- mConnectButton->getActionEventId()));
- return;
-
- case InputAction::GUI_INSERT:
- CREATEWIDGET(EditServerDialog, this, ServerInfo(), -1);
- return;
-
- case InputAction::GUI_DELETE:
- {
- const int index = mServersList->getSelected();
- if (index >= 0)
- {
- mServersList->setSelected(0);
- mServers.erase(mServers.begin() + index);
- saveCustomServers();
- }
- return;
- }
-
- case InputAction::GUI_BACKSPACE:
- {
- const int index = mServersList->getSelected();
- if (index >= 0)
- {
- CREATEWIDGET(EditServerDialog, this, mServers.at(index),
- index);
- }
- return;
- }
-
- default:
- break;
- }
- PRAGMA45(GCC diagnostic pop)
- if (!event.isConsumed())
- mServersList->keyPressed(event);
-}
-
-void ServerDialog::valueChanged(const SelectionEvent &event A_UNUSED)
-{
- const int index = mServersList->getSelected();
- if (index == -1)
- {
- mDeleteButton->setEnabled(false);
- return;
- }
- mDeleteButton->setEnabled(true);
-}
-
-void ServerDialog::mouseClicked(MouseEvent &event)
-{
- if (event.getButton() == MouseButton::LEFT)
- {
- event.consume();
- if (event.getClickCount() == 2 &&
- event.getSource() == mServersList)
- {
- action(ActionEvent(mConnectButton,
- mConnectButton->getActionEventId()));
- }
- }
-}
-
-void ServerDialog::logic()
-{
- BLOCK_START("ServerDialog::logic")
- {
- MutexLocker tempLock(&mMutex);
- if (mDownloadStatus == ServerDialogDownloadStatus::COMPLETE)
- {
- loadServers();
- mDownloadStatus = ServerDialogDownloadStatus::OVER;
- mDescription->setCaption(std::string());
- logger->log("Servers list updated");
- }
- else if (mDownloadStatus == ServerDialogDownloadStatus::IN_PROGRESS)
- {
- // TRANSLATORS: servers dialog label
- mDescription->setCaption(strprintf(_("Downloading server list..."
- "%2.2f%%"), static_cast<double>(mDownloadProgress * 100)));
- }
- else if (mDownloadStatus == ServerDialogDownloadStatus::IDLE)
- {
- // TRANSLATORS: servers dialog label
- mDescription->setCaption(_("Waiting for server..."));
- }
- else if (mDownloadStatus == ServerDialogDownloadStatus::PREPARING)
- {
- // TRANSLATORS: servers dialog label
- mDescription->setCaption(_("Preparing download"));
- }
- else if (mDownloadStatus == ServerDialogDownloadStatus::ERROR)
- {
- // TRANSLATORS: servers dialog label
- mDescription->setCaption(_("Error retreiving server list!"));
- logger->log("Error: servers list updating error");
- }
- }
-
- Window::logic();
- BLOCK_END("ServerDialog::logic")
-}
-
-void ServerDialog::downloadServerList()
-{
- // Try to load the configuration value for the onlineServerList
- std::string listFile = branding.getStringValue("onlineServerList");
- std::string listFile2 = branding.getStringValue("onlineServerList2");
-
- // Fall back to manaplus.org when neither branding
- // nor config set it
- if (listFile.empty())
- listFile = "http://manaplus.org/serverlist.xml";
-
- if (mDownload != nullptr)
- {
- mDownload->cancel();
- delete2(mDownload)
- }
-
- mDownload = new Net::Download(this, listFile,
- &downloadUpdate, false, false, true);
- mDownload->setFile(pathJoin(mDir,
- branding.getStringValue("onlineServerFile")));
- if (!listFile2.empty())
- mDownload->addMirror(listFile2);
- mDownload->start();
-
- config.setValue("serverslistupdate", getDateString());
-}
-
-static void loadHostsGroup(XmlNodeConstPtr node,
- ServerInfo &server)
-{
- HostsGroup group;
- group.name = XML::langProperty(node,
- "name",
- // TRANSLATORS: unknown hosts group name
- _("Unknown"));
- for_each_xml_child_node(hostNode, node)
- {
- if (!xmlNameEqual(hostNode, "host") ||
- !XmlHaveChildContent(hostNode))
- {
- continue;
- }
- const std::string host = XmlChildContent(hostNode);
- if (host.empty())
- continue;
- if (!checkPath(host))
- {
- logger->log1("Warning: incorrect update server name");
- continue;
- }
-
- group.hosts.push_back(host);
- }
- if (!group.hosts.empty())
- server.updateHosts.push_back(group);
-}
-
-static void loadServerSourcesList(XmlNodeConstPtr node,
- STD_VECTOR<ServerUrlInfo> &list)
-{
- for_each_xml_child_node(urlNode, node)
- {
- if (!xmlNameEqual(urlNode, "url") ||
- !XmlHaveChildContent(urlNode))
- {
- continue;
- }
- const std::string name = XML::langProperty(urlNode,
- "name",
- "");
- if (name.empty())
- continue;
- const std::string url = XmlChildContent(urlNode);
- if (url.empty())
- continue;
- list.push_back(ServerUrlInfo(name, url));
- }
-}
-
-static void loadServerSources(XmlNodeConstPtr node,
- ServerInfo &server)
-{
- for_each_xml_child_node(subNode, node)
- {
- if (xmlNameEqual(subNode, "free"))
- {
- loadServerSourcesList(subNode, server.freeSources);
- }
- else if (xmlNameEqual(subNode, "nonfree"))
- {
- loadServerSourcesList(subNode, server.nonFreeSources);
- }
- }
-}
-
-void ServerDialog::loadServers(const bool addNew)
-{
- XML::Document doc(pathJoin(mDir,
- branding.getStringValue("onlineServerFile")),
- UseVirtFs_false,
- SkipError_true);
- XmlNodeConstPtr rootNode = doc.rootNode();
-
- if (rootNode == nullptr ||
- !xmlNameEqual(rootNode, "serverlist"))
- {
- logger->log1("Error loading server list!");
- return;
- }
-
- const int ver = XML::getProperty(rootNode, "version", 0);
- if (ver != 1)
- {
- logger->log("Error: unsupported online server list version: %d",
- ver);
- return;
- }
-
- const std::string lang = getLangShort();
- const std::string description2("description_" + lang);
-
- for_each_xml_child_node(serverNode, rootNode)
- {
- if (!xmlNameEqual(serverNode, "server"))
- continue;
-
- const std::string type = XML::getProperty(
- serverNode, "type", "unknown");
- ServerInfo server;
- server.type = ServerInfo::parseType(type);
- const std::string licenseType = XML::getProperty(
- serverNode, "licenseType", "notset");
- server.freeType = ServerInfo::parseFreeType(licenseType);
-
- // Ignore unknown server types
- if (server.type == ServerType::UNKNOWN)
- {
- logger->log("Ignoring server entry with unknown type: %s",
- type.c_str());
- continue;
- }
-
- server.name = XML::getProperty(serverNode, "name", std::string());
- std::string version = XML::getProperty(serverNode, "minimumVersion",
- std::string());
-
- const bool meetsMinimumVersion = (compareStrI(version, SMALL_VERSION)
- <= 0);
-
- // For display in the list
- if (meetsMinimumVersion)
- version.clear();
- else if (version.empty())
- {
- // TRANSLATORS: servers dialog label
- version = _("requires a newer version");
- }
- else
- {
- // TRANSLATORS: servers dialog label
- version = strprintf(_("requires v%s"), version.c_str());
- }
-
- const Font *const font = gui->getFont();
-
- for_each_xml_child_node(subNode, serverNode)
- {
- if (xmlNameEqual(subNode, "connection"))
- {
- server.hostname = XML::getProperty(subNode, "hostname", "");
- server.althostname = XML::getProperty(
- subNode, "althostname", "");
- server.port = CAST_U16(
- XML::getProperty(subNode, "port", 0));
- server.packetVersion = XML::getProperty(subNode,
- "packetVersion", 0);
-
- if (server.port == 0)
- {
- // If no port is given, use the default for the given type
- server.port = defaultPortForServerType(server.type);
- }
- }
- else if (XmlHaveChildContent(subNode))
- {
- if ((xmlNameEqual(subNode, "description")
- && server.description.empty()) || (!lang.empty()
- && xmlNameEqual(subNode, description2.c_str())))
- {
- server.description = XmlChildContent(subNode);
- }
- else if (xmlNameEqual(subNode, "registerurl"))
- {
- server.registerUrl = XmlChildContent(subNode);
- }
- else if (xmlNameEqual(subNode, "onlineListUrl"))
- {
- server.onlineListUrl = XmlChildContent(subNode);
- }
- else if (xmlNameEqual(subNode, "support"))
- {
- server.supportUrl = XmlChildContent(subNode);
- }
- else if (xmlNameEqual(subNode, "persistentIp"))
- {
- std::string text = XmlChildContent(subNode);
- server.persistentIp = (text == "1" || text == "true");
- }
- else if (xmlNameEqual(subNode, "updateMirror"))
- {
- server.updateMirrors.push_back(XmlChildContent(subNode));
- }
- else if (xmlNameEqual(subNode, "site"))
- {
- server.serverUrl = XmlChildContent(subNode);
- }
- }
- if (xmlNameEqual(subNode, "updates"))
- {
- loadHostsGroup(subNode, server);
- }
- else if (xmlNameEqual(subNode, "defaultUpdateHost"))
- {
- server.defaultHostName = XML::langProperty(
- // TRANSLATORS: default hosts group name
- subNode, "name", _("default"));
- }
- else if (xmlNameEqual(subNode, "sources"))
- {
- loadServerSources(subNode, server);
- }
- else if (xmlNameEqual(subNode, "docs"))
- {
- loadServerSourcesList(subNode, server.docs);
- }
- }
-
- server.version.first = font->getWidth(version);
- server.version.second = version;
-
- MutexLocker tempLock(&mMutex);
- // Add the server to the local list if it's not already present
- bool found = false;
- for (unsigned int i = 0, fsz = CAST_U32(
- mServers.size()); i < fsz; i++)
- {
- if (mServers[i] == server)
- {
- // Use the name listed in the server list
- mServers[i].name = server.name;
- mServers[i].type = server.type;
- mServers[i].freeType = server.freeType;
- mServers[i].version = server.version;
- mServers[i].description = server.description;
- mServers[i].registerUrl = server.registerUrl;
- mServers[i].onlineListUrl = server.onlineListUrl;
- mServers[i].supportUrl = server.supportUrl;
- mServers[i].serverUrl = server.serverUrl;
- mServers[i].althostname = server.althostname;
- mServers[i].persistentIp = server.persistentIp;
- mServers[i].updateMirrors = server.updateMirrors;
- mServers[i].defaultHostName = server.defaultHostName;
- mServers[i].updateHosts = server.updateHosts;
- mServers[i].packetVersion = server.packetVersion;
- mServers[i].freeSources = server.freeSources;
- mServers[i].nonFreeSources = server.nonFreeSources;
- mServers[i].docs = server.docs;
- mServersListModel->setVersionString(i, version);
- found = true;
- break;
- }
- }
- if (!found && addNew)
- mServers.push_back(server);
- }
- if (mServersList->getSelected() < 0)
- mServersList->setSelected(0);
-}
-
-void ServerDialog::loadCustomServers()
-{
- for (int i = 0; i < MAX_SERVERLIST; ++i)
- {
- const std::string index = toString(i);
- const std::string nameKey("MostUsedServerDescName" + index);
- const std::string descKey("MostUsedServerDescription" + index);
- const std::string hostKey("MostUsedServerName" + index);
- const std::string typeKey("MostUsedServerType" + index);
- const std::string portKey("MostUsedServerPort" + index);
- const std::string onlineListUrlKey
- ("MostUsedServerOnlineList" + index);
- const std::string persistentIpKey("persistentIp" + index);
- const std::string packetVersionKey
- ("MostUsedServerPacketVersion" + index);
-
- ServerInfo server;
- server.name = config.getValue(nameKey, "");
- server.description = config.getValue(descKey, "");
- server.onlineListUrl = config.getValue(onlineListUrlKey, "");
- server.hostname = config.getValue(hostKey, "");
- server.type = ServerInfo::parseType(config.getValue(typeKey, ""));
- server.persistentIp = config.getValue(
- persistentIpKey, 0) != 0 ? true : false;
- server.packetVersion = config.getValue(packetVersionKey, 0);
-
- const int defaultPort = defaultPortForServerType(server.type);
- server.port = CAST_U16(
- config.getValue(portKey, defaultPort));
-
- // skip invalid server
- if (!server.isValid())
- continue;
-
- server.save = true;
- mServers.push_back(server);
- }
-}
-
-void ServerDialog::saveCustomServers(const ServerInfo &currentServer,
- const int index)
-{
- // Make sure the current server is mentioned first
- if (currentServer.isValid())
- {
- if (index >= 0 && CAST_SIZE(index) < mServers.size())
- {
- mServers[index] = currentServer;
- }
- else
- {
- FOR_EACH (ServerInfos::iterator, i, mServers)
- {
- if (*i == currentServer)
- {
- mServers.erase(i);
- break;
- }
- }
- mServers.insert(mServers.begin(), currentServer);
- }
- }
-
- int savedServerCount = 0;
-
- for (unsigned i = 0, fsz = CAST_U32(mServers.size());
- i < fsz && savedServerCount < MAX_SERVERLIST; ++ i)
- {
- const ServerInfo &server = mServers.at(i);
-
- // Only save servers that were loaded from settings
- if (!(server.save && server.isValid()))
- continue;
-
- const std::string num = toString(savedServerCount);
- const std::string nameKey("MostUsedServerDescName" + num);
- const std::string descKey("MostUsedServerDescription" + num);
- const std::string hostKey("MostUsedServerName" + num);
- const std::string typeKey("MostUsedServerType" + num);
- const std::string portKey("MostUsedServerPort" + num);
- const std::string onlineListUrlKey
- ("MostUsedServerOnlineList" + num);
- const std::string persistentIpKey("persistentIp" + num);
- const std::string packetVersionKey
- ("MostUsedServerPacketVersion" + num);
-
- config.setValue(nameKey, server.name);
- config.setValue(descKey, server.description);
- config.setValue(onlineListUrlKey, server.onlineListUrl);
- config.setValue(hostKey, server.hostname);
- config.setValue(typeKey, serverTypeToString(server.type));
- config.setValue(portKey, toString(server.port));
- config.setValue(persistentIpKey, server.persistentIp);
- config.setValue(packetVersionKey, server.packetVersion);
- ++ savedServerCount;
- }
-
- // Insert an invalid entry at the end to make the loading stop there
- if (savedServerCount < MAX_SERVERLIST)
- config.setValue("MostUsedServerName" + toString(savedServerCount), "");
-}
-
-int ServerDialog::downloadUpdate(void *ptr,
- const DownloadStatusT status,
- size_t total,
- const size_t remaining)
-{
- if ((ptr == nullptr) || status == DownloadStatus::Cancelled)
- return -1;
-
- ServerDialog *const sd = reinterpret_cast<ServerDialog*>(ptr);
- bool finished = false;
-
- if (sd->mDownload == nullptr)
- return -1;
-
- if (status == DownloadStatus::Complete)
- {
- finished = true;
- }
- else if (CAST_S32(status) < 0)
- {
- logger->log("Error retreiving server list: %s\n",
- sd->mDownload->getError());
- sd->mDownloadStatus = ServerDialogDownloadStatus::ERROR;
- }
- else
- {
- float progress = static_cast<float>(remaining);
- if (total != 0u)
- progress /= static_cast<float>(total);
-
- if (progress != progress || progress < 0.0F)
- progress = 0.0f;
- else if (progress > 1.0F)
- progress = 1.0F;
-
- MutexLocker lock1(&sd->mMutex);
- sd->mDownloadStatus = ServerDialogDownloadStatus::IN_PROGRESS;
- sd->mDownloadProgress = progress;
- }
-
- if (finished)
- {
- MutexLocker lock1(&sd->mMutex);
- sd->mDownloadStatus = ServerDialogDownloadStatus::COMPLETE;
- }
-
- return 0;
-}
-
-void ServerDialog::updateServer(const ServerInfo &server, const int index)
-{
- saveCustomServers(server, index);
-}
-
-bool ServerDialog::needUpdateServers() const
-{
- if (mServers.empty() || config.getStringValue("serverslistupdate")
- != getDateString())
- {
- return true;
- }
-
- return false;
-}
-
-void ServerDialog::close()
-{
- if (mDownload != nullptr)
- mDownload->cancel();
- client->setState(State::FORCE_QUIT);
- Window::close();
-}
diff --git a/src/gui/windows/serverdialog.h b/src/gui/windows/serverdialog.h
deleted file mode 100644
index b541e7f65..000000000
--- a/src/gui/windows/serverdialog.h
+++ /dev/null
@@ -1,150 +0,0 @@
-/*
- * The ManaPlus Client
- * Copyright (C) 2004-2009 The Mana World Development Team
- * Copyright (C) 2009-2010 The Mana Developers
- * Copyright (C) 2011-2017 The ManaPlus Developers
- *
- * This file is part of The ManaPlus Client.
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-#ifndef GUI_WINDOWS_SERVERDIALOG_H
-#define GUI_WINDOWS_SERVERDIALOG_H
-
-#include "gui/widgets/window.h"
-
-#include "enums/gui/serverdialogdonwloadstatus.h"
-
-#include "enums/net/downloadstatus.h"
-
-#include "net/serverinfo.h"
-
-#include "utils/mutex.h"
-
-#include "listeners/actionlistener.h"
-#include "listeners/keylistener.h"
-#include "listeners/selectionlistener.h"
-
-class Button;
-class CheckBox;
-class Label;
-class ListBox;
-class ServersListModel;
-
-namespace Net
-{
- class Download;
-} // namespace Net
-
-/**
- * The server choice dialog.
- *
- * \ingroup Interface
- */
-class ServerDialog final : public Window,
- public ActionListener,
- public KeyListener,
- public SelectionListener
-{
- public:
- /**
- * Constructor
- *
- * @see Window::Window
- */
- ServerDialog(ServerInfo *const serverInfo, const std::string &dir);
-
- A_DELETE_COPY(ServerDialog)
-
- void postInit() override final;
-
- /**
- * Destructor
- */
- ~ServerDialog();
-
- /**
- * Called when receiving actions from the widgets.
- */
- void action(const ActionEvent &event) override final;
-
- void keyPressed(KeyEvent &event) override final;
-
- /**
- * Called when the selected value changed in the servers list box.
- */
- void valueChanged(const SelectionEvent &event) override final;
-
- void mouseClicked(MouseEvent &event) override final;
-
- void logic() override final;
-
- void updateServer(const ServerInfo &server, const int index);
-
- void connectToSelectedServer();
-
- void close() override final;
-
- protected:
- friend class ServersListModel;
-
- MutexLocker lock()
- { return MutexLocker(&mMutex); }
-
- private:
- friend class EditServerDialog;
-
- /**
- * Called to load a list of available server from an online xml file.
- */
- void downloadServerList();
-
- void loadServers(const bool addNew = true);
-
- void loadCustomServers();
-
- void saveCustomServers(const ServerInfo &currentServer = ServerInfo(),
- const int index = -1);
-
- bool needUpdateServers() const;
-
- static int downloadUpdate(void *ptr,
- const DownloadStatusT status,
- size_t total,
- const size_t remaining);
-
- Mutex mMutex;
- ServerInfos mServers;
- const std::string &mDir;
- Label *mDescription A_NONNULLPOINTER;
- Button *mQuitButton A_NONNULLPOINTER;
- Button *mConnectButton A_NONNULLPOINTER;
- Button *mAddEntryButton A_NONNULLPOINTER;
- Button *mEditEntryButton A_NONNULLPOINTER;
- Button *mDeleteButton A_NONNULLPOINTER;
- Button *mLoadButton A_NONNULLPOINTER;
- Button *mInfoButton A_NONNULLPOINTER;
- ServersListModel *mServersListModel A_NONNULLPOINTER;
- ListBox *mServersList A_NONNULLPOINTER;
-
- /** Status of the current download. */
- Net::Download *mDownload;
- ServerInfo *mServerInfo;
- CheckBox *mPersistentIPCheckBox;
- float mDownloadProgress;
- ServerDialogDownloadStatusT mDownloadStatus;
-};
-
-#endif // GUI_WINDOWS_SERVERDIALOG_H
diff --git a/src/gui/windows/serverinfowindow.cpp b/src/gui/windows/serverinfowindow.cpp
deleted file mode 100644
index 20f8d5f42..000000000
--- a/src/gui/windows/serverinfowindow.cpp
+++ /dev/null
@@ -1,184 +0,0 @@
-/*
- * The ManaPlus Client
- * Copyright (C) 2017 The ManaPlus Developers
- *
- * This file is part of The ManaPlus Client.
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-#include "gui/windows/serverinfowindow.h"
-
-#include "enums/gui/layouttype.h"
-
-#include "gui/gui.h"
-
-#include "gui/widgets/layout.h"
-#include "gui/widgets/scrollarea.h"
-#include "gui/widgets/staticbrowserbox.h"
-
-#include "utils/foreach.h"
-#include "utils/gettext.h"
-#include "utils/process.h"
-
-#include "debug.h"
-
-ServerInfoWindow *serverInfoWindow = nullptr;
-
-ServerInfoWindow::ServerInfoWindow(ServerInfo &serverInfo) :
- // TRANSLATORS: servers dialog name
- Window(_("Server info"), Modal_false, nullptr, "serverinfo.xml"),
- LinkHandler(),
- mServerInfo(serverInfo),
- mBrowserBox(new StaticBrowserBox(this, Opaque_true,
- "browserbox.xml")),
- mScrollArea(new ScrollArea(this, mBrowserBox,
- Opaque_true, "serverinfo_background.xml"))
-{
- setMinWidth(300);
- setMinHeight(220);
- setContentSize(455, 350);
- setWindowName("ServerInfoWindow");
- setCloseButton(true);
- setResizable(true);
- setStickyButtonLock(true);
-
- setDefaultSize(500, 400, ImagePosition::CENTER);
-
- mBrowserBox->setOpaque(Opaque_false);
- mBrowserBox->setLinkHandler(this);
- if (gui != nullptr)
- mBrowserBox->setFont(gui->getHelpFont());
- mBrowserBox->setProcessVars(true);
- mBrowserBox->setEnableTabs(true);
-
- place(0, 0, mScrollArea, 5, 3).setPadding(3);
-
- Layout &layout = getLayout();
- layout.setRowHeight(0, LayoutType::SET);
-
- loadWindowState();
- enableVisibleSound(true);
- widgetResized(Event(nullptr));
-}
-
-void ServerInfoWindow::postInit()
-{
- Window::postInit();
- setVisible(Visible_true);
- showServerInfo();
-}
-
-ServerInfoWindow::~ServerInfoWindow()
-{
-}
-
-void ServerInfoWindow::handleLink(const std::string &link,
- MouseEvent *const event A_UNUSED)
-{
- if (strStartWith(link, "http://") ||
- strStartWith(link, "https://"))
- {
- openBrowser(link);
- }
-}
-
-void ServerInfoWindow::showServerInfo()
-{
- const ServerFreeTypeT type = mServerInfo.freeType;
- if (type == ServerFreeType::Free)
- {
- // TRANSLATORS: server info comment
- mBrowserBox->addRow(_("##BServer with free license."));
- }
- else if (type == ServerFreeType::NonFree)
- {
- // TRANSLATORS: server info comment
- mBrowserBox->addRow(_("##BServer with non free license."));
- }
- else if (type == ServerFreeType::Unknown ||
- type == ServerFreeType::NotSet)
- {
- // TRANSLATORS: server info comment
- mBrowserBox->addRow(_("##BServer unknown license."));
- }
- mBrowserBox->addRow("");
- addServerComment(mServerInfo.serverUrl,
- // TRANSLATORS: server info comment
- _("Server"));
- addServerComment(mServerInfo.supportUrl,
- // TRANSLATORS: server info comment
- _("Support"));
- addServerComment(mServerInfo.registerUrl,
- // TRANSLATORS: server info comment
- _("Register"));
-
- addSourcesList(mServerInfo.nonFreeSources,
- // TRANSLATORS: server info non free comment
- _("##BNon free sources"));
- addSourcesList(mServerInfo.freeSources,
- // TRANSLATORS: server info non free comment
- _("##BFree sources"));
- addSourcesList(mServerInfo.docs,
- // TRANSLATORS: server info documentation comment
- _("##BDocumentation"));
- mBrowserBox->updateHeight();
-}
-
-void ServerInfoWindow::addSourcesList(const STD_VECTOR<ServerUrlInfo> &list,
- const std::string &comment)
-{
- if (!list.empty())
- {
- mBrowserBox->addRow("");
- mBrowserBox->addRow(comment);
- FOR_EACH (STD_VECTOR<ServerUrlInfo>::const_iterator, it, list)
- {
- const ServerUrlInfo &info = *it;
- addServerComment(info.url,
- info.name);
- }
- }
-}
-
-void ServerInfoWindow::addServerComment(const std::string &url,
- const std::string &comment)
-{
- std::string str;
- if (!url.empty())
- {
- if (strStartWith(url, "http://") ||
- strStartWith(url, "https://"))
- {
- str = strprintf("%s: @@%s|@@##0",
- comment.c_str(),
- url.c_str());
- }
- else
- {
- str = strprintf("%s: %s",
- comment.c_str(),
- url.c_str());
- }
- mBrowserBox->addRow(str);
- }
-}
-
-void ServerInfoWindow::close()
-{
- Window::close();
- if (serverInfoWindow == this)
- serverInfoWindow = nullptr;
- scheduleDelete();
-}
diff --git a/src/gui/windows/serverinfowindow.h b/src/gui/windows/serverinfowindow.h
deleted file mode 100644
index d872b1fdf..000000000
--- a/src/gui/windows/serverinfowindow.h
+++ /dev/null
@@ -1,68 +0,0 @@
-/*
- * The ManaPlus Client
- * Copyright (C) 2017 The ManaPlus Developers
- *
- * This file is part of The ManaPlus Client.
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-#ifndef GUI_WINDOWS_SERVERINFOWINDOW_H
-#define GUI_WINDOWS_SERVERINFOWINDOW_H
-
-#include "gui/widgets/window.h"
-
-#include "gui/widgets/linkhandler.h"
-
-#include "net/serverinfo.h"
-
-class ScrollArea;
-class ServerInfo;
-class StaticBrowserBox;
-
-class ServerInfoWindow final : public Window,
- public LinkHandler
-{
- public:
- explicit ServerInfoWindow(ServerInfo &serverInfo);
-
- A_DELETE_COPY(ServerInfoWindow)
-
- void postInit() override final;
-
- ~ServerInfoWindow();
-
- void handleLink(const std::string &link,
- MouseEvent *const event A_UNUSED) override final;
-
- void close() override final;
-
- protected:
- void showServerInfo();
-
- void addSourcesList(const STD_VECTOR<ServerUrlInfo> &list,
- const std::string &comment);
-
- void addServerComment(const std::string &url,
- const std::string &comment);
-
- private:
- ServerInfo mServerInfo;
- StaticBrowserBox *mBrowserBox A_NONNULLPOINTER;
- ScrollArea *mScrollArea A_NONNULLPOINTER;
-};
-
-extern ServerInfoWindow *serverInfoWindow;
-
-#endif // GUI_WINDOWS_SERVERINFOWINDOW_H
diff --git a/src/gui/windows/setupwindow.cpp b/src/gui/windows/setupwindow.cpp
deleted file mode 100644
index eeb86ce7d..000000000
--- a/src/gui/windows/setupwindow.cpp
+++ /dev/null
@@ -1,335 +0,0 @@
-/*
- * The ManaPlus Client
- * Copyright (C) 2004-2009 The Mana World Development Team
- * Copyright (C) 2009-2010 The Mana Developers
- * Copyright (C) 2011-2017 The ManaPlus Developers
- *
- * This file is part of The ManaPlus Client.
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-#include "gui/windows/setupwindow.h"
-
-#include "configuration.h"
-#include "game.h"
-#include "main.h"
-
-#include "gui/windows/chatwindow.h"
-#include "gui/windows/statuswindow.h"
-
-#include "gui/widgets/createwidget.h"
-
-#include "gui/widgets/tabs/setup_audio.h"
-#include "gui/widgets/tabs/setup_chat.h"
-#include "gui/widgets/tabs/setup_colors.h"
-#include "gui/widgets/tabs/setup_input.h"
-#include "gui/widgets/tabs/setup_joystick.h"
-#include "gui/widgets/tabs/setup_misc.h"
-#include "gui/widgets/tabs/setup_mods.h"
-#include "gui/widgets/tabs/setup_perfomance.h"
-#include "gui/widgets/tabs/setup_players.h"
-#include "gui/widgets/tabs/setup_quick.h"
-#include "gui/widgets/tabs/setup_relations.h"
-#include "gui/widgets/tabs/setup_theme.h"
-#include "gui/widgets/tabs/setup_touch.h"
-#include "gui/widgets/tabs/setup_video.h"
-#include "gui/widgets/tabs/setup_visual.h"
-
-#include "gui/widgets/button.h"
-#include "gui/widgets/label.h"
-#include "gui/widgets/tabbedarea.h"
-
-#include "input/touch/touchmanager.h"
-
-#include "utils/delete2.h"
-#include "utils/dtor.h"
-#include "utils/foreach.h"
-#include "utils/gettext.h"
-
-#include "debug.h"
-
-SetupWindow *setupWindow = nullptr;
-
-SetupWindow::SetupWindow() :
- // TRANSLATORS: setup window name
- Window(_("Setup"), Modal_false, nullptr, "setup.xml"),
- ActionListener(),
- mTabs(),
- mWindowsToReset(),
- mButtons(),
- mModsTab(nullptr),
- mQuickTab(nullptr),
- mResetWindows(nullptr),
- mPanel(CREATEWIDGETR(TabbedArea, this)),
- mVersion(new Label(this, FULL_VERSION)),
- mButtonPadding(5)
-{
- setCloseButton(true);
- setResizable(true);
- setStickyButtonLock(true);
-}
-
-void SetupWindow::postInit()
-{
- Window::postInit();
- int width = 620;
- const int height = 450;
-
- if (config.getIntValue("screenwidth") >= 730)
- width += 100;
-
- setContentSize(width, height);
- setMinWidth(310);
- setMinHeight(210);
-
- mPanel->setSelectable(false);
- mPanel->getTabContainer()->setSelectable(false);
- mPanel->getWidgetContainer()->setSelectable(false);
-
- static const char *const buttonNames[] =
- {
- // TRANSLATORS: setup button
- N_("Apply"),
- // TRANSLATORS: setup button
- N_("Cancel"),
- // TRANSLATORS: setup button
- N_("Store"),
- // TRANSLATORS: setup button
- N_("Reset Windows"),
- nullptr
- };
- int x = width;
- mButtonPadding = getOption("buttonPadding", 5);
- for (const char *const * curBtn = buttonNames;
- *curBtn != nullptr;
- ++ curBtn)
- {
- Button *const btn = new Button(this, gettext(*curBtn), *curBtn, this);
- mButtons.push_back(btn);
- x -= btn->getWidth() + mButtonPadding;
- btn->setPosition(x, height - btn->getHeight() - mButtonPadding);
- add(btn);
-
- // Store this button, as it needs to be enabled/disabled
- if (strcmp(*curBtn, "Reset Windows") == 0)
- mResetWindows = btn;
- }
-
- mPanel->setDimension(Rect(5, 5, width - 10, height - 40));
- mPanel->enableScrollButtons(true);
-
- mTabs.push_back(new Setup_Video(this));
- mTabs.push_back(new Setup_Visual(this));
- mTabs.push_back(new Setup_Audio(this));
- mTabs.push_back(new Setup_Perfomance(this));
- mTabs.push_back(new Setup_Touch(this));
- mTabs.push_back(new Setup_Input(this));
- mTabs.push_back(new Setup_Joystick(this));
- mTabs.push_back(new Setup_Colors(this));
- mTabs.push_back(new Setup_Chat(this));
- mTabs.push_back(new Setup_Players(this));
- mTabs.push_back(new Setup_Relations(this));
- mTabs.push_back(new Setup_Theme(this));
- mTabs.push_back(new Setup_Misc(this));
-
- FOR_EACH (std::list<SetupTab*>::const_iterator, i, mTabs)
- {
- SetupTab *const tab = *i;
- mPanel->addTab(tab->getName(), tab);
- }
- add(mPanel);
-
- if (mResetWindows != nullptr)
- {
- mVersion->setPosition(9,
- height - mVersion->getHeight() - mResetWindows->getHeight() - 9);
- }
- else
- {
- mVersion->setPosition(9, height - mVersion->getHeight() - 30);
- }
- add(mVersion);
-
- center();
-
- widgetResized(Event(nullptr));
- setInGame(false);
- enableVisibleSound(true);
-}
-
-SetupWindow::~SetupWindow()
-{
- delete_all(mTabs);
- mButtons.clear();
- setupWindow = nullptr;
-}
-
-void SetupWindow::action(const ActionEvent &event)
-{
- if (Game::instance() != nullptr)
- Game::instance()->resetAdjustLevel();
- const std::string &eventId = event.getId();
-
- if (eventId == "Apply")
- {
- setVisible(Visible_false);
- for_each(mTabs.begin(), mTabs.end(), std::mem_fun(&SetupTab::apply));
- }
- else if (eventId == "Cancel")
- {
- doCancel();
- }
- else if (eventId == "Store")
- {
- if (chatWindow != nullptr)
- chatWindow->saveState();
- config.write();
- serverConfig.write();
- }
- else if (eventId == "Reset Windows")
- {
- // Bail out if this action happens to be activated before the windows
- // are created (though it should be disabled then)
- if (statusWindow == nullptr)
- return;
-
- FOR_EACH (std::list<Window*>::const_iterator, it, mWindowsToReset)
- {
- if (*it != nullptr)
- (*it)->resetToDefaultSize();
- }
- }
-}
-
-void SetupWindow::setInGame(const bool inGame)
-{
- if (mResetWindows != nullptr)
- mResetWindows->setEnabled(inGame);
-}
-
-void SetupWindow::externalUpdate()
-{
- unloadAdditionalTabs();
- mModsTab = new Setup_Mods(this);
- mTabs.push_back(mModsTab);
- mPanel->addTab(mModsTab->getName(), mModsTab);
- mQuickTab = new Setup_Quick(this);
- mTabs.push_back(mQuickTab);
- mPanel->addTab(mQuickTab->getName(), mQuickTab);
- FOR_EACH (std::list<SetupTab*>::const_iterator, it, mTabs)
- {
- if (*it != nullptr)
- (*it)->externalUpdated();
- }
-}
-
-void SetupWindow::unloadTab(SetupTab *const page)
-{
- if (page != nullptr)
- {
- mTabs.remove(page);
- mPanel->removeTab(mPanel->getTab(page->getName()));
- }
-}
-
-void SetupWindow::unloadAdditionalTabs()
-{
- unloadTab(mModsTab);
- unloadTab(mQuickTab);
- delete2(mModsTab);
- delete2(mQuickTab);
-}
-
-void SetupWindow::externalUnload()
-{
- FOR_EACH (std::list<SetupTab*>::const_iterator, it, mTabs)
- {
- if (*it != nullptr)
- (*it)->externalUnloaded();
- }
- unloadAdditionalTabs();
-}
-
-void SetupWindow::registerWindowForReset(Window *const window)
-{
- mWindowsToReset.push_back(window);
-}
-
-void SetupWindow::unregisterWindowForReset(const Window *const window)
-{
- FOR_EACH (std::list<Window*>::iterator, it, mWindowsToReset)
- {
- if (*it == window)
- {
- mWindowsToReset.erase(it);
- return;
- }
- }
-}
-
-void SetupWindow::hideWindows()
-{
- FOR_EACH (std::list<Window*>::const_iterator, it, mWindowsToReset)
- {
- Window *const window = *it;
- if ((window != nullptr) && !window->isSticky())
- window->setVisible(Visible_false);
- }
- setVisible(Visible_false);
-}
-
-void SetupWindow::doCancel()
-{
- setVisible(Visible_false);
- for_each(mTabs.begin(), mTabs.end(), std::mem_fun(&SetupTab::cancel));
-}
-
-void SetupWindow::activateTab(const std::string &name)
-{
- std::string tmp = gettext(name.c_str());
- mPanel->setSelectedTabByName(tmp);
-}
-
-void SetupWindow::setVisible(Visible visible)
-{
- touchManager.setTempHide(visible == Visible_true);
- Window::setVisible(visible);
-}
-
-void SetupWindow::widgetResized(const Event &event)
-{
- Window::widgetResized(event);
-
- const Rect area = getChildrenArea();
- int x = area.width;
- const int height = area.height;
- const int width = area.width;
- mPanel->setDimension(Rect(5, 5, width - 10, height - 40));
- FOR_EACH (STD_VECTOR<Button*>::iterator, it, mButtons)
- {
- Button *const btn = *it;
- x -= btn->getWidth() + mButtonPadding;
- btn->setPosition(x, height - btn->getHeight() - mButtonPadding);
- }
- if (mResetWindows != nullptr)
- {
- mVersion->setPosition(9,
- height - mVersion->getHeight() - mResetWindows->getHeight() - 9);
- }
- else
- {
- mVersion->setPosition(9, height - mVersion->getHeight() - 30);
- }
-}
diff --git a/src/gui/windows/setupwindow.h b/src/gui/windows/setupwindow.h
deleted file mode 100644
index 79a11a469..000000000
--- a/src/gui/windows/setupwindow.h
+++ /dev/null
@@ -1,96 +0,0 @@
-/*
- * The ManaPlus Client
- * Copyright (C) 2004-2009 The Mana World Development Team
- * Copyright (C) 2009-2010 The Mana Developers
- * Copyright (C) 2011-2017 The ManaPlus Developers
- *
- * This file is part of The ManaPlus Client.
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-#ifndef GUI_WINDOWS_SETUPWINDOW_H
-#define GUI_WINDOWS_SETUPWINDOW_H
-
-#include "gui/widgets/window.h"
-
-#include "listeners/actionlistener.h"
-
-class Button;
-class Label;
-class SetupTab;
-class TabbedArea;
-
-/**
- * The setup dialog. Displays several tabs for configuring different aspects
- * of the game.
- *
- * \ingroup GUI
- */
-class SetupWindow final : public Window,
- public ActionListener
-{
- public:
- SetupWindow();
-
- A_DELETE_COPY(SetupWindow)
-
- ~SetupWindow();
-
- void postInit() override final;
-
- void action(const ActionEvent &event) override final;
-
- void setInGame(const bool inGame);
-
- void externalUpdate();
-
- void externalUnload();
-
- void registerWindowForReset(Window *const window);
-
- void unregisterWindowForReset(const Window *const window);
-
- void hideWindows();
-
- void clearWindowsForReset()
- { mWindowsToReset.clear(); }
-
- void doCancel();
-
- void activateTab(const std::string &name);
-
- void setVisible(Visible visible) override final;
-
- void widgetResized(const Event &event) override final;
-
- private:
- void unloadAdditionalTabs();
-
- void unloadTab(SetupTab *const page);
-
- std::list<SetupTab*> mTabs;
- std::list<Window*> mWindowsToReset;
- STD_VECTOR<Button*> mButtons;
- SetupTab *mModsTab;
- SetupTab *mQuickTab;
- Button *mResetWindows;
- TabbedArea *mPanel A_NONNULLPOINTER;
- Label *mVersion A_NONNULLPOINTER;
- int mButtonPadding;
-};
-
-extern SetupWindow* setupWindow;
-
-#endif // GUI_WINDOWS_SETUPWINDOW_H
diff --git a/src/gui/windows/shopselldialog.cpp b/src/gui/windows/shopselldialog.cpp
deleted file mode 100644
index 26911836b..000000000
--- a/src/gui/windows/shopselldialog.cpp
+++ /dev/null
@@ -1,60 +0,0 @@
-/*
- * The ManaPlus Client
- * Copyright (C) 2004-2009 The Mana World Development Team
- * Copyright (C) 2009-2010 The Mana Developers
- * Copyright (C) 2011-2017 The ManaPlus Developers
- *
- * This file is part of The ManaPlus Client.
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-#ifdef TMWA_SUPPORT
-
-#include "gui/windows/shopselldialog.h"
-
-#include "being/playerinfo.h"
-
-#include "gui/windows/tradewindow.h"
-
-#include "gui/models/shopitems.h"
-
-#include "gui/widgets/shoplistbox.h"
-
-#include "net/buysellhandler.h"
-
-#include "debug.h"
-
-ShopSellDialog::ShopSellDialog(const std::string &nick) :
- SellDialog(IsSell_true, Advanced_false),
- mNick(nick)
-{
-}
-
-void ShopSellDialog::sellAction(const ActionEvent &event A_UNUSED)
-{
- if (mAmountItems <= 0 || mAmountItems > mMaxItems)
- return;
-
- const int selectedItem = mShopItemList->getSelected();
- ShopItem *const item = mShopItems->at(selectedItem);
- if (item == nullptr || PlayerInfo::isItemProtected(item->getId()))
- return;
- buySellHandler->sendSellRequest(mNick, item, mAmountItems);
-
- if (tradeWindow != nullptr)
- tradeWindow->addAutoItem(mNick, item, mAmountItems);
-}
-
-#endif // TMWA_SUPPORT
diff --git a/src/gui/windows/shopselldialog.h b/src/gui/windows/shopselldialog.h
deleted file mode 100644
index debed53b3..000000000
--- a/src/gui/windows/shopselldialog.h
+++ /dev/null
@@ -1,54 +0,0 @@
-/*
- * The ManaPlus Client
- * Copyright (C) 2004-2009 The Mana World Development Team
- * Copyright (C) 2009-2010 The Mana Developers
- * Copyright (C) 2011-2017 The ManaPlus Developers
- *
- * This file is part of The ManaPlus Client.
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-#ifndef GUI_WINDOWS_SHOPSELLDIALOG_H
-#define GUI_WINDOWS_SHOPSELLDIALOG_H
-
-#ifdef TMWA_SUPPORT
-
-#include "gui/widgets/selldialog.h"
-
-/**
- * The sell dialog.
- *
- * \ingroup Interface
- */
-class ShopSellDialog final : public SellDialog
-{
- public:
- /**
- * Constructor.
- *
- * @see Window::Window
- */
- explicit ShopSellDialog(const std::string &nick);
-
- A_DELETE_COPY(ShopSellDialog)
-
- protected:
- void sellAction(const ActionEvent &event) override final;
-
- std::string mNick;
-};
-
-#endif // TMWA_SUPPORT
-#endif // GUI_WINDOWS_SHOPSELLDIALOG_H
diff --git a/src/gui/windows/shopwindow.cpp b/src/gui/windows/shopwindow.cpp
deleted file mode 100644
index 0e55bcca1..000000000
--- a/src/gui/windows/shopwindow.cpp
+++ /dev/null
@@ -1,1175 +0,0 @@
-/*
- * The ManaPlus Client
- * Copyright (C) 2004-2009 The Mana World Development Team
- * Copyright (C) 2009-2010 The Mana Developers
- * Copyright (C) 2011-2017 The ManaPlus Developers
- *
- * This file is part of The ManaPlus Client.
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-#include "gui/windows/shopwindow.h"
-
-#include "const/resources/currency.h"
-
-#ifdef TMWA_SUPPORT
-#include "gui/windows/buydialog.h"
-#include "gui/windows/chatwindow.h"
-#include "gui/windows/confirmdialog.h"
-#include "gui/windows/shopselldialog.h"
-#include "gui/windows/tradewindow.h"
-
-#include "const/gui/chat.h"
-#endif // TMWA_SUPPORT
-
-#include "enums/gui/layouttype.h"
-
-#include "gui/windows/editdialog.h"
-
-#include "gui/windows/itemamountwindow.h"
-#include "gui/windows/setupwindow.h"
-
-#include "gui/models/shopitems.h"
-
-#include "gui/widgets/button.h"
-#include "gui/widgets/checkbox.h"
-#include "gui/widgets/containerplacer.h"
-#include "gui/widgets/createwidget.h"
-#include "gui/widgets/layout.h"
-#include "gui/widgets/scrollarea.h"
-#include "gui/widgets/shoplistbox.h"
-#include "gui/widgets/tabstrip.h"
-
-#include "listeners/shoprenamelistener.h"
-
-#ifdef TMWA_SUPPORT
-#include "actormanager.h"
-#include "soundmanager.h"
-#endif // TMWA_SUPPORT
-#include "configuration.h"
-#include "settings.h"
-
-#include "being/localplayer.h"
-#include "being/playerinfo.h"
-
-#ifdef TMWA_SUPPORT
-#include "being/playerrelations.h"
-#include "net/chathandler.h"
-#endif // TMWA_SUPPORT
-#include "net/buyingstorehandler.h"
-#include "net/vendinghandler.h"
-#include "net/net.h"
-#ifdef TMWA_SUPPORT
-#include "net/tradehandler.h"
-#endif // TMWA_SUPPORT
-
-#include "utils/checkutils.h"
-#include "utils/delete2.h"
-#include "utils/foreach.h"
-#include "utils/gettext.h"
-
-#ifdef TMWA_SUPPORT
-#include "resources/iteminfo.h"
-#endif // TMWA_SUPPORT
-
-#include "resources/inventory/inventory.h"
-
-#include "resources/item/shopitem.h"
-
-#include <sys/stat.h>
-
-#include <sstream>
-
-#include "debug.h"
-
-ShopWindow *shopWindow = nullptr;
-extern std::string tradePartnerName;
-ShopWindow::DialogList ShopWindow::instances;
-
-ShopWindow::ShopWindow() :
- // TRANSLATORS: shop window name
- Window(_("Personal Shop"), Modal_false, nullptr, "shop.xml"),
- VendingModeListener(),
- VendingSlotsListener(),
- BuyingStoreModeListener(),
- BuyingStoreSlotsListener(),
- ActionListener(),
- SelectionListener(),
- // TRANSLATORS: shop window button
- mCloseButton(new Button(this, _("Close"), "close", this)),
- mBuyShopItems(new ShopItems(false, DEFAULT_CURRENCY)),
- mSellShopItems(new ShopItems(false, DEFAULT_CURRENCY)),
- mTradeItem(nullptr),
- mBuyShopItemList(CREATEWIDGETR(ShopListBox,
- this, mBuyShopItems, mBuyShopItems, ShopListBoxType::BuyShop)),
- mSellShopItemList(CREATEWIDGETR(ShopListBox,
- this, mSellShopItems, mSellShopItems, ShopListBoxType::SellShop)),
- mCurrentShopItemList(nullptr),
- mScrollArea(new ScrollArea(this, mBuyShopItemList,
- fromBool(getOptionBool("showbuybackground"), Opaque),
- "shop_buy_background.xml")),
- // TRANSLATORS: shop window label
- mAddButton(new Button(this, _("Add"), "add", this)),
- // TRANSLATORS: shop window label
- mDeleteButton(new Button(this, _("Delete"), "delete", this)),
- mAnnounceButton(nullptr),
- mPublishButton(nullptr),
- mRenameButton(nullptr),
- mAnnounceLinks(nullptr),
- mTabs(nullptr),
- mAcceptPlayer(),
- mTradeNick(),
- mSellShopName(serverConfig.getStringValue("sellShopName")),
- mSelectedItem(-1),
- mAnnonceTime(0),
- mLastRequestTimeList(0),
- mLastRequestTimeItem(0),
- mRandCounter(0),
- mTradeMoney(0),
- mSellShopSize(0),
- mBuyShopSize(0),
- isBuySelected(true),
- mHaveVending(Net::getNetworkType() != ServerType::TMWATHENA),
- mEnableBuyingStore(false),
- mEnableVending(false)
-{
- setWindowName("Personal Shop");
- setResizable(true);
- setCloseButton(true);
- setStickyButtonLock(true);
- setMinWidth(300);
- setMinHeight(220);
- if (mainGraphics->mWidth > 600)
- setDefaultSize(500, 300, ImagePosition::CENTER);
- else
- setDefaultSize(380, 300, ImagePosition::CENTER);
-
- if (setupWindow != nullptr)
- setupWindow->registerWindowForReset(this);
-
- const int size = config.getIntValue("fontSize")
- + getOption("tabHeightAdjust", 16);
- mTabs = new TabStrip(this, "shop", size);
- mTabs->addActionListener(this);
- mTabs->setActionEventId("tab_");
- // TRANSLATORS: shop window tab name
- mTabs->addButton(_("Buy"), "buy", true);
- // TRANSLATORS: shop window tab name
- mTabs->addButton(_("Sell"), "sell", false);
- mTabs->setSelectable(false);
- mScrollArea->setSelectable(false);
-
- loadList();
-
- mBuyShopItemList->setPriceCheck(false);
- mSellShopItemList->setPriceCheck(false);
-
- mScrollArea->setHorizontalScrollPolicy(ScrollArea::SHOW_NEVER);
-
- mBuyShopItemList->addSelectionListener(this);
- mSellShopItemList->addSelectionListener(this);
-
- ContainerPlacer placer;
- placer = getPlacer(0, 0);
-
- placer(0, 0, mTabs, 8).setPadding(3);
-
- if (mHaveVending)
- {
- // TRANSLATORS: shop window button
- mPublishButton = new Button(this, _("Publish"), "publish", this);
- // TRANSLATORS: shop window button
- mRenameButton = new Button(this, _("Rename"), "rename", this);
- placer(2, 6, mPublishButton);
- placer(3, 6, mRenameButton);
- }
- else
- {
- // TRANSLATORS: shop window button
- mAnnounceButton = new Button(this, _("Announce"), "announce", this);
- // TRANSLATORS: shop window checkbox
- mAnnounceLinks = new CheckBox(this, _("Show links in announce"), false,
- this, "link announce");
-
- placer(2, 6, mAnnounceButton);
- placer(0, 7, mAnnounceLinks, 7);
- }
-
- placer(0, 1, mScrollArea, 8, 5).setPadding(3);
- placer(0, 6, mAddButton);
- placer(1, 6, mDeleteButton);
- placer(7, 6, mCloseButton);
-
- Layout &layout = getLayout();
- layout.setRowHeight(0, LayoutType::SET);
-
- center();
- loadWindowState();
- updateShopName();
- instances.push_back(this);
-}
-
-void ShopWindow::postInit()
-{
- Window::postInit();
- setVisible(Visible_false);
- enableVisibleSound(true);
- updateSelection();
-}
-
-ShopWindow::~ShopWindow()
-{
- saveList();
-
- delete2(mBuyShopItemList);
- delete2(mSellShopItemList);
- delete2(mBuyShopItems);
- delete2(mSellShopItems);
- delete2(mTradeItem);
-
- instances.remove(this);
-}
-
-void ShopWindow::action(const ActionEvent &event)
-{
- const std::string &eventId = event.getId();
- if (eventId == "close")
- {
- close();
- return;
- }
-#ifdef TMWA_SUPPORT
- else if (eventId == "yes")
- {
- startTrade();
- }
- else if (eventId == "no")
- {
- mTradeNick.clear();
- }
- else if (eventId == "ignore")
- {
- playerRelations.ignoreTrade(mTradeNick);
- mTradeNick.clear();
- }
- else if (eventId == "announce")
- {
- if (isBuySelected)
- {
- if (mBuyShopItems->getNumberOfElements() > 0)
- announce(mBuyShopItems, BUY);
- }
- else if (mSellShopItems->getNumberOfElements() > 0)
- {
- announce(mSellShopItems, SELL);
- }
- }
-#endif // TMWA_SUPPORT
- else if (eventId == "delete")
- {
- if (isBuySelected)
- {
- if (mBuyShopItemList != nullptr &&
- mBuyShopItemList->getSelected() >= 0)
- {
- mBuyShopItems->del(mBuyShopItemList->getSelected());
- if (isShopEmpty() && (localPlayer != nullptr))
- localPlayer->updateStatus();
- }
- }
- else if ((mSellShopItemList != nullptr)
- && mSellShopItemList->getSelected() >= 0)
- {
- mSellShopItems->del(mSellShopItemList->getSelected());
- if (isShopEmpty() && (localPlayer != nullptr))
- localPlayer->updateStatus();
- }
- }
- else if (eventId == "tab_buy")
- {
- isBuySelected = true;
- updateSelection();
- }
- else if (eventId == "tab_sell")
- {
- isBuySelected = false;
- updateSelection();
- }
- else if (eventId == "publish")
- {
- if (isBuySelected)
- {
- if (mEnableBuyingStore)
- {
- buyingStoreHandler->close();
- BuyingStoreModeListener::distributeEvent(false);
- }
- else
- {
- STD_VECTOR<ShopItem*> &items = mBuyShopItems->items();
- if (!items.empty())
- {
- buyingStoreHandler->create(mSellShopName,
- PlayerInfo::getAttribute(Attributes::MONEY),
- true,
- items);
- }
- }
- }
- else
- {
- if (mEnableVending)
- {
- vendingHandler->close();
- VendingModeListener::distributeEvent(false);
- }
- else
- {
- STD_VECTOR<ShopItem*> &oldItems = mSellShopItems->items();
- STD_VECTOR<ShopItem*> items;
- const Inventory *const inv = PlayerInfo::getCartInventory();
- if (inv == nullptr)
- return;
- FOR_EACH (STD_VECTOR<ShopItem*>::iterator, it, oldItems)
- {
- ShopItem *const item = *it;
- if (item == nullptr)
- continue;
- const Item *const cartItem = inv->findItem(item->getId(),
- item->getColor());
- if (cartItem == nullptr)
- continue;
- item->setInvIndex(cartItem->getInvIndex());
- const int amount = cartItem->getQuantity();
- if (amount == 0)
- continue;
- if (item->getQuantity() > amount)
- item->setQuantity(amount);
- items.push_back(item);
- if (static_cast<signed int>(items.size()) >= mSellShopSize)
- break;
- }
- if (!items.empty())
- vendingHandler->createShop(mSellShopName, true, items);
- }
- }
- }
- else if (eventId == "rename")
- {
- EditDialog *const dialog = CREATEWIDGETR(EditDialog,
- // TRANSLATORS: shop rename dialog title
- _("Please enter new shop name"),
- mSellShopName,
- "OK");
- shopRenameListener.setDialog(dialog);
- dialog->addActionListener(&shopRenameListener);
- }
-
- if (mSelectedItem < 1)
- return;
-
- const Inventory *const inv = mHaveVending && !isBuySelected
- ? PlayerInfo::getCartInventory() : PlayerInfo::getInventory();
- if (inv == nullptr)
- return;
-
- // +++ need support for colors
- Item *const item = inv->findItem(mSelectedItem, ItemColor_zero);
- if (item != nullptr)
- {
- if (eventId == "add")
- {
- if (isBuySelected)
- {
- ItemAmountWindow::showWindow(ItemAmountWindowUsage::ShopBuyAdd,
- this,
- item,
- sumAmount(item));
- }
- else
- {
- ItemAmountWindow::showWindow(
- ItemAmountWindowUsage::ShopSellAdd,
- this,
- item,
- sumAmount(item));
- }
- }
- }
-}
-
-void ShopWindow::valueChanged(const SelectionEvent &event A_UNUSED)
-{
- updateButtonsAndLabels();
-}
-
-void ShopWindow::updateButtonsAndLabels()
-{
- bool allowDel(false);
- bool allowAdd(false);
- const bool sellNotEmpty = mSellShopItems->getNumberOfElements() > 0;
- if (isBuySelected)
- {
- allowAdd = !mEnableBuyingStore;
- allowDel = !mEnableBuyingStore
- && mBuyShopItemList->getSelected() != -1
- && mBuyShopItems->getNumberOfElements() > 0;
- if (mPublishButton != nullptr)
- {
- if (mEnableBuyingStore)
- {
- // TRANSLATORS: unpublish shop button
- mPublishButton->setCaption(_("Unpublish"));
- }
- else
- {
- // TRANSLATORS: publish shop button
- mPublishButton->setCaption(_("Publish"));
- }
- mPublishButton->adjustSize();
- if (mBuyShopSize > 0)
- mPublishButton->setEnabled(true);
- else
- mPublishButton->setEnabled(false);
- }
- }
- else
- {
- allowAdd = !mEnableVending && mSelectedItem != -1;
- allowDel = !mEnableVending
- && mSellShopItemList->getSelected() != -1
- && sellNotEmpty;
- if (mPublishButton != nullptr)
- {
- if (mEnableVending)
- {
- // TRANSLATORS: unpublish shop button
- mPublishButton->setCaption(_("Unpublish"));
- }
- else
- {
- // TRANSLATORS: publish shop button
- mPublishButton->setCaption(_("Publish"));
- }
- mPublishButton->adjustSize();
- if (sellNotEmpty
- && mSellShopSize > 0
- && (localPlayer != nullptr)
- && localPlayer->getHaveCart())
- {
- mPublishButton->setEnabled(true);
- }
- else
- {
- mPublishButton->setEnabled(false);
- }
- }
- }
- mAddButton->setEnabled(allowAdd);
- mDeleteButton->setEnabled(allowDel);
- if (mRenameButton != nullptr)
- mRenameButton->setEnabled(!mEnableVending);
-}
-
-void ShopWindow::setVisible(Visible visible)
-{
- Window::setVisible(visible);
-}
-
-void ShopWindow::addBuyItem(const Item *const item, const int amount,
- const int price)
-{
- if (item == nullptr)
- return;
- const bool emp = isShopEmpty();
- mBuyShopItems->addItemNoDup(item->getId(),
- item->getType(),
- item->getColor(),
- amount,
- price);
- if (emp && (localPlayer != nullptr))
- localPlayer->updateStatus();
-
- updateButtonsAndLabels();
-}
-
-void ShopWindow::addSellItem(const Item *const item, const int amount,
- const int price)
-{
- if (item == nullptr)
- return;
- const bool emp = isShopEmpty();
- mSellShopItems->addItemNoDup(item->getId(),
- item->getType(),
- item->getColor(),
- amount,
- price);
- if (emp && (localPlayer != nullptr))
- localPlayer->updateStatus();
-
- updateButtonsAndLabels();
-}
-
-void ShopWindow::loadList()
-{
- std::ifstream shopFile;
- struct stat statbuf;
-
- mBuyShopItems->clear();
- mSellShopItems->clear();
-
- const std::string shopListName = settings.serverConfigDir
- + "/shoplist.txt";
-
- if (stat(shopListName.c_str(), &statbuf) == 0 &&
- S_ISREG(statbuf.st_mode))
- {
- shopFile.open(shopListName.c_str(), std::ios::in);
- if (!shopFile.is_open())
- {
- reportAlways("Error opening file for reading: %s",
- shopListName.c_str());
- shopFile.close();
- return;
- }
- char line[101];
- while (shopFile.getline(line, 100))
- {
- std::string buf;
- const std::string str = line;
- if (!str.empty())
- {
- STD_VECTOR<int> tokens;
- std::stringstream ss(str);
-
- while (ss >> buf)
- tokens.push_back(atoi(buf.c_str()));
-
- if (tokens.size() == 5 && (tokens[0] != 0))
- {
- // +++ need impliment colors?
- if ((tokens[1] != 0) && (tokens[2] != 0))
- {
- mBuyShopItems->addItem(
- tokens[0],
- ItemType::Unknown,
- ItemColor_one,
- tokens[1],
- tokens[2]);
- }
- if ((tokens[3] != 0) && (tokens[4] != 0))
- {
- mSellShopItems->addItem(
- tokens[0],
- ItemType::Unknown,
- ItemColor_one,
- tokens[3],
- tokens[4]);
- }
- }
- }
- }
- shopFile.close();
- }
-}
-
-void ShopWindow::saveList() const
-{
- std::ofstream shopFile;
- const std::string shopListName = settings.serverConfigDir
- + "/shoplist.txt";
- std::map<int, ShopItem*> mapItems;
-
- shopFile.open(shopListName.c_str(), std::ios::binary);
- if (!shopFile.is_open())
- {
- reportAlways("Error opening file writing: %s",
- shopListName.c_str());
- return;
- }
-
- STD_VECTOR<ShopItem*> items = mBuyShopItems->items();
- FOR_EACH (STD_VECTOR<ShopItem*>::const_iterator, it, items)
- {
- ShopItem *const item = *(it);
- if (item != nullptr)
- mapItems[item->getId()] = item;
- }
-
- items = mSellShopItems->items();
- FOR_EACH (STD_VECTOR<ShopItem*>::const_iterator, it, items)
- {
- if ((*it) == nullptr)
- continue;
- const ShopItem *const sellItem = *(it);
- const ShopItem *const buyItem = mapItems[sellItem->getId()];
-
- shopFile << sellItem->getId();
- if (buyItem != nullptr)
- {
- shopFile << strprintf(" %d %d ", buyItem->getQuantity(),
- buyItem->getPrice());
- mapItems.erase(sellItem->getId());
- }
- else
- {
- shopFile << " 0 0 ";
- }
-
- shopFile << strprintf("%d %d", sellItem->getQuantity(),
- sellItem->getPrice()) << std::endl;
- }
-
- for (std::map<int, ShopItem*>::const_iterator mapIt = mapItems.begin(),
- mapIt_fend = mapItems.end();
- mapIt != mapIt_fend;
- ++mapIt)
- {
- const ShopItem *const buyItem = (*mapIt).second;
- if (buyItem != nullptr)
- {
- shopFile << buyItem->getId();
- shopFile << strprintf(" %d %d ", buyItem->getQuantity(),
- buyItem->getPrice());
- shopFile << "0 0" << std::endl;
- }
- }
-
- shopFile.close();
-}
-
-#ifdef TMWA_SUPPORT
-void ShopWindow::announce(ShopItems *const list, const int mode)
-{
- if (list == nullptr)
- return;
-
- std::string data;
- if (mode == BUY)
- data.append("Buy ");
- else
- data.append("Sell ");
-
- if (mAnnonceTime != 0 &&
- (mAnnonceTime + (2 * 60) > cur_time || mAnnonceTime > cur_time))
- {
- return;
- }
-
- mAnnonceTime = cur_time;
- if (mAnnounceButton != nullptr)
- mAnnounceButton->setEnabled(false);
-
- STD_VECTOR<ShopItem*> items = list->items();
-
- FOR_EACH (STD_VECTOR<ShopItem*>::const_iterator, it, items)
- {
- const ShopItem *const item = *(it);
- if (item->getQuantity() > 1)
- {
- if (mAnnounceLinks->isSelected())
- {
- data.append(strprintf("[@@%d|%s@@] (%dGP) %d, ", item->getId(),
- item->getInfo().getName().c_str(),
- item->getPrice(), item->getQuantity()));
- }
- else
- {
- data.append(strprintf("%s (%dGP) %d, ",
- item->getInfo().getName().c_str(),
- item->getPrice(), item->getQuantity()));
- }
- }
- else
- {
- if (mAnnounceLinks->isSelected())
- {
- data.append(strprintf("[@@%d|%s@@] (%dGP), ", item->getId(),
- item->getInfo().getName().c_str(), item->getPrice()));
- }
- else
- {
- data.append(strprintf("%s (%dGP), ",
- item->getInfo().getName().c_str(), item->getPrice()));
- }
- }
- }
-
- chatHandler->channelMessage(TRADE_CHANNEL, data);
-}
-
-void ShopWindow::startTrade()
-{
- if (actorManager == nullptr ||
- tradeWindow == nullptr)
- {
- return;
- }
-
- const Being *const being = actorManager->findBeingByName(
- mTradeNick, ActorType::Player);
- tradeWindow->clear();
- if (mTradeMoney != 0)
- {
- tradeWindow->addAutoMoney(mTradeNick, mTradeMoney);
- }
- else
- {
- tradeWindow->addAutoItem(mTradeNick, mTradeItem,
- mTradeItem->getQuantity());
- }
- tradeHandler->request(being);
- tradePartnerName = mTradeNick;
- mTradeNick.clear();
-}
-
-void ShopWindow::giveList(const std::string &nick, const int mode)
-{
- if (!checkFloodCounter(mLastRequestTimeList))
- return;
-
- std::string data("\302\202");
-
- ShopItems *list;
- if (mode == BUY)
- {
- list = mBuyShopItems;
- data.append("S1");
- }
- else
- {
- list = mSellShopItems;
- data.append("B1");
- }
- if (list == nullptr)
- return;
-
- const Inventory *const inv = PlayerInfo::getInventory();
- if (inv == nullptr)
- return;
-
- STD_VECTOR<ShopItem*> items = list->items();
-
- FOR_EACH (STD_VECTOR<ShopItem*>::const_iterator, it, items)
- {
- const ShopItem *const item = *(it);
- if (item == nullptr)
- continue;
-
- if (mode == SELL)
- {
- const Item *const item2 = inv->findItem(item->getId(),
- ItemColor_zero);
- if (item2 != nullptr)
- {
- int amount = item->getQuantity();
- if (item2->getQuantity() < amount)
- amount = item2->getQuantity();
-
- if (amount != 0)
- {
- data.append(strprintf("%s%s%s",
- encodeStr(item->getId(), 2).c_str(),
- encodeStr(item->getPrice(), 4).c_str(),
- encodeStr(amount, 3).c_str()));
- }
- }
- }
- else
- {
- int amount = item->getQuantity();
- if (item->getPrice() * amount > PlayerInfo::getAttribute(
- Attributes::MONEY))
- {
- amount = PlayerInfo::getAttribute(Attributes::MONEY)
- / item->getPrice();
- }
-
- if (amount > 0)
- {
- data.append(strprintf("%s%s%s",
- encodeStr(item->getId(), 2).c_str(),
- encodeStr(item->getPrice(), 4).c_str(),
- encodeStr(amount, 3).c_str()));
- }
- }
- }
- sendMessage(nick, data, true);
-}
-
-void ShopWindow::sendMessage(const std::string &nick,
- std::string data,
- const bool random)
-{
- if (chatWindow == nullptr)
- return;
-
- if (random)
- {
- mRandCounter ++;
- if (mRandCounter > 200)
- mRandCounter = 0;
- data.append(encodeStr(mRandCounter, 2));
- }
-
- if (config.getBoolValue("hideShopMessages"))
- chatHandler->privateMessage(nick, data);
- else
- chatWindow->addWhisper(nick, data, ChatMsgType::BY_PLAYER);
-}
-
-void ShopWindow::showList(const std::string &nick, std::string data)
-{
- const Inventory *const inv = PlayerInfo::getInventory();
- if (inv == nullptr)
- return;
-
- BuyDialog *buyDialog = nullptr;
- SellDialog *sellDialog = nullptr;
- if (data.find("B1") == 0)
- {
- data = data.substr(2);
- CREATEWIDGETV(buyDialog, BuyDialog, nick, DEFAULT_CURRENCY);
- }
- else if (data.find("S1") == 0)
- {
- data = data.substr(2);
- CREATEWIDGETV(sellDialog, ShopSellDialog, nick);
- }
- else
- {
- return;
- }
-
- if (buyDialog != nullptr)
- buyDialog->setMoney(PlayerInfo::getAttribute(Attributes::MONEY));
- if (sellDialog != nullptr)
- sellDialog->setMoney(PlayerInfo::getAttribute(Attributes::MONEY));
-
- for (unsigned f = 0; f < data.length(); f += 9)
- {
- if (f + 9 > data.length())
- break;
-
- const int id = decodeStr(data.substr(f, 2));
- const int price = decodeStr(data.substr(f + 2, 4));
- int amount = decodeStr(data.substr(f + 6, 3));
- if (buyDialog != nullptr && amount > 0)
- {
- buyDialog->addItem(id,
- ItemType::Unknown,
- ItemColor_one,
- amount,
- price);
- }
- if (sellDialog != nullptr)
- {
- const Item *const item = inv->findItem(id, ItemColor_zero);
- if (item != nullptr)
- {
- if (item->getQuantity() < amount)
- amount = item->getQuantity();
- }
- else
- {
- amount = 0;
- }
- ShopItem *const shopItem = sellDialog->addItem(id,
- ItemType::Unknown,
- ItemColor_one,
- amount,
- price);
-
- if (shopItem != nullptr && amount <= 0)
- shopItem->setDisabled(true);
- }
- }
- if (buyDialog != nullptr)
- buyDialog->sort();
-}
-
-void ShopWindow::processRequest(const std::string &nick,
- std::string data,
- const int mode)
-{
- if (localPlayer == nullptr ||
- !mTradeNick.empty() ||
- PlayerInfo::isTrading() == Trading_true ||
- actorManager == nullptr ||
- actorManager->findBeingByName(nick, ActorType::Player) == nullptr)
- {
- return;
- }
-
- const Inventory *const inv = PlayerInfo::getInventory();
- if (inv == nullptr)
- return;
-
- const size_t idx = data.find(' ');
- if (idx == std::string::npos)
- return;
-
- if (!checkFloodCounter(mLastRequestTimeItem))
- return;
-
- if (!mTradeNick.empty())
- {
- sendMessage(nick,
- // TRANSLATORS: error buy/sell shop request
- _("error: player busy") + std::string(" "),
- true);
- return;
- }
-
- data = data.substr(idx + 1);
-
- std::string part1;
- std::string part2;
- std::string part3;
- std::stringstream ss(data);
- int id;
- int price;
- int amount;
-
- if (!(ss >> part1))
- return;
-
- if (!(ss >> part2))
- return;
-
- if (!(ss >> part3))
- return;
-
- id = atoi(part1.c_str());
- price = atoi(part2.c_str());
- amount = atoi(part3.c_str());
-
- delete mTradeItem;
- // +++ need impliment colors?
- mTradeItem = new ShopItem(-1,
- id,
- ItemType::Unknown,
- ItemColor_one,
- amount,
- price,
- DEFAULT_CURRENCY);
-
- if (mode == BUY)
- {
- // +++ need support for colors
- const Item *const item2 = inv->findItem(mTradeItem->getId(),
- ItemColor_zero);
- if (item2 == nullptr ||
- item2->getQuantity() < amount ||
- !findShopItem(mTradeItem, SELL))
- {
- sendMessage(nick,
- // TRANSLATORS: error buy/sell shop request
- _("error: Can't sell this item") + std::string(" "),
- true);
- return;
- }
- mTradeMoney = 0;
- }
- else
- {
- if (!findShopItem(mTradeItem, BUY))
- {
- sendMessage(nick,
- // TRANSLATORS: error buy/sell shop request
- _("error: Can't buy this item") + std::string(" "),
- true);
- return;
- }
- mTradeMoney = mTradeItem->getPrice() * mTradeItem->getQuantity();
- }
-
- mTradeNick = nick;
-
- if (config.getBoolValue("autoShop"))
- {
- soundManager.playGuiSound(SOUND_TRADE);
- startTrade();
- }
- else
- {
- std::string msg;
- if (mode == BUY)
- {
- // TRANSLATORS: buy shop request (nick, item)
- msg = strprintf(_("%s wants to buy %s do you accept?"),
- nick.c_str(),
- mTradeItem->getInfo().getName().c_str());
- }
- else
- {
- // TRANSLATORS: sell shop request (nick, item)
- msg = strprintf(_("%s wants to sell %s do you accept?"),
- nick.c_str(),
- mTradeItem->getInfo().getName().c_str());
- }
-
- ConfirmDialog *const confirmDlg = CREATEWIDGETR(ConfirmDialog,
- // TRANSLATORS: shop window dialog
- _("Request for Trade"),
- msg,
- SOUND_REQUEST,
- true);
- confirmDlg->addActionListener(this);
- }
-}
-
-void ShopWindow::updateTimes()
-{
- BLOCK_START("ShopWindow::updateTimes")
- if (mAnnounceButton == nullptr)
- {
- BLOCK_END("ShopWindow::updateTimes")
- return;
- }
- if (mAnnonceTime + (2 * 60) < cur_time ||
- mAnnonceTime > cur_time)
- {
- mAnnounceButton->setEnabled(true);
- }
- BLOCK_END("ShopWindow::updateTimes")
-}
-
-bool ShopWindow::checkFloodCounter(time_t &counterTime)
-{
- if (counterTime == 0 || counterTime > cur_time)
- counterTime = cur_time;
- else if (counterTime + 10 > cur_time)
- return false;
- else
- counterTime = cur_time;
- return true;
-}
-
-bool ShopWindow::findShopItem(const ShopItem *const shopItem,
- const int mode) const
-{
- if (shopItem == nullptr)
- return false;
-
- STD_VECTOR<ShopItem*> items;
- if (mode == SELL)
- items = mSellShopItems->items();
- else
- items = mBuyShopItems->items();
-
- FOR_EACH (STD_VECTOR<ShopItem*>::const_iterator, it, items)
- {
- const ShopItem *const item = *(it);
- if (item == nullptr)
- continue;
-
- if (item->getId() == shopItem->getId()
- && item->getPrice() == shopItem->getPrice()
- && item->getQuantity() >= shopItem->getQuantity())
- {
- return true;
- }
- }
- return false;
-}
-#endif // TMWA_SUPPORT
-
-int ShopWindow::sumAmount(const Item *const shopItem)
-{
- if ((localPlayer == nullptr) || (shopItem == nullptr))
- return 0;
-
- const Inventory *const inv = PlayerInfo::getInventory();
- if (inv == nullptr)
- return 0;
- int sum = 0;
-
- for (unsigned f = 0; f < inv->getSize(); f ++)
- {
- const Item *const item = inv->getItem(f);
- if ((item != nullptr) && item->getId() == shopItem->getId())
- sum += item->getQuantity();
- }
- return sum;
-}
-
-bool ShopWindow::isShopEmpty() const
-{
- if (mBuyShopItems->empty() && mSellShopItems->empty())
- return true;
- return false;
-}
-
-void ShopWindow::updateSelection()
-{
- if (isBuySelected)
- mCurrentShopItemList = mBuyShopItemList;
- else
- mCurrentShopItemList = mSellShopItemList;
- mScrollArea->setContent(mCurrentShopItemList);
- updateButtonsAndLabels();
-}
-
-void ShopWindow::updateShopName()
-{
- if (mSellShopName.empty())
- {
- // TRANSLATORS: shop window name
- setCaption(_("Personal Shop"));
- }
- else
- {
- // TRANSLATORS: shop window name
- setCaption(strprintf(_("Personal Shop - %s"), mSellShopName.c_str()));
- }
-}
-
-void ShopWindow::setShopName(const std::string &name)
-{
- mSellShopName = name;
- serverConfig.setValue("sellShopName", mSellShopName);
- updateShopName();
-}
-
-void ShopWindow::vendingSlotsChanged(const int slots)
-{
- mSellShopSize = slots;
- updateButtonsAndLabels();
-}
-
-void ShopWindow::vendingEnabled(const bool b)
-{
- mEnableVending = b;
- localPlayer->enableShop(b);
- if (!b)
- mSellShopSize = 0;
- updateButtonsAndLabels();
-}
-
-void ShopWindow::buyingStoreSlotsChanged(const int slots)
-{
- mBuyShopSize = slots;
- updateButtonsAndLabels();
-}
-
-void ShopWindow::buyingStoreEnabled(const bool b)
-{
- mEnableBuyingStore = b;
- localPlayer->enableShop(b);
- if (!b)
- mBuyShopSize = 0;
- updateButtonsAndLabels();
-}
diff --git a/src/gui/windows/shopwindow.h b/src/gui/windows/shopwindow.h
deleted file mode 100644
index e96ab3de8..000000000
--- a/src/gui/windows/shopwindow.h
+++ /dev/null
@@ -1,207 +0,0 @@
-/*
- * The ManaPlus Client
- * Copyright (C) 2004-2009 The Mana World Development Team
- * Copyright (C) 2009-2010 The Mana Developers
- * Copyright (C) 2011-2017 The ManaPlus Developers
- *
- * This file is part of The ManaPlus Client.
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-#ifndef GUI_WINDOWS_SHOPWINDOW_H
-#define GUI_WINDOWS_SHOPWINDOW_H
-
-#include "gui/widgets/window.h"
-
-#include "listeners/actionlistener.h"
-#include "listeners/buyingstoremodelistener.h"
-#include "listeners/buyingstoreslotslistener.h"
-#include "listeners/selectionlistener.h"
-#include "listeners/vendingmodelistener.h"
-#include "listeners/vendingslotslistener.h"
-
-class Button;
-class CheckBox;
-class Item;
-class ScrollArea;
-class ShopItem;
-class ShopItems;
-class ShopListBox;
-class TabStrip;
-
-/**
- * The buy dialog.
- *
- * \ingroup Interface
- */
-class ShopWindow final : public Window,
- public VendingModeListener,
- public VendingSlotsListener,
- public BuyingStoreModeListener,
- public BuyingStoreSlotsListener,
- public ActionListener,
- public SelectionListener
-{
- public:
- enum ShopMode
- {
- BUY = 0,
- SELL = 1
- };
-
- /**
- * Constructor.
- *
- * @see Window::Window
- */
- ShopWindow();
-
- A_DELETE_COPY(ShopWindow)
-
- /**
- * Destructor
- */
- ~ShopWindow();
-
- void postInit() override final;
-
- /**
- * Called when receiving actions from the widgets.
- */
- void action(const ActionEvent &event) override final;
-
- /**
- * Updates the labels according to the selected item.
- */
- void valueChanged(const SelectionEvent &event) override final;
-
- /**
- * Updates the state of buttons and labels.
- */
- void updateButtonsAndLabels();
-
- /**
- * Sets the visibility of this window.
- */
- void setVisible(Visible visible) override final;
-
- /**
- * Returns true if any instances exist.
- */
- static bool isActive() A_WARN_UNUSED
- { return !instances.empty(); }
-
- void setItemSelected(const int id)
- { mSelectedItem = id; updateButtonsAndLabels(); }
-
- void addBuyItem(const Item *const item, const int amount,
- const int price);
-
- void addSellItem(const Item *const item, const int amount,
- const int price);
-
- void loadList();
-
- void saveList() const;
-
-#ifdef TMWA_SUPPORT
- void setAcceptPlayer(const std::string &name)
- { mAcceptPlayer = name; }
-
- const std::string &getAcceptPlayer() const noexcept2 A_WARN_UNUSED
- { return mAcceptPlayer; }
-
- void announce(ShopItems *const list, const int mode);
-
- void giveList(const std::string &nick, const int mode);
-
- void sendMessage(const std::string &nick, std::string data,
- const bool random = false);
-
- static void showList(const std::string &nick, std::string data);
-
- void processRequest(const std::string &nick, std::string data,
- const int mode);
- void updateTimes();
-
- static bool checkFloodCounter(time_t &counterTime) A_WARN_UNUSED;
-
- bool findShopItem(const ShopItem *const shopItem,
- const int mode) const A_WARN_UNUSED;
-#endif // TMWA_SUPPORT
-
- static int sumAmount(const Item *const shopItem) A_WARN_UNUSED;
-
- bool isShopEmpty() const A_WARN_UNUSED;
-
- void vendingEnabled(const bool b) override final;
-
- void vendingSlotsChanged(const int slots) override final;
-
- void buyingStoreEnabled(const bool b) override final;
-
- void buyingStoreSlotsChanged(const int slots) override final;
-
- void setShopName(const std::string &name);
-
- private:
-#ifdef TMWA_SUPPORT
- void startTrade();
-#endif // TMWA_SUPPORT
-
- void updateSelection();
-
- void updateShopName();
-
- typedef std::list<ShopWindow*> DialogList;
- static DialogList instances;
-
- Button *mCloseButton A_NONNULLPOINTER;
-
- ShopItems *mBuyShopItems A_NONNULLPOINTER;
- ShopItems *mSellShopItems A_NONNULLPOINTER;
- ShopItem *mTradeItem;
-
- ShopListBox *mBuyShopItemList A_NONNULLPOINTER;
- ShopListBox *mSellShopItemList A_NONNULLPOINTER;
- ShopListBox *mCurrentShopItemList;
- ScrollArea *mScrollArea A_NONNULLPOINTER;
- Button *mAddButton A_NONNULLPOINTER;
- Button *mDeleteButton A_NONNULLPOINTER;
- Button *mAnnounceButton;
- Button *mPublishButton;
- Button *mRenameButton;
- CheckBox *mAnnounceLinks;
- TabStrip *mTabs;
- std::string mAcceptPlayer;
- std::string mTradeNick;
- std::string mSellShopName;
- int mSelectedItem;
- time_t mAnnonceTime;
- time_t mLastRequestTimeList;
- time_t mLastRequestTimeItem;
- int mRandCounter;
- int mTradeMoney;
- int mSellShopSize;
- int mBuyShopSize;
- bool isBuySelected;
- bool mHaveVending;
- bool mEnableBuyingStore;
- bool mEnableVending;
-};
-
-extern ShopWindow *shopWindow;
-
-#endif // GUI_WINDOWS_SHOPWINDOW_H
diff --git a/src/gui/windows/shortcutwindow.cpp b/src/gui/windows/shortcutwindow.cpp
deleted file mode 100644
index 1bb35d3f1..000000000
--- a/src/gui/windows/shortcutwindow.cpp
+++ /dev/null
@@ -1,269 +0,0 @@
-/*
- * The ManaPlus Client
- * Copyright (C) 2007-2009 The Mana World Development Team
- * Copyright (C) 2009-2010 The Mana Developers
- * Copyright (C) 2011-2017 The ManaPlus Developers
- *
- * This file is part of The ManaPlus Client.
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-#include "gui/windows/shortcutwindow.h"
-
-#include "enums/gui/layouttype.h"
-
-#include "gui/windows/setupwindow.h"
-#include "gui/widgets/tabbedarea.h"
-
-#include "gui/widgets/button.h"
-#include "gui/widgets/createwidget.h"
-#include "gui/widgets/layout.h"
-#include "gui/widgets/scrollarea.h"
-#include "gui/widgets/shortcutcontainer.h"
-
-#include "gui/widgets/tabs/shortcuttab.h"
-
-#include "utils/delete2.h"
-#include "utils/foreach.h"
-
-#include "debug.h"
-
-ShortcutWindow *dropShortcutWindow = nullptr;
-ShortcutWindow *emoteShortcutWindow = nullptr;
-ShortcutWindow *itemShortcutWindow = nullptr;
-ShortcutWindow *spellShortcutWindow = nullptr;
-static const int SCROLL_PADDING = 0;
-
-int ShortcutWindow::mBoxesWidth = 0;
-
-ShortcutWindow::ShortcutWindow(const std::string &restrict title,
- ShortcutContainer *restrict const content,
- const std::string &restrict skinFile,
- int width, int height) :
- Window("Window", Modal_false, nullptr, skinFile),
- mItems(content),
- mScrollArea(new ScrollArea(this, mItems, Opaque_false)),
- mTabs(nullptr),
- mPages(),
- mButtonIndex(0)
-{
- setWindowName(title);
- setTitleBarHeight(getPadding() + getTitlePadding());
-
- setShowTitle(false);
- setResizable(true);
- setDefaultVisible(false);
- setSaveVisible(true);
- setAllowClose(true);
-
- mDragOffsetX = 0;
- mDragOffsetY = 0;
-
- if (content != nullptr)
- content->setWidget2(this);
- if (setupWindow != nullptr)
- setupWindow->registerWindowForReset(this);
-
- setMinWidth(32);
- setMinHeight(32);
- const int border = SCROLL_PADDING * 2 + getPadding() * 2;
- if (mItems != nullptr)
- {
- const int bw = mItems->getBoxWidth();
- const int bh = mItems->getBoxHeight();
- const int maxItems = mItems->getMaxItems();
- setMaxWidth(bw * maxItems + border);
- setMaxHeight(bh * maxItems + border);
-
- if (width == 0)
- width = bw + border;
- if (height == 0)
- height = bh * maxItems + border;
-
- setDefaultSize(width, height, ImagePosition::LOWER_RIGHT);
-
- mBoxesWidth += bw + border;
- }
-
- mScrollArea->setPosition(SCROLL_PADDING, SCROLL_PADDING);
- mScrollArea->setHorizontalScrollPolicy(ScrollArea::SHOW_NEVER);
-
- place(0, 0, mScrollArea, 5, 5).setPadding(0);
-
- Layout &layout = getLayout();
- layout.setRowHeight(0, LayoutType::SET);
- layout.setMargin(0);
-
- loadWindowState();
- enableVisibleSound(true);
-}
-
-ShortcutWindow::ShortcutWindow(const std::string &restrict title,
- const std::string &restrict skinFile,
- const int width, const int height) :
- Window("Window", Modal_false, nullptr, skinFile),
- mItems(nullptr),
- mScrollArea(nullptr),
- mTabs(CREATEWIDGETR(TabbedArea, this)),
- mPages(),
- mButtonIndex(0)
-{
- setWindowName(title);
- setTitleBarHeight(getPadding() + getTitlePadding());
- setShowTitle(false);
- setResizable(true);
- setDefaultVisible(false);
- setSaveVisible(true);
- setAllowClose(true);
-
- mDragOffsetX = 0;
- mDragOffsetY = 0;
-
- if (setupWindow != nullptr)
- setupWindow->registerWindowForReset(this);
-
- if ((width != 0) && (height != 0))
- setDefaultSize(width, height, ImagePosition::LOWER_RIGHT);
-
- setMinWidth(32);
- setMinHeight(32);
-
- place(0, 0, mTabs, 5, 5);
-
- Layout &layout = getLayout();
- layout.setRowHeight(0, LayoutType::SET);
- layout.setMargin(0);
-
- loadWindowState();
- enableVisibleSound(true);
-}
-
-ShortcutWindow::~ShortcutWindow()
-{
- if (mTabs != nullptr)
- mTabs->removeAll();
- delete2(mTabs);
- delete2(mItems);
-}
-
-void ShortcutWindow::addButton(const std::string &text,
- const std::string &eventName,
- ActionListener *const listener)
-{
- place(mButtonIndex++, 5, new Button(this, text, eventName, listener));
- Window::widgetResized(Event(nullptr));
-}
-
-void ShortcutWindow::addTab(const std::string &name,
- ShortcutContainer *const content)
-{
- if ((content == nullptr) || (mTabs == nullptr))
- return;
- ScrollArea *const scroll = new ScrollArea(this, content, Opaque_false);
- scroll->setPosition(SCROLL_PADDING, SCROLL_PADDING);
- scroll->setHorizontalScrollPolicy(ScrollArea::SHOW_NEVER);
- content->setWidget2(this);
- Tab *const tab = new ShortcutTab(this, name, content);
- mTabs->addTab(tab, scroll);
- mPages.push_back(content);
-}
-
-int ShortcutWindow::getTabIndex() const
-{
- if (mTabs == nullptr)
- return 0;
- return mTabs->getSelectedTabIndex();
-}
-
-void ShortcutWindow::widgetHidden(const Event &event)
-{
- Window::widgetHidden(event);
- if (mItems != nullptr)
- mItems->widgetHidden(event);
- if (mTabs != nullptr)
- {
- ScrollArea *const scroll = static_cast<ScrollArea *>(
- mTabs->getCurrentWidget());
- if (scroll != nullptr)
- {
- ShortcutContainer *const content = static_cast<ShortcutContainer*>(
- scroll->getContent());
-
- if (content != nullptr)
- content->widgetHidden(event);
- }
- }
-}
-
-void ShortcutWindow::mousePressed(MouseEvent &event)
-{
- Window::mousePressed(event);
-
- if (event.isConsumed())
- return;
-
- if (event.getButton() == MouseButton::LEFT)
- {
- mDragOffsetX = event.getX();
- mDragOffsetY = event.getY();
- }
-}
-
-void ShortcutWindow::mouseDragged(MouseEvent &event)
-{
- Window::mouseDragged(event);
-
- if (event.isConsumed())
- return;
-
- if (canMove() && isMovable() && mMoved)
- {
- int newX = std::max(0, getX() + event.getX() - mDragOffsetX);
- int newY = std::max(0, getY() + event.getY() - mDragOffsetY);
- newX = std::min(mainGraphics->mWidth - getWidth(), newX);
- newY = std::min(mainGraphics->mHeight - getHeight(), newY);
- setPosition(newX, newY);
- }
-}
-
-void ShortcutWindow::widgetMoved(const Event& event)
-{
- Window::widgetMoved(event);
- if (mItems != nullptr)
- mItems->setRedraw(true);
- FOR_EACH (STD_VECTOR<ShortcutContainer*>::iterator, it, mPages)
- (*it)->setRedraw(true);
-}
-
-void ShortcutWindow::nextTab()
-{
- if (mTabs != nullptr)
- mTabs->selectNextTab();
-}
-
-void ShortcutWindow::prevTab()
-{
- if (mTabs != nullptr)
- mTabs->selectPrevTab();
-}
-
-#ifdef USE_PROFILER
-void ShortcutWindow::logicChildren()
-{
- BLOCK_START("ShortcutWindow::logicChildren")
- BasicContainer::logicChildren();
- BLOCK_END("ShortcutWindow::logicChildren")
-}
-#endif // USE_PROFILER
diff --git a/src/gui/windows/shortcutwindow.h b/src/gui/windows/shortcutwindow.h
deleted file mode 100644
index f21c505c5..000000000
--- a/src/gui/windows/shortcutwindow.h
+++ /dev/null
@@ -1,100 +0,0 @@
-/*
- * The ManaPlus Client
- * Copyright (C) 2007-2009 The Mana World Development Team
- * Copyright (C) 2009-2010 The Mana Developers
- * Copyright (C) 2011-2017 The ManaPlus Developers
- *
- * This file is part of The ManaPlus Client.
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-#ifndef GUI_WINDOWS_SHORTCUTWINDOW_H
-#define GUI_WINDOWS_SHORTCUTWINDOW_H
-
-#include "gui/widgets/window.h"
-
-class ScrollArea;
-class ShortcutContainer;
-class TabbedArea;
-
-/**
- * A window around a ShortcutContainer.
- *
- * \ingroup Interface
- */
-class ShortcutWindow final : public Window
-{
- public:
- /**
- * Constructor.
- */
- ShortcutWindow(const std::string &restrict title,
- ShortcutContainer *restrict const content,
- const std::string &restrict skinFile = "",
- int width = 0, int height = 0);
-
- explicit ShortcutWindow(const std::string &restrict title,
- const std::string &restrict skinFile = "",
- const int width = 0, const int height = 0);
-
- A_DELETE_COPY(ShortcutWindow)
-
- /**
- * Destructor.
- */
- ~ShortcutWindow();
-
- void addTab(const std::string &name, ShortcutContainer *const content);
-
- int getTabIndex() const A_WARN_UNUSED;
-
- void widgetHidden(const Event &event) override final;
-
- void widgetMoved(const Event& event) override final;
-
- void mousePressed(MouseEvent &event) override final;
-
- void mouseDragged(MouseEvent &event) override final;
-
- void nextTab();
-
- void prevTab();
-
- void addButton(const std::string &text,
- const std::string &eventName,
- ActionListener *const listener);
-
-#ifdef USE_PROFILER
- void logicChildren();
-#endif // USE_PROFILER
-
- private:
- ShortcutWindow();
- ShortcutContainer *mItems;
-
- ScrollArea *mScrollArea A_NONNULLPOINTER;
- TabbedArea *mTabs;
- STD_VECTOR<ShortcutContainer*> mPages;
- int mButtonIndex;
-
- static int mBoxesWidth;
-};
-
-extern ShortcutWindow *dropShortcutWindow;
-extern ShortcutWindow *emoteShortcutWindow;
-extern ShortcutWindow *itemShortcutWindow;
-extern ShortcutWindow *spellShortcutWindow;
-
-#endif // GUI_WINDOWS_SHORTCUTWINDOW_H
diff --git a/src/gui/windows/skilldialog.cpp b/src/gui/windows/skilldialog.cpp
deleted file mode 100644
index 9f11605ef..000000000
--- a/src/gui/windows/skilldialog.cpp
+++ /dev/null
@@ -1,1432 +0,0 @@
-/*
- * The ManaPlus Client
- * Copyright (C) 2004-2009 The Mana World Development Team
- * Copyright (C) 2009-2010 The Mana Developers
- * Copyright (C) 2011-2017 The ManaPlus Developers
- *
- * This file is part of The ManaPlus Client.
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-#include "gui/windows/skilldialog.h"
-
-#include "configuration.h"
-#include "effectmanager.h"
-#include "spellmanager.h"
-
-#include "being/localplayer.h"
-#include "being/playerinfo.h"
-
-#include "const/resources/spriteaction.h"
-
-#include "enums/resources/skill/skillsettype.h"
-
-#include "gui/shortcut/itemshortcut.h"
-
-#include "gui/windows/setupwindow.h"
-#include "gui/windows/shortcutwindow.h"
-
-#include "gui/widgets/button.h"
-#include "gui/widgets/createwidget.h"
-#include "gui/widgets/label.h"
-#include "gui/widgets/scrollarea.h"
-#include "gui/widgets/tabbedarea.h"
-
-#include "gui/widgets/tabs/skilltab.h"
-
-#include "gui/windows/textdialog.h"
-
-#include "listeners/textskilllistener.h"
-
-#include "net/playerhandler.h"
-#include "net/skillhandler.h"
-
-#include "utils/checkutils.h"
-#include "utils/dtor.h"
-#include "utils/gettext.h"
-#include "utils/timer.h"
-
-#include "resources/beingcommon.h"
-
-#include "debug.h"
-
-SkillDialog *skillDialog = nullptr;
-
-namespace
-{
- TextSkillListener textSkillListener;
-} // namespace
-
-static SkillOwner::Type parseOwner(const std::string &str)
-{
- if (str == "player")
- return SkillOwner::Player;
- else if (str == "mercenary")
- return SkillOwner::Mercenary;
- else if (str == "homunculus")
- return SkillOwner::Homunculus;
- return SkillOwner::Player;
-}
-
-SkillDialog::SkillDialog() :
- // TRANSLATORS: skills dialog name
- Window(_("Skills"), Modal_false, nullptr, "skills.xml"),
- ActionListener(),
- mSkills(),
- mDurations(),
- mTabs(CREATEWIDGETR(TabbedArea, this)),
- mDeleteTabs(),
- mPointsLabel(new Label(this, "0")),
- // TRANSLATORS: skills dialog button
- mUseButton(new Button(this, _("Use"), "use", this)),
- // TRANSLATORS: skills dialog button
- mIncreaseButton(new Button(this, _("Up"), "inc", this)),
- mDefaultModel(nullptr),
- mDefaultTab(nullptr)
-{
- setWindowName("Skills");
- setCloseButton(true);
- setResizable(true);
- setSaveVisible(true);
- setStickyButtonLock(true);
- setDefaultSize(windowContainer->getWidth() - 280, 30, 275, 425);
- if (setupWindow != nullptr)
- setupWindow->registerWindowForReset(this);
-
- mUseButton->setEnabled(false);
- mIncreaseButton->setEnabled(false);
- mTabs->setSelectable(false);
- mTabs->getTabContainer()->setSelectable(false);
- mTabs->getWidgetContainer()->setSelectable(false);
-
- place(0, 0, mTabs, 5, 5);
- place(0, 5, mPointsLabel, 4);
- place(3, 5, mUseButton);
- place(4, 5, mIncreaseButton);
-}
-
-void SkillDialog::postInit()
-{
- Window::postInit();
- setLocationRelativeTo(getParent());
- loadWindowState();
- enableVisibleSound(true);
-}
-
-SkillDialog::~SkillDialog()
-{
- clearSkills();
-}
-
-void SkillDialog::addDefaultTab()
-{
- mDefaultModel = new SkillModel;
- SkillListBox *const listbox = new SkillListBox(this,
- mDefaultModel);
- listbox->setActionEventId("sel");
- listbox->addActionListener(this);
- ScrollArea *const scroll = new ScrollArea(this,
- listbox,
- Opaque_false);
- scroll->setHorizontalScrollPolicy(ScrollArea::SHOW_NEVER);
- scroll->setVerticalScrollPolicy(ScrollArea::SHOW_ALWAYS);
- // TRANSLATORS: unknown skills tab name
- mDefaultTab = new SkillTab(this, _("Unknown"), listbox);
- mDeleteTabs.push_back(mDefaultTab);
- mDefaultTab->setVisible(Visible_false);
- mTabs->addTab(mDefaultTab, scroll);
- mTabs->adjustTabPositions();
- mTabs->setSelectedTabDefault();
-}
-
-void SkillDialog::action(const ActionEvent &event)
-{
- const std::string &eventId = event.getId();
- if (eventId == "inc")
- {
- if (playerHandler == nullptr)
- return;
- const SkillTab *const tab = static_cast<const SkillTab *>(
- mTabs->getSelectedTab());
- if (tab != nullptr)
- {
- if (const SkillInfo *const info = tab->getSelectedInfo())
- playerHandler->increaseSkill(CAST_U16(info->id));
- }
- }
- else if (eventId == "sel")
- {
- const SkillTab *const tab = static_cast<const SkillTab *>(
- mTabs->getSelectedTab());
- if (tab != nullptr)
- {
- if (const SkillInfo *const info = tab->getSelectedInfo())
- {
- mUseButton->setEnabled(info->isUsable());
- mUseButton->setCaption(info->useButton);
- mIncreaseButton->setEnabled(info->id < SKILL_VAR_MIN_ID);
- const int num = itemShortcutWindow->getTabIndex();
- if (num >= 0 && num < CAST_S32(SHORTCUT_TABS)
- && (itemShortcut[num] != nullptr))
- {
- itemShortcut[num]->setItemSelected(
- info->id + SKILL_MIN_ID);
- }
- }
- else
- {
- mUseButton->setEnabled(false);
- mIncreaseButton->setEnabled(false);
- // TRANSLATORS: skills dialog button
- mUseButton->setCaption(_("Use"));
- }
- }
- }
- else if (eventId == "use")
- {
- const SkillTab *const tab = static_cast<const SkillTab *>(
- mTabs->getSelectedTab());
- if (tab != nullptr)
- {
- const SkillInfo *const info = tab->getSelectedInfo();
- if (info == nullptr)
- return;
- useSkill(info,
- fromBool(config.getBoolValue("skillAutotarget"), AutoTarget),
- info->customSelectedLevel,
- info->useTextParameter,
- std::string(),
- info->customCastType,
- info->customOffsetX,
- info->customOffsetY);
- }
- }
- else if (eventId == "close")
- {
- setVisible(Visible_false);
- }
-}
-
-std::string SkillDialog::update(const int id)
-{
- const SkillMap::const_iterator i = mSkills.find(id);
-
- if (i != mSkills.end())
- {
- SkillInfo *const info = i->second;
- if (info != nullptr)
- {
- info->update();
- return info->data->name;
- }
- }
-
- return std::string();
-}
-
-void SkillDialog::update()
-{
- // TRANSLATORS: skills dialog label
- mPointsLabel->setCaption(strprintf(_("Skill points available: %d"),
- PlayerInfo::getAttribute(Attributes::PLAYER_SKILL_POINTS)));
- mPointsLabel->adjustSize();
-
- ItemShortcut *const shortcuts = itemShortcut[SHORTCUT_AUTO_TAB];
- shortcuts->clear();
- size_t idx = 0;
-
- FOR_EACH (SkillMap::const_iterator, it, mSkills)
- {
- SkillInfo *const info = (*it).second;
- if (info == nullptr)
- continue;
- if (info->modifiable == Modifiable_true)
- info->update();
- if (info->visible == Visible_false ||
- idx >= SHORTCUT_ITEMS ||
- !info->data->autoTab)
- {
- continue;
- }
- const SkillType::SkillType type = info->type;
- if (type == SkillType::Attack ||
- type == SkillType::Ground ||
- type == SkillType::Self ||
- type == SkillType::Support)
- {
- shortcuts->setItemFast(idx,
- info->id + SKILL_MIN_ID,
- fromInt(info->customSelectedLevel, ItemColor));
-
- shortcuts->setItemData(idx,
- info->toDataStr());
- idx ++;
- }
- }
-
- skillPopup->reset();
-}
-
-void SkillDialog::updateModels()
-{
- std::set<SkillModel*> models;
-
- FOR_EACH (SkillMap::const_iterator, it, mSkills)
- {
- SkillInfo *const info = (*it).second;
- if (info != nullptr)
- {
- SkillModel *const model = info->model;
- if (model != nullptr)
- models.insert(model);
- }
- }
- FOR_EACH (std::set<SkillModel*>::iterator, it, models)
- {
- SkillModel *const model = *it;
- if (model != nullptr)
- model->updateVisibilities();
- }
-}
-
-void SkillDialog::clearSkills()
-{
- mTabs->removeAll();
- mDeleteTabs.clear();
- mDefaultTab = nullptr;
- mDefaultModel = nullptr;
-
- delete_all(mSkills);
- mSkills.clear();
- mDurations.clear();
-}
-
-void SkillDialog::hideSkills(const SkillOwner::Type owner)
-{
- FOR_EACH (SkillMap::iterator, it, mSkills)
- {
- SkillInfo *const info = (*it).second;
- if ((info != nullptr) && info->owner == owner)
- {
- PlayerInfo::setSkillLevel(info->id, 0);
- if (info->alwaysVisible == Visible_false)
- info->visible = Visible_false;
- }
- }
-}
-
-void SkillDialog::loadSkills()
-{
- clearSkills();
- loadXmlFile(paths.getStringValue("skillsFile"), SkipError_false);
- if (mSkills.empty())
- loadXmlFile(paths.getStringValue("skillsFile2"), SkipError_false);
- loadXmlFile(paths.getStringValue("skillsPatchFile"), SkipError_true);
- loadXmlDir("skillsPatchDir", loadXmlFile);
- addDefaultTab();
-
- update();
-}
-
-void SkillDialog::loadXmlFile(const std::string &fileName,
- const SkipError skipError)
-{
- XML::Document doc(fileName,
- UseVirtFs_true,
- skipError);
- XmlNodePtrConst root = doc.rootNode();
-
- int setCount = 0;
-
- if ((root == nullptr) || !xmlNameEqual(root, "skills"))
- {
- logger->log("Error loading skills: " + fileName);
- return;
- }
-
- for_each_xml_child_node(set, root)
- {
- if (xmlNameEqual(set, "include"))
- {
- const std::string name = XML::getProperty(set, "name", "");
- if (!name.empty())
- loadXmlFile(name, skipError);
- continue;
- }
- else if (xmlNameEqual(set, "set"))
- {
- setCount++;
- const std::string setName = XML::getProperty(set, "name",
- // TRANSLATORS: skills dialog default skill tab
- strprintf(_("Skill Set %d"), setCount));
-
- const std::string setTypeStr = XML::getProperty(set, "type", "");
- SkillSetTypeT setType = SkillSetType::VerticalList;
- if (setTypeStr.empty() ||
- setTypeStr == "list" ||
- setTypeStr == "vertical")
- {
- setType = SkillSetType::VerticalList;
- }
- else if (setTypeStr == "rectangle")
- {
- setType = SkillSetType::Rectangle;
- }
-
- bool alwaysVisible = false;
- SkillModel *const model = new SkillModel;
- SkillTab *tab = nullptr;
- ScrollArea *scroll = nullptr;
-
- switch (setType)
- {
- case SkillSetType::VerticalList:
- {
- // possible leak listbox, scroll
- SkillListBox *const listbox = new SkillListBox(this,
- model);
- listbox->setActionEventId("sel");
- listbox->addActionListener(this);
- scroll = new ScrollArea(this,
- listbox,
- Opaque_false);
- scroll->setHorizontalScrollPolicy(ScrollArea::SHOW_NEVER);
- scroll->setVerticalScrollPolicy(ScrollArea::SHOW_ALWAYS);
- tab = new SkillTab(this, setName, listbox);
- break;
- }
- case SkillSetType::Rectangle:
- {
- SkillRectangleListBox *const listbox =
- new SkillRectangleListBox(this,
- model);
- listbox->setActionEventId("sel");
- listbox->addActionListener(this);
- scroll = new ScrollArea(this,
- listbox,
- Opaque_false);
- scroll->setHorizontalScrollPolicy(ScrollArea::SHOW_NEVER);
- scroll->setVerticalScrollPolicy(ScrollArea::SHOW_ALWAYS);
- tab = new SkillTab(this, setName, listbox);
- break;
- }
- default:
- reportAlways("Unsupported skillset type: %s",
- setTypeStr.c_str());
- return;
- }
- if (mDefaultModel == nullptr)
- {
- mDefaultModel = model;
- mDefaultTab = tab;
- }
-
- mDeleteTabs.push_back(tab);
- if (alwaysVisible == true)
- tab->setVisible(Visible_true);
- else
- tab->setVisible(Visible_false);
- mTabs->addTab(tab, scroll);
-
- for_each_xml_child_node(node, set)
- {
- if (xmlNameEqual(node, "skill"))
- {
- SkillInfo *const skill = loadSkill(node, model);
- if (skill == nullptr)
- continue;
- if (skill->alwaysVisible == Visible_true)
- alwaysVisible = true;
- skill->tab = tab;
- for_each_xml_child_node(levelNode, node)
- {
- if (!xmlNameEqual(levelNode, "level"))
- continue;
- loadSkillData(node, skill);
- }
- }
- }
-
- model->updateVisibilities();
- }
- }
-}
-
-SkillInfo *SkillDialog::loadSkill(XmlNodeConstPtr node,
- SkillModel *const model)
-{
- int id = XML::getIntProperty(node, "id", -1, -1, 1000000);
- if (id == -1)
- {
- id = XML::getIntProperty(node, "var", -1, -1, 100000);
- if (id == -1)
- return nullptr;
- id += SKILL_VAR_MIN_ID;
- }
-
- SkillInfo *skill = getSkill(id);
- if (skill == nullptr)
- {
- std::string name = XML::langProperty(node, "name",
- // TRANSLATORS: skills dialog. skill id
- strprintf(_("Skill %d"), id));
-
- skill = new SkillInfo;
- skill->id = CAST_U32(id);
- skill->modifiable = Modifiable_false;
- skill->model = model;
- skill->update();
- skill->useButton = XML::getProperty(
- // TRANSLATORS: skills dialog button
- node, "useButton", _("Use"));
- skill->owner = parseOwner(XML::getProperty(
- node, "owner", "player"));
- skill->errorText = XML::getProperty(
- node, "errorText", name);
- skill->alwaysVisible = fromBool(XML::getBoolProperty(
- node, "alwaysVisible", false), Visible);
- skill->castingAction = XML::getProperty(node,
- "castingAction", SpriteAction::CAST);
- skill->castingRideAction = XML::getProperty(node,
- "castingRideAction", SpriteAction::CASTRIDE);
- skill->castingSkyAction = XML::getProperty(node,
- "castingSkyAction", SpriteAction::CASTSKY);
- skill->castingWaterAction = XML::getProperty(node,
- "castingWaterAction", SpriteAction::CASTWATER);
- skill->useTextParameter = XML::getBoolProperty(
- node, "useTextParameter", false);
- skill->x = XML::getProperty(node,
- "x", 0);
- skill->y = XML::getProperty(node,
- "y", 0);
- skill->visible = skill->alwaysVisible;
- model->addSkill(skill);
- mSkills[id] = skill;
- }
-
- loadSkillData(node, skill);
- return skill;
-}
-
-void SkillDialog::loadSkillData(XmlNodeConstPtr node,
- SkillInfo *const skill)
-{
- if (skill == nullptr)
- return;
- const int level = (skill->alwaysVisible == Visible_true) ?
- 0 : XML::getProperty(node, "level", 0);
- SkillData *data = skill->getData(level);
- if (data == nullptr)
- data = new SkillData;
-
- const std::string name = XML::langProperty(node, "name",
- // TRANSLATORS: skills dialog. skill id
- strprintf(_("Skill %u"), skill->id));
- data->name = name;
- const std::string icon = XML::getProperty(node, "icon", "");
- if (icon.empty())
- {
- data->setIcon(paths.getStringValue("missingSkillIcon"));
- data->haveIcon = false;
- }
- else
- {
- data->setIcon(icon);
- data->haveIcon = true;
- }
- if (skill->id < SKILL_VAR_MIN_ID)
- {
- data->dispName = strprintf("%s, %u",
- name.c_str(),
- skill->id);
- }
- else
- {
- data->dispName = strprintf("%s, (%u)",
- name.c_str(),
- skill->id - SKILL_VAR_MIN_ID);
- }
- data->shortName = XML::langProperty(node,
- "shortName", name.substr(0, 3));
- data->description = XML::langProperty(
- node, "description", "");
-
- MissileInfo &missile = data->missile;
- missile.particle = XML::getProperty(
- node, "missile-particle", "");
- missile.z = XML::getFloatProperty(
- node, "missile-z", 32.0f);
- missile.lifeTime = XML::getProperty(
- node, "missile-lifetime", 500);
- missile.speed = XML::getFloatProperty(
- node, "missile-speed", 7.0f);
- missile.dieDistance = XML::getFloatProperty(
- node, "missile-diedistance", 8.0f);
-
- MissileInfo &castingMissile = data->castingMissile;
- castingMissile.particle = XML::getProperty(
- node, "castingMissile-particle", "");
- castingMissile.z = XML::getFloatProperty(
- node, "castingMissile-z", 32.0f);
- castingMissile.lifeTime = XML::getProperty(
- node, "castingMissile-lifetime", 500);
- castingMissile.speed = XML::getFloatProperty(
- node, "castingMissile-speed", 7.0f);
- castingMissile.dieDistance = XML::getFloatProperty(
- node, "castingMissile-diedistance", 8.0f);
-
- data->castingAnimation = XML::getProperty(
- node,
- "castingAnimation",
- paths.getStringValue("skillCastingAnimation"));
-
- data->soundHit.sound = XML::getProperty(
- node, "soundHit", "");
- data->soundHit.delay = XML::getProperty(
- node, "soundHitDelay", 0);
- data->soundMiss.sound = XML::getProperty(
- node, "soundMiss", "");
- data->soundMiss.delay = XML::getProperty(
- node, "soundMissDelay", 0);
- data->invokeCmd = XML::getProperty(
- node, "invokeCmd", "");
- data->updateEffectId = XML::getProperty(
- node, "levelUpEffectId", -1);
- data->removeEffectId = XML::getProperty(
- node, "removeEffectId", -1);
- data->hitEffectId = XML::getProperty(
- node, "hitEffectId", -1);
- data->missEffectId = XML::getProperty(
- node, "missEffectId", -1);
- data->castingSrcEffectId = XML::getProperty(
- node, "castingSrcEffectId", -1);
- data->castingDstEffectId = XML::getProperty(
- node, "castingDstEffectId", -1);
- data->srcEffectId = XML::getProperty(
- node, "srcEffectId", -1);
- data->dstEffectId = XML::getProperty(
- node, "dstEffectId", -1);
- data->castingGroundEffectId = XML::getProperty(
- node, "castingGroundEffectId", -1);
- data->autoTab = XML::getBoolProperty(
- node, "autoTab", true);
-
- skill->addData(level, data);
-}
-
-void SkillDialog::removeSkill(const int id)
-{
- const SkillMap::const_iterator it = mSkills.find(id);
-
- if (it != mSkills.end())
- {
- SkillInfo *const info = it->second;
- if (info != nullptr)
- {
- info->level = 0;
- info->update();
- PlayerInfo::setSkillLevel(id, 0);
- if (info->alwaysVisible == Visible_false)
- info->visible = Visible_false;
- }
- }
-}
-
-bool SkillDialog::updateSkill(const int id,
- const int range,
- const Modifiable modifiable,
- const SkillType::SkillType type,
- const int sp)
-{
- const SkillMap::const_iterator it = mSkills.find(id);
-
- if (it != mSkills.end())
- {
- SkillInfo *const info = it->second;
- if (info != nullptr)
- {
- info->modifiable = modifiable;
- info->range = range;
- info->type = type;
- info->sp = sp;
- info->update();
- if (info->tab != nullptr)
- {
- info->tab->setVisible(Visible_true);
- mTabs->adjustTabPositions();
- mTabs->setSelectedTabDefault();
- }
- }
- return true;
- }
- return false;
-}
-
-std::string SkillDialog::getDefaultSkillIcon(const SkillType::SkillType type)
-{
- std::string icon;
- switch (type)
- {
- case SkillType::Attack:
- icon = paths.getStringValue("attackSkillIcon");
- break;
- case SkillType::Ground:
- icon = paths.getStringValue("groundSkillIcon");
- break;
- case SkillType::Self:
- icon = paths.getStringValue("selfSkillIcon");
- break;
- case SkillType::Unused:
- icon = paths.getStringValue("unusedSkillIcon");
- break;
- case SkillType::Support:
- icon = paths.getStringValue("supportSkillIcon");
- break;
- case SkillType::TargetTrap:
- icon = paths.getStringValue("trapSkillIcon");
- break;
- case SkillType::Unknown:
- icon = paths.getStringValue("unknownSkillIcon");
- break;
- default:
- break;
- }
- return icon;
-}
-
-void SkillDialog::addSkill(const SkillOwner::Type owner,
- const int id,
- const std::string &name,
- const int level,
- const int range,
- const Modifiable modifiable,
- const SkillType::SkillType type,
- const int sp)
-{
- if (mDefaultModel != nullptr)
- {
- SkillInfo *const skill = new SkillInfo;
- skill->id = CAST_U32(id);
- skill->type = type;
- skill->owner = owner;
- SkillData *const data = skill->data;
- if (name.empty())
- {
- data->name = "Unknown skill Id: " + toString(id);
- data->dispName = data->name;
- }
- else
- {
- data->name = name;
- data->dispName = strprintf("%s, %u", name.c_str(), skill->id);
- }
- data->description.clear();
- const std::string icon = getDefaultSkillIcon(type);
- if (icon.empty())
- {
- data->setIcon(paths.getStringValue("missingSkillIcon"));
- data->haveIcon = false;
- }
- else
- {
- data->setIcon(icon);
- data->haveIcon = true;
- }
- data->autoTab = settings.unknownSkillsAutoTab;
- data->shortName = toString(skill->id);
- skill->modifiable = modifiable;
- skill->visible = Visible_false;
- skill->alwaysVisible = Visible_false;
- skill->model = mDefaultModel;
- skill->level = level;
- // TRANSLATORS: skills dialog. skill level
- skill->skillLevel = strprintf(_("Lvl: %d"), level);
- skill->range = range;
- skill->sp = sp;
- skill->update();
- // TRANSLATORS: skills dialog button
- skill->useButton = _("Use");
- // TRANSLATORS: skill error message
- skill->errorText = strprintf(_("Failed skill: %s"), name.c_str());
- skill->tab = mDefaultTab;
- mDefaultModel->addSkill(skill);
- mDefaultTab->setVisible(Visible_true);
- mTabs->adjustTabPositions();
- mTabs->setSelectedTabDefault();
-
- mSkills[id] = skill;
- mDefaultModel->updateVisibilities();
- }
-}
-
-SkillInfo* SkillDialog::getSkill(const int id) const
-{
- SkillMap::const_iterator it = mSkills.find(id);
- if (it != mSkills.end())
- return (*it).second;
- return nullptr;
-}
-
-SkillInfo* SkillDialog::getSkillByItem(const int itemId) const
-{
- SkillMap::const_iterator it = mSkills.find(itemId - SKILL_MIN_ID);
- if (it != mSkills.end())
- return (*it).second;
- return nullptr;
-}
-
-void SkillDialog::setSkillDuration(const SkillOwner::Type owner,
- const int id,
- const int duration)
-{
- SkillMap::const_iterator it = mSkills.find(id);
- SkillInfo *info = nullptr;
- if (it == mSkills.end())
- {
- addSkill(owner, id, "", 0, 0, Modifiable_false, SkillType::Unknown, 0);
- it = mSkills.find(id);
- }
- if (it != mSkills.end())
- {
- info = (*it).second;
- }
- if (info != nullptr)
- {
- info->duration = duration;
- info->durationTime = tick_time;
- addSkillDuration(info);
- }
-}
-
-void SkillDialog::widgetResized(const Event &event)
-{
- Window::widgetResized(event);
-
- if (mTabs != nullptr)
- mTabs->adjustSize();
-}
-
-void SkillDialog::useItem(const int itemId,
- const AutoTarget autoTarget,
- const int level,
- const std::string &data) const
-{
- const std::map<int, SkillInfo*>::const_iterator
- it = mSkills.find(itemId - SKILL_MIN_ID);
- if (it == mSkills.end())
- return;
-
- const SkillInfo *const info = (*it).second;
- CastTypeT castType = CastType::Default;
- int offsetX = 0;
- int offsetY = 0;
-
- if (!data.empty())
- {
- STD_VECTOR<int> vect;
- splitToIntVector(vect, data, ' ');
- const size_t sz = vect.size();
- if (sz > 0)
- castType = static_cast<CastTypeT>(vect[0]);
- if (sz > 2)
- {
- offsetX = vect[1];
- offsetY = vect[2];
- }
- }
- useSkill(info,
- autoTarget,
- level,
- false,
- std::string(),
- castType,
- offsetX,
- offsetY);
-}
-
-void SkillDialog::updateTabSelection()
-{
- const SkillTab *const tab = static_cast<SkillTab*>(
- mTabs->getSelectedTab());
- if (tab != nullptr)
- {
- if (const SkillInfo *const info = tab->getSelectedInfo())
- {
- mUseButton->setEnabled(info->range > 0);
- mIncreaseButton->setEnabled(info->id < SKILL_VAR_MIN_ID);
- mUseButton->setCaption(info->useButton);
- }
- else
- {
- mUseButton->setEnabled(false);
- // TRANSLATORS: inventory button
- mUseButton->setCaption(_("Use"));
- }
- }
-}
-
-void SkillDialog::updateQuest(const int var,
- const int val1,
- const int val2 A_UNUSED,
- const int val3 A_UNUSED,
- const int time1 A_UNUSED)
-{
- const int id = var + SKILL_VAR_MIN_ID;
- const SkillMap::const_iterator it = mSkills.find(id);
-
- if (it != mSkills.end())
- {
- SkillInfo *const info = it->second;
- if (info != nullptr)
- {
- PlayerInfo::setSkillLevel(id, val1);
- info->level = val1;
- info->update();
- }
- }
-}
-
-SkillData *SkillDialog::getSkillData(const int id) const
-{
- const SkillMap::const_iterator it = mSkills.find(id);
- if (it != mSkills.end())
- {
- SkillInfo *const info = it->second;
- if (info != nullptr)
- return info->data;
- }
- return nullptr;
-}
-
-SkillData *SkillDialog::getSkillDataByLevel(const int id,
- const int level) const
-{
- const SkillMap::const_iterator it = mSkills.find(id);
- if (it != mSkills.end())
- {
- SkillInfo *const info = it->second;
- if (info != nullptr)
- return info->getData1(level);
- }
- return nullptr;
-}
-
-void SkillDialog::playUpdateEffect(const int id) const
-{
- if (effectManager == nullptr)
- return;
- const SkillData *const data = getSkillData(id);
- if (data == nullptr)
- return;
- effectManager->triggerDefault(data->updateEffectId,
- localPlayer,
- paths.getIntValue("skillLevelUpEffectId"));
-}
-
-void SkillDialog::playRemoveEffect(const int id) const
-{
- if (effectManager == nullptr)
- return;
- const SkillData *const data = getSkillData(id);
- if (data == nullptr)
- return;
- effectManager->triggerDefault(data->removeEffectId,
- localPlayer,
- paths.getIntValue("skillRemoveEffectId"));
-}
-
-void SkillDialog::playCastingDstTileEffect(const int id,
- const int level,
- const int x,
- const int y,
- const int delay) const
-{
- if (effectManager == nullptr)
- return;
- SkillData *const data = getSkillDataByLevel(id, level);
- if (data == nullptr)
- return;
- effectManager->triggerDefault(data->castingGroundEffectId,
- x * 32,
- y * 32,
- cur_time + delay / 1000, // end time in seconds
- paths.getIntValue("skillCastingGroundEffectId"));
-}
-
-void SkillDialog::useSkill(const int skillId,
- const AutoTarget autoTarget,
- int level,
- const bool withText,
- const std::string &text,
- CastTypeT castType,
- const int offsetX,
- const int offsetY)
-{
- SkillInfo *const info = skillDialog->getSkill(skillId);
- if (info == nullptr)
- return;
- if (castType == CastType::Default)
- castType = info->customCastType;
- useSkill(info,
- autoTarget,
- level,
- withText,
- text,
- castType,
- offsetX,
- offsetY);
-}
-
-void SkillDialog::useSkill(const SkillInfo *const info,
- const AutoTarget autoTarget,
- int level,
- const bool withText,
- const std::string &text,
- const CastTypeT castType,
- const int offsetX,
- const int offsetY)
-{
- if ((info == nullptr) || (localPlayer == nullptr))
- return;
- if (level == 0)
- level = info->level;
-
- const SkillData *data = info->getData1(level);
- if (data != nullptr)
- {
- const std::string cmd = data->invokeCmd;
- if (!cmd.empty())
- SpellManager::invokeCommand(cmd, localPlayer->getTarget());
- }
- switch (castType)
- {
- default:
- case CastType::Default:
- useSkillDefault(info,
- autoTarget,
- level,
- withText,
- text,
- offsetX,
- offsetY);
- break;
- case CastType::Target:
- {
- const Being *const being = localPlayer->getTarget();
- useSkillTarget(info,
- autoTarget,
- level,
- withText,
- text,
- being,
- offsetX,
- offsetY);
- break;
- }
- case CastType::Position:
- {
- int x = 0;
- int y = 0;
- viewport->getMouseTile(x, y);
- useSkillPosition(info,
- level,
- withText,
- text,
- x,
- y,
- offsetX,
- offsetY);
- break;
- }
- case CastType::Self:
- // +++ probably need call useSkillSelf
- useSkillTarget(info,
- autoTarget,
- level,
- withText,
- text,
- localPlayer,
- offsetX,
- offsetY);
- break;
- }
-}
-
-void SkillDialog::useSkillTarget(const SkillInfo *const info,
- const AutoTarget autoTarget,
- int level,
- const bool withText,
- const std::string &text,
- const Being *being,
- int offsetX,
- int offsetY)
-{
- SkillType::SkillType type = info->type;
- if ((type & SkillType::Attack) != 0)
- {
- if ((being == nullptr) && autoTarget == AutoTarget_true)
- {
- if (localPlayer != nullptr)
- {
- being = localPlayer->setNewTarget(ActorType::Monster,
- AllowSort_true);
- }
- }
- if (being != nullptr)
- {
- skillHandler->useBeing(info->id,
- level,
- being->getId());
- }
- }
- else if ((type & SkillType::Support) != 0)
- {
- if (being == nullptr)
- being = localPlayer;
- if (being != nullptr)
- {
- skillHandler->useBeing(info->id,
- level,
- being->getId());
- }
- }
- else if ((type & SkillType::Self) != 0)
- {
- skillHandler->useBeing(info->id,
- level,
- localPlayer->getId());
- }
- else if ((type & SkillType::Ground) != 0)
- {
- if (being == nullptr)
- return;
- being->fixDirectionOffsets(offsetX, offsetY);
- const int x = being->getTileX() + offsetX;
- const int y = being->getTileY() + offsetY;
- if (info->useTextParameter)
- {
- if (withText)
- {
- skillHandler->usePos(info->id,
- level,
- x, y,
- text);
- }
- else
- {
- const SkillData *data = info->getData1(level);
- textSkillListener.setSkill(info->id,
- x,
- y,
- level);
- TextDialog *const dialog = CREATEWIDGETR(TextDialog,
- // TRANSLATORS: text skill dialog header
- strprintf(_("Add text to skill %s"),
- data->name.c_str()),
- // TRANSLATORS: text skill dialog field
- _("Text: "));
- dialog->setModal(Modal_true);
- textSkillListener.setDialog(dialog);
- dialog->setActionEventId("ok");
- dialog->addActionListener(&textSkillListener);
- }
- }
- else
- {
- skillHandler->usePos(info->id,
- level,
- x, y);
- }
- }
- else if ((type & SkillType::TargetTrap) != 0)
- {
- // for now unused
- }
- else if (type == SkillType::Unknown ||
- type == SkillType::Unused)
- {
- // unknown / unused
- }
- else
- {
- reportAlways("Unsupported skill type: %d", type);
- }
-}
-
-void SkillDialog::useSkillPosition(const SkillInfo *const info,
- int level,
- const bool withText,
- const std::string &text,
- const int x,
- const int y,
- int offsetX,
- int offsetY)
-{
- SkillType::SkillType type = info->type;
- if ((type & SkillType::Ground) != 0)
- {
- localPlayer->fixDirectionOffsets(offsetX, offsetY);
- if (info->useTextParameter)
- {
- if (withText)
- {
- skillHandler->usePos(info->id,
- level,
- x + offsetX,
- y + offsetY,
- text);
- }
- else
- {
- const SkillData *data = info->getData1(level);
- textSkillListener.setSkill(info->id,
- x + offsetX,
- y + offsetY,
- level);
- TextDialog *const dialog = CREATEWIDGETR(TextDialog,
- // TRANSLATORS: text skill dialog header
- strprintf(_("Add text to skill %s"),
- data->name.c_str()),
- // TRANSLATORS: text skill dialog field
- _("Text: "));
- dialog->setModal(Modal_true);
- textSkillListener.setDialog(dialog);
- dialog->setActionEventId("ok");
- dialog->addActionListener(&textSkillListener);
- }
- }
- else
- {
- skillHandler->usePos(info->id,
- level,
- x + offsetX,
- y + offsetY);
- }
- }
- else if ((type & SkillType::Support) != 0)
- {
- // wrong type
- skillHandler->useBeing(info->id,
- level,
- localPlayer->getId());
- }
- else if ((type & SkillType::Self) != 0)
- {
- skillHandler->useBeing(info->id,
- level,
- localPlayer->getId());
- }
- else if ((type & SkillType::Attack) != 0)
- {
- // do nothing
- // +++ probably need select some target on x,y position?
- }
- else if ((type & SkillType::TargetTrap) != 0)
- {
- // for now unused
- }
- else if (type == SkillType::Unknown ||
- type == SkillType::Unused)
- {
- // unknown / unused
- }
- else
- {
- reportAlways("Unsupported skill type: %d", type);
- }
-}
-
-void SkillDialog::useSkillDefault(const SkillInfo *const info,
- const AutoTarget autoTarget,
- int level,
- const bool withText,
- const std::string &text,
- int offsetX,
- int offsetY)
-{
- SkillType::SkillType type = info->type;
- if ((type & SkillType::Attack) != 0)
- {
- const Being *being = localPlayer->getTarget();
- if ((being == nullptr) && autoTarget == AutoTarget_true)
- {
- being = localPlayer->setNewTarget(ActorType::Monster,
- AllowSort_true);
- }
- if (being != nullptr)
- {
- skillHandler->useBeing(info->id,
- level,
- being->getId());
- }
- }
- else if ((type & SkillType::Support) != 0)
- {
- const Being *being = localPlayer->getTarget();
- if (being == nullptr)
- being = localPlayer;
- if (being != nullptr)
- {
- skillHandler->useBeing(info->id,
- level,
- being->getId());
- }
- }
- else if ((type & SkillType::Self) != 0)
- {
- skillHandler->useBeing(info->id,
- level,
- localPlayer->getId());
- }
- else if ((type & SkillType::Ground) != 0)
- {
- int x = 0;
- int y = 0;
- viewport->getMouseTile(x, y);
- localPlayer->fixDirectionOffsets(offsetX, offsetY);
- x += offsetX;
- y += offsetY;
- if (info->useTextParameter)
- {
- if (withText)
- {
- skillHandler->usePos(info->id,
- level,
- x, y,
- text);
- }
- else
- {
- const SkillData *data = info->getData1(level);
- textSkillListener.setSkill(info->id,
- x,
- y,
- level);
- TextDialog *const dialog = CREATEWIDGETR(TextDialog,
- // TRANSLATORS: text skill dialog header
- strprintf(_("Add text to skill %s"),
- data->name.c_str()),
- // TRANSLATORS: text skill dialog field
- _("Text: "));
- dialog->setModal(Modal_true);
- textSkillListener.setDialog(dialog);
- dialog->setActionEventId("ok");
- dialog->addActionListener(&textSkillListener);
- }
- }
- else
- {
- skillHandler->usePos(info->id,
- level,
- x, y);
- }
- }
- else if ((type & SkillType::TargetTrap) != 0)
- {
- // for now unused
- }
- else if (type == SkillType::Unknown ||
- type == SkillType::Unused)
- {
- // unknown / unused
- }
- else
- {
- reportAlways("Unsupported skill type: %d", type);
- }
-}
-
-void SkillDialog::addSkillDuration(SkillInfo *const skill)
-{
- if (skill == nullptr)
- return;
-
- FOR_EACH (STD_VECTOR<SkillInfo*>::const_iterator, it, mDurations)
- {
- if ((*it)->id == skill->id)
- return;
- }
- mDurations.push_back(skill);
-}
-
-void SkillDialog::slowLogic()
-{
- FOR_EACH_SAFE (STD_VECTOR<SkillInfo*>::iterator, it, mDurations)
- {
- SkillInfo *const skill = *it;
- if (skill != nullptr)
- {
- const int time = get_elapsed_time(skill->durationTime);
- if (time >= skill->duration)
- {
- it = mDurations.erase(it);
- skill->cooldown = 0;
- skill->duration = 0;
- skill->durationTime = 0;
- if (it == mDurations.end())
- return;
- if (it != mDurations.begin())
- -- it;
- }
- else if (time != 0)
- {
- skill->cooldown = skill->duration * 100 / time;
- }
- }
- }
-}
-
-void SkillDialog::selectSkillLevel(const int skillId,
- const int level)
-{
- SkillInfo *const info = getSkill(skillId);
- if (info == nullptr)
- return;
- if (level > info->level)
- info->customSelectedLevel = info->level;
- else
- info->customSelectedLevel = level;
- info->update();
-}
-
-void SkillDialog::selectSkillCastType(const int skillId,
- const CastTypeT type)
-{
- SkillInfo *const info = getSkill(skillId);
- if (info == nullptr)
- return;
- info->customCastType = type;
- info->update();
-}
-
-void SkillDialog::setSkillOffsetX(const int skillId,
- const int offset)
-{
- SkillInfo *const info = getSkill(skillId);
- if (info == nullptr)
- return;
- info->customOffsetX = offset;
- info->update();
-}
-
-void SkillDialog::setSkillOffsetY(const int skillId,
- const int offset)
-{
- SkillInfo *const info = getSkill(skillId);
- if (info == nullptr)
- return;
- info->customOffsetY = offset;
- info->update();
-}
diff --git a/src/gui/windows/skilldialog.h b/src/gui/windows/skilldialog.h
deleted file mode 100644
index 2273125f0..000000000
--- a/src/gui/windows/skilldialog.h
+++ /dev/null
@@ -1,237 +0,0 @@
-/*
- * The ManaPlus Client
- * Copyright (C) 2004-2009 The Mana World Development Team
- * Copyright (C) 2009-2010 The Mana Developers
- * Copyright (C) 2011-2017 The ManaPlus Developers
- *
- * This file is part of The ManaPlus Client.
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-#ifndef GUI_WINDOWS_SKILLDIALOG_H
-#define GUI_WINDOWS_SKILLDIALOG_H
-
-#include "gui/widgets/window.h"
-
-#include "enums/simpletypes/autotarget.h"
-#include "enums/simpletypes/modifiable.h"
-
-#include "enums/resources/skill/casttype.h"
-#include "enums/resources/skill/skillowner.h"
-#include "enums/resources/skill/skilltype.h"
-
-#include "listeners/actionlistener.h"
-
-#include "utils/xml.h"
-
-class Being;
-class Button;
-class Label;
-class SkillModel;
-class SkillTab;
-class Tab;
-class TabbedArea;
-
-struct SkillData;
-struct SkillInfo;
-
-/**
- * The skill dialog.
- *
- * \ingroup Interface
- */
-class SkillDialog final : public Window,
- public ActionListener
-{
- public:
- SkillDialog();
-
- A_DELETE_COPY(SkillDialog)
-
- ~SkillDialog();
-
- void postInit() override final;
-
- /**
- * Called when receiving actions from widget.
- */
- void action(const ActionEvent &event) override final;
-
- /**
- * Update the given skill's display
- */
- std::string update(const int id);
-
- /**
- * Update other parts of the display
- */
- void update();
-
- void updateModels();
-
- void loadXmlFile(const std::string &fileName,
- const SkipError skipError);
-
- void clearSkills();
-
- void hideSkills(const SkillOwner::Type owner);
-
- void loadSkills();
-
- bool updateSkill(const int id,
- const int range,
- const Modifiable modifiable,
- const SkillType::SkillType type,
- const int sp);
-
- void addSkill(const SkillOwner::Type owner,
- const int id,
- const std::string &name,
- const int level,
- const int range,
- const Modifiable modifiable,
- const SkillType::SkillType type,
- const int sp);
-
- SkillInfo* getSkill(const int id) const A_WARN_UNUSED;
-
- SkillInfo* getSkillByItem(const int itemId) const A_WARN_UNUSED;
-
- void setSkillDuration(const SkillOwner::Type owner,
- const int id,
- const int duration);
-
- bool hasSkills() const noexcept2 A_WARN_UNUSED
- { return !mSkills.empty(); }
-
- void widgetResized(const Event &event) override final;
-
- void useItem(const int itemId,
- const AutoTarget autoTarget,
- const int level,
- const std::string &data) const;
-
- void updateTabSelection();
-
- void updateQuest(const int var,
- const int val1,
- const int val2,
- const int val3,
- const int time1);
-
- void playUpdateEffect(const int id) const;
-
- void playRemoveEffect(const int id) const;
-
- void playCastingDstTileEffect(const int id,
- const int level,
- const int x,
- const int y,
- const int delay) const;
-
- void slowLogic();
-
- void removeSkill(const int id);
-
- static void useSkill(const int skillId,
- const AutoTarget autoTarget,
- int level,
- const bool withText,
- const std::string &text,
- CastTypeT castType,
- const int offsetX,
- const int offsetY);
-
- static void useSkill(const SkillInfo *const info,
- const AutoTarget autoTarget,
- int level,
- const bool withText,
- const std::string &text,
- const CastTypeT castType,
- const int offsetX,
- const int offsetY);
-
- SkillData *getSkillData(const int id) const;
-
- SkillData *getSkillDataByLevel(const int id,
- const int level) const;
-
- void selectSkillLevel(const int skillId,
- const int level);
-
- void selectSkillCastType(const int skillId,
- const CastTypeT type);
-
- void setSkillOffsetX(const int skillId,
- const int offset);
-
- void setSkillOffsetY(const int skillId,
- const int offset);
-
- private:
- static void useSkillDefault(const SkillInfo *const info,
- const AutoTarget autoTarget,
- int level,
- const bool withText,
- const std::string &text,
- int offsetX,
- int offsetY);
-
- static void useSkillTarget(const SkillInfo *const info,
- const AutoTarget autoTarget,
- int level,
- const bool withText,
- const std::string &text,
- const Being *being,
- int offsetX,
- int offsetY);
-
- static void useSkillPosition(const SkillInfo *const info,
- int level,
- const bool withText,
- const std::string &text,
- const int x,
- const int y,
- int offsetX,
- int offsetY);
-
- static std::string getDefaultSkillIcon(const SkillType::SkillType
- type);
-
- void addSkillDuration(SkillInfo *const skill);
-
- SkillInfo *loadSkill(XmlNodeConstPtr node,
- SkillModel *const model);
-
- void loadSkillData(XmlNodeConstPtr node,
- SkillInfo *const skill);
-
- void addDefaultTab();
-
- typedef std::map<int, SkillInfo*> SkillMap;
- SkillMap mSkills;
- STD_VECTOR<SkillInfo*> mDurations;
- TabbedArea *mTabs A_NONNULLPOINTER;
- std::list<Tab*> mDeleteTabs;
- Label *mPointsLabel A_NONNULLPOINTER;
- Button *mUseButton A_NONNULLPOINTER;
- Button *mIncreaseButton A_NONNULLPOINTER;
- SkillModel *mDefaultModel;
- SkillTab *mDefaultTab;
-};
-
-extern SkillDialog *skillDialog;
-
-#endif // GUI_WINDOWS_SKILLDIALOG_H
diff --git a/src/gui/windows/socialwindow.cpp b/src/gui/windows/socialwindow.cpp
deleted file mode 100644
index 174762100..000000000
--- a/src/gui/windows/socialwindow.cpp
+++ /dev/null
@@ -1,659 +0,0 @@
-/*
- * The ManaPlus Client
- * Copyright (C) 2010 The Mana Developers
- * Copyright (C) 2011-2017 The ManaPlus Developers
- *
- * This file is part of The ManaPlus Client.
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-#include "gui/windows/socialwindow.h"
-
-#include "gui/popups/popupmenu.h"
-
-#include "gui/windows/setupwindow.h"
-
-#include "gui/widgets/button.h"
-#include "gui/widgets/label.h"
-#include "gui/widgets/tabbedarea.h"
-
-#include "gui/widgets/tabs/socialattacktab.h"
-#include "gui/widgets/tabs/socialfriendstab.h"
-#include "gui/widgets/tabs/socialguildtab.h"
-#include "gui/widgets/tabs/socialnavigationtab.h"
-#include "gui/widgets/tabs/socialpartytab.h"
-#include "gui/widgets/tabs/socialpickuptab.h"
-#include "gui/widgets/tabs/socialplayerstab.h"
-
-#ifdef TMWA_SUPPORT
-#include "gui/widgets/tabs/socialguildtab2.h"
-
-#include "net/tmwa/guildmanager.h"
-#endif // TMWA_SUPPORT
-
-#include "debug.h"
-
-SocialWindow *socialWindow = nullptr;
-
-SocialWindow::SocialWindow() :
- // TRANSLATORS: social window name
- Window(_("Social"), Modal_false, nullptr, "social.xml"),
- ActionListener(),
- PlayerRelationsListener(),
- mGuildInvited(0),
- mGuildAcceptDialog(nullptr),
- mGuildCreateDialog(nullptr),
- mPartyInviter(),
- mGuilds(),
- mParties(),
- mPartyAcceptDialog(nullptr),
- mAttackFilter(nullptr),
- mPickupFilter(nullptr),
- // TRANSLATORS: here P is title for visible players tab in social window
- mPlayers(new SocialPlayersTab(this, _("P"),
- fromBool(getOptionBool("showtabbackground"), Opaque))),
- mNavigation(new SocialNavigationTab(this,
- fromBool(getOptionBool("showtabbackground"), Opaque))),
- // TRANSLATORS: here F is title for friends tab in social window
- mFriends(new SocialFriendsTab(this, _("F"),
- fromBool(getOptionBool("showtabbackground"), Opaque))),
- // TRANSLATORS: social window button
- mMenuButton(new Button(this, _("Menu"), "menu", this)),
- mCountLabel(new Label(this, "1000 / 1000")),
- mTabs(CREATEWIDGETR(TabbedArea, this)),
- mMap(nullptr),
- mLastUpdateTime(0),
- mPartyId(0),
- mNeedUpdate(false),
- mProcessedPortals(false)
-{
-}
-
-void SocialWindow::postInit()
-{
- Window::postInit();
- setWindowName("Social");
- setVisible(Visible_false);
- setSaveVisible(true);
- setResizable(true);
- setSaveVisible(true);
- setCloseButton(true);
- setStickyButtonLock(true);
-
- setMinWidth(120);
- setMinHeight(55);
- setDefaultSize(590, 200, 180, 300);
- if (setupWindow != nullptr)
- setupWindow->registerWindowForReset(this);
-
- place(0, 0, mMenuButton);
- place(0, 1, mCountLabel);
- place(0, 2, mTabs, 2, 4);
-
- widgetResized(Event(nullptr));
-
- loadWindowState();
-
- mTabs->addTab(mPlayers, mPlayers->mScroll);
- mTabs->addTab(mFriends, mFriends->mScroll);
- mTabs->addTab(mNavigation, mNavigation->mScroll);
- mTabs->setSelectable(false);
- mTabs->getTabContainer()->setSelectable(false);
- mTabs->getWidgetContainer()->setSelectable(false);
-
- if (config.getBoolValue("enableAttackFilter"))
- {
- mAttackFilter = new SocialAttackTab(this,
- fromBool(getOptionBool("showtabbackground"), Opaque));
- mTabs->addTab(mAttackFilter, mAttackFilter->mScroll);
- }
- else
- {
- mAttackFilter = nullptr;
- }
-
- if (config.getBoolValue("enablePickupFilter"))
- {
- mPickupFilter = new SocialPickupTab(this,
- fromBool(getOptionBool("showtabbackground"), Opaque));
- mTabs->addTab(mPickupFilter, mPickupFilter->mScroll);
- }
- else
- {
- mPickupFilter = nullptr;
- }
-
- if ((localPlayer != nullptr) && (localPlayer->getParty() != nullptr))
- addTab(localPlayer->getParty());
-
- if ((localPlayer != nullptr) && (localPlayer->getGuild() != nullptr))
- addTab(localPlayer->getGuild());
-
- enableVisibleSound(true);
- updateButtons();
- playerRelations.addListener(this);
-}
-
-SocialWindow::~SocialWindow()
-{
- playerRelations.removeListener(this);
- if (mGuildAcceptDialog != nullptr)
- {
- mGuildAcceptDialog->close();
- mGuildAcceptDialog->scheduleDelete();
- mGuildAcceptDialog = nullptr;
-
- mGuildInvited = 0;
- }
-
- if (mPartyAcceptDialog != nullptr)
- {
- mPartyAcceptDialog->close();
- mPartyAcceptDialog->scheduleDelete();
- mPartyAcceptDialog = nullptr;
-
- mPartyInviter.clear();
- }
- delete2(mPlayers);
- delete2(mNavigation);
- delete2(mAttackFilter);
- delete2(mPickupFilter);
- delete2(mFriends);
- FOR_EACH (GuildMap::iterator, it, mGuilds)
- {
- delete (*it).second;
- }
- mGuilds.clear();
- FOR_EACH (PartyMap::iterator, it, mParties)
- {
- delete (*it).second;
- }
- mParties.clear();
-}
-
-bool SocialWindow::addTab(Guild *const guild)
-{
- if (guild == nullptr)
- return false;
-
- if (mGuilds.find(guild) != mGuilds.end())
- return false;
-
- SocialTab *tab = nullptr;
- if (guild->getServerGuild())
- {
- tab = new SocialGuildTab(this, guild,
- fromBool(getOptionBool("showtabbackground"), Opaque));
- }
-#ifdef TMWA_SUPPORT
- else
- {
- tab = new SocialGuildTab2(this, guild,
- fromBool(getOptionBool("showtabbackground"), Opaque));
- }
-#endif // TMWA_SUPPORT
-
- mGuilds[guild] = tab;
- mTabs->addTab(tab, tab->mScroll);
-
- updateButtons();
-
- return true;
-}
-
-bool SocialWindow::removeTab(Guild *const guild)
-{
- const GuildMap::iterator it = mGuilds.find(guild);
- if (it == mGuilds.end())
- return false;
-
- mTabs->removeTab(it->second);
- delete it->second;
- mGuilds.erase(it);
-
- updateButtons();
-
- return true;
-}
-
-bool SocialWindow::addTab(Party *const party)
-{
- if (party == nullptr)
- return false;
-
- if (mParties.find(party) != mParties.end())
- return false;
-
- SocialPartyTab *const tab = new SocialPartyTab(this, party,
- fromBool(getOptionBool("showtabbackground"), Opaque));
- mParties[party] = tab;
-
- mTabs->addTab(tab, tab->mScroll);
-
- updateButtons();
-
- return true;
-}
-
-bool SocialWindow::removeTab(Party *const party)
-{
- const PartyMap::iterator it = mParties.find(party);
- if (it == mParties.end())
- return false;
-
- mTabs->removeTab(it->second);
- delete it->second;
- mParties.erase(it);
-
- updateButtons();
-
- return true;
-}
-
-void SocialWindow::action(const ActionEvent &event)
-{
- const std::string &eventId = event.getId();
-
- if (event.getSource() == mPartyAcceptDialog)
- {
- if (eventId == "yes")
- {
- if (localChatTab != nullptr)
- {
- localChatTab->chatLog(
- // TRANSLATORS: chat message
- strprintf(_("Accepted party invite from %s."),
- mPartyInviter.c_str()),
- ChatMsgType::BY_SERVER);
- }
- partyHandler->inviteResponse(mPartyId, true);
- }
- else if (eventId == "no")
- {
- if (localChatTab != nullptr)
- {
- localChatTab->chatLog(
- // TRANSLATORS: chat message
- strprintf(_("Rejected party invite from %s."),
- mPartyInviter.c_str()),
- ChatMsgType::BY_SERVER);
- }
- partyHandler->inviteResponse(mPartyId, false);
- }
-
- mPartyInviter.clear();
- mPartyAcceptDialog = nullptr;
- }
- else if (event.getSource() == mGuildAcceptDialog)
- {
- if (eventId == "yes")
- {
- if (localChatTab != nullptr)
- {
- localChatTab->chatLog(
- // TRANSLATORS: chat message
- strprintf(_("Accepted guild invite from %s."),
- mPartyInviter.c_str()),
- ChatMsgType::BY_SERVER);
- }
-#ifdef TMWA_SUPPORT
- if (guildManager == nullptr || !GuildManager::getEnableGuildBot())
- guildHandler->inviteResponse(mGuildInvited, true);
- else
- GuildManager::inviteResponse(true);
-#else // TMWA_SUPPORT
-
- guildHandler->inviteResponse(mGuildInvited, true);
-#endif // TMWA_SUPPORT
- }
- else if (eventId == "no")
- {
- if (localChatTab != nullptr)
- {
- localChatTab->chatLog(
- // TRANSLATORS: chat message
- strprintf(_("Rejected guild invite from %s."),
- mPartyInviter.c_str()),
- ChatMsgType::BY_SERVER);
- }
-#ifdef TMWA_SUPPORT
- if (guildManager == nullptr || !GuildManager::getEnableGuildBot())
- guildHandler->inviteResponse(mGuildInvited, false);
- else
- GuildManager::inviteResponse(false);
-#else // TMWA_SUPPORT
-
- guildHandler->inviteResponse(mGuildInvited, false);
-#endif // TMWA_SUPPORT
- }
-
- mGuildInvited = 0;
- mGuildAcceptDialog = nullptr;
- }
- else if (eventId == "party")
- {
- popupMenu->showPartyPopup();
- }
- else if (eventId == "guild")
- {
- popupMenu->showGuildPopup();
- }
- else if (eventId == "attack")
- {
- popupMenu->showAttackPopup();
- }
- else if (eventId == "friends")
- {
- popupMenu->showFriendsPopup();
- }
- else if (eventId == "navigation")
- {
- popupMenu->showNavigationPopup();
- }
- else if (eventId == "pickup")
- {
- popupMenu->showPickupPopup();
- }
- else if (eventId == "players")
- {
- popupMenu->showPlayersPopup();
- }
-}
-
-void SocialWindow::showGuildInvite(const std::string &restrict guildName,
- const int guildId,
- const std::string &restrict inviterName)
-{
- // check there isnt already an invite showing
- if (mGuildInvited != 0)
- {
- if (localChatTab != nullptr)
- {
- // TRANSLATORS: chat message
- localChatTab->chatLog(_("Received guild request, but one already "
- "exists."),
- ChatMsgType::BY_SERVER);
- }
- return;
- }
-
- const std::string msg = strprintf(
- // TRANSLATORS: chat message
- _("%s has invited you to join the guild %s."),
- inviterName.c_str(), guildName.c_str());
-
- if (localChatTab != nullptr)
- localChatTab->chatLog(msg, ChatMsgType::BY_SERVER);
-
- CREATEWIDGETV(mGuildAcceptDialog, ConfirmDialog,
- // TRANSLATORS: guild invite message
- _("Accept Guild Invite"),
- msg,
- SOUND_REQUEST,
- false,
- Modal_false,
- this);
- mGuildAcceptDialog->addActionListener(this);
- mGuildInvited = guildId;
-}
-
-void SocialWindow::showPartyInvite(const std::string &restrict partyName,
- const std::string &restrict inviter,
- const int partyId)
-{
- // check there isnt already an invite showing
- if (!mPartyInviter.empty())
- {
- if (localChatTab != nullptr)
- {
- // TRANSLATORS: chat message
- localChatTab->chatLog(_("Received party request, but one already "
- "exists."),
- ChatMsgType::BY_SERVER);
- }
- return;
- }
-
- std::string msg;
- if (inviter.empty())
- {
- if (partyName.empty())
- {
- // TRANSLATORS: party invite message
- msg = _("You have been invited you to join a party.");
- }
- else
- {
- // TRANSLATORS: party invite message
- msg = strprintf(_("You have been invited to join the %s party."),
- partyName.c_str());
- }
- }
- else
- {
- if (partyName.empty())
- {
- // TRANSLATORS: party invite message
- msg = strprintf(_("%s has invited you to join their party."),
- inviter.c_str());
- }
- else
- {
- // TRANSLATORS: party invite message
- msg = strprintf(_("%s has invited you to join the %s party."),
- inviter.c_str(), partyName.c_str());
- }
- }
-
- if (localChatTab != nullptr)
- localChatTab->chatLog(msg, ChatMsgType::BY_SERVER);
-
- // show invite
- CREATEWIDGETV(mPartyAcceptDialog, ConfirmDialog,
- // TRANSLATORS: party invite message
- _("Accept Party Invite"),
- msg,
- SOUND_REQUEST,
- false,
- Modal_false,
- this);
- mPartyAcceptDialog->addActionListener(this);
- mPartyInviter = inviter;
- mPartyId = partyId;
-}
-
-void SocialWindow::updateActiveList()
-{
- mNeedUpdate = true;
-}
-
-void SocialWindow::slowLogic()
-{
- BLOCK_START("SocialWindow::slowLogic")
- const time_t nowTime = cur_time;
- if (mNeedUpdate && nowTime - mLastUpdateTime > 1)
- {
- mPlayers->updateList();
- mFriends->updateList();
- mNeedUpdate = false;
- mLastUpdateTime = nowTime;
- }
- else if (nowTime - mLastUpdateTime > 5)
- {
- mPlayers->updateList();
- mNeedUpdate = false;
- mLastUpdateTime = nowTime;
- }
- BLOCK_END("SocialWindow::slowLogic")
-}
-
-void SocialWindow::updateAvatar(const std::string &name)
-{
- mPlayers->updateAvatar(name);
-}
-
-void SocialWindow::resetDamage(const std::string &name)
-{
- mPlayers->resetDamage(name);
-}
-
-void SocialWindow::updateButtons()
-{
-// if (!mTabs)
-// return;
-
-// const bool hasTabs = mTabs->getNumberOfTabs() > 0;
-}
-
-void SocialWindow::updatePortals()
-{
- if (mNavigation != nullptr)
- mNavigation->updateList();
-}
-
-void SocialWindow::updatePortalNames()
-{
- if (mNavigation != nullptr)
- static_cast<SocialNavigationTab*>(mNavigation)->updateNames();
-}
-
-void SocialWindow::selectPortal(const unsigned num)
-{
- if (mNavigation != nullptr)
- mNavigation->selectIndex(num);
-}
-
-int SocialWindow::getPortalIndex(const int x, const int y)
-{
- if (mNavigation != nullptr)
- {
- return static_cast<SocialNavigationTab*>(
- mNavigation)->getPortalIndex(x, y);
- }
- return -1;
-}
-
-void SocialWindow::addPortal(const int x, const int y)
-{
- if (mNavigation != nullptr)
- static_cast<SocialNavigationTab*>(mNavigation)->addPortal(x, y);
-}
-
-void SocialWindow::removePortal(const int x, const int y)
-{
- if (mNavigation != nullptr)
- static_cast<SocialNavigationTab*>(mNavigation)->removePortal(x, y);
-}
-
-void SocialWindow::nextTab()
-{
- if (mTabs != nullptr)
- mTabs->selectNextTab();
-}
-
-void SocialWindow::prevTab()
-{
- if (mTabs != nullptr)
- mTabs->selectPrevTab();
-}
-
-void SocialWindow::updateAttackFilter()
-{
- if (mAttackFilter != nullptr)
- mAttackFilter->updateList();
-}
-
-void SocialWindow::updatePickupFilter()
-{
- if (mPickupFilter != nullptr)
- mPickupFilter->updateList();
-}
-
-void SocialWindow::updateParty()
-{
- if (localPlayer == nullptr)
- return;
-
- Party *const party = localPlayer->getParty();
- if (party != nullptr)
- {
- const PartyMap::iterator it = mParties.find(party);
- if (it != mParties.end())
- {
- SocialTab *const tab = (*it).second;
- tab->buildCounter(0, 0);
- }
- }
-}
-
-void SocialWindow::widgetResized(const Event &event)
-{
- Window::widgetResized(event);
- if (mTabs != nullptr)
- mTabs->adjustSize();
-}
-
-void SocialWindow::updateCounter(const SocialTab *const tab,
- const std::string &counter)
-{
- if (mTabs->getSelectedTab() == tab)
- {
- mCountLabel->setCaption(counter);
- mCountLabel->adjustSize();
- }
-}
-
-void SocialWindow::updateMenu(const SocialTab *const tab,
- const std::string &menu)
-{
- if (mTabs->getSelectedTab() == tab)
- mMenuButton->setActionEventId(menu);
-}
-
-void SocialWindow::updateGuildCounter(const int online, const int total)
-{
- if (localPlayer == nullptr)
- return;
-
- Guild *const guild = localPlayer->getGuild();
- if (guild != nullptr)
- {
- const GuildMap::iterator it = mGuilds.find(guild);
- if (it != mGuilds.end())
- {
- SocialTab *const tab = (*it).second;
- tab->buildCounter(online, total);
- }
- }
-}
-
-void SocialWindow::updatedPlayer(const std::string &name A_UNUSED)
-{
- mNeedUpdate = true;
-}
-
-void SocialWindow::updateAll()
-{
- mNeedUpdate = true;
-}
-
-#ifdef USE_PROFILER
-void SocialWindow::logicChildren()
-{
- BLOCK_START("SocialWindow::logicChildren")
- BasicContainer::logicChildren();
- BLOCK_END("SocialWindow::logicChildren")
-}
-#endif // USE_PROFILER
diff --git a/src/gui/windows/socialwindow.h b/src/gui/windows/socialwindow.h
deleted file mode 100644
index 2abee7170..000000000
--- a/src/gui/windows/socialwindow.h
+++ /dev/null
@@ -1,171 +0,0 @@
-/*
- * The ManaPlus Client
- * Copyright (C) 2010 The Mana Developers
- * Copyright (C) 2011-2017 The ManaPlus Developers
- *
- * This file is part of The ManaPlus Client.
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-#ifndef GUI_WINDOWS_SOCIALWINDOW_H
-#define GUI_WINDOWS_SOCIALWINDOW_H
-
-#include "gui/widgets/window.h"
-
-#include "listeners/actionlistener.h"
-#include "listeners/playerrelationslistener.h"
-
-class Button;
-class ConfirmDialog;
-class Guild;
-class Label;
-class Map;
-class Party;
-class SocialTab;
-class TabbedArea;
-class TextDialog;
-
-/**
- * Party window.
- *
- * \ingroup Interface
- */
-class SocialWindow final : public Window,
- private ActionListener,
- public PlayerRelationsListener
-{
- public:
- SocialWindow();
-
- A_DELETE_COPY(SocialWindow)
-
- ~SocialWindow();
-
- void postInit() override final;
-
- bool addTab(Guild *const guild);
-
- bool removeTab(Guild *const guild);
-
- bool addTab(Party *const party);
-
- bool removeTab(Party *const party);
-
- void action(const ActionEvent &event) override final;
-
- void showGuildInvite(const std::string &restrict guildName,
- const int guildId,
- const std::string &restrict inviterName);
-
- void showPartyInvite(const std::string &restrict partyName,
- const std::string &restrict inviter,
- const int partyId);
-
- void updateActiveList();
-
- void updateAvatar(const std::string &name);
-
- void resetDamage(const std::string &name);
-
- void slowLogic();
-
- void updatePortals();
-
- void updatePortalNames();
-
- void updateParty();
-
- int getPortalIndex(const int x, const int y) A_WARN_UNUSED;
-
- void addPortal(const int x, const int y);
-
- void removePortal(const int x, const int y);
-
- void nextTab();
-
- void prevTab();
-
- const Map* getMap() const noexcept2 A_WARN_UNUSED
- { return mMap; }
-
- void setMap(Map *const map)
- { mMap = map; mProcessedPortals = false; }
-
- bool getProcessedPortals() const noexcept2 A_WARN_UNUSED
- { return mProcessedPortals; }
-
- void setProcessedPortals(const bool n) noexcept2
- { mProcessedPortals = n; }
-
- void selectPortal(const unsigned num);
-
- void updateAttackFilter();
-
- void updatePickupFilter();
-
- void widgetResized(const Event &event) override final;
-
- void updateCounter(const SocialTab *const tab,
- const std::string &count);
-
- void updateMenu(const SocialTab *const tab,
- const std::string &menu);
-
- void updateGuildCounter(const int online = 0, const int total = 0);
-
- void updatedPlayer(const std::string &name) override final;
-
- void updateAll() override final;
-
-#ifdef USE_PROFILER
- void logicChildren();
-#endif // USE_PROFILER
-
- protected:
- friend class SocialTab;
- typedef std::map<Guild*, SocialTab*> GuildMap;
- typedef std::map<Party*, SocialTab*> PartyMap;
-
- void updateButtons();
-
- int mGuildInvited;
- ConfirmDialog *mGuildAcceptDialog;
- TextDialog *mGuildCreateDialog;
- std::string mPartyInviter;
- GuildMap mGuilds;
- PartyMap mParties;
-
- ConfirmDialog *mPartyAcceptDialog;
-
- SocialTab *mAttackFilter;
- SocialTab *mPickupFilter;
- SocialTab *mPlayers A_NONNULLPOINTER;
- SocialTab *mNavigation A_NONNULLPOINTER;
- SocialTab *mFriends A_NONNULLPOINTER;
-
- Button *mMenuButton A_NONNULLPOINTER;
- Label *mCountLabel A_NONNULLPOINTER;
- TabbedArea *mTabs A_NONNULLPOINTER;
- Map *mMap;
-
- time_t mLastUpdateTime;
- int mPartyId;
- bool mNeedUpdate;
- bool mProcessedPortals;
-};
-
-extern SocialWindow *socialWindow;
-
-#endif // GUI_WINDOWS_SOCIALWINDOW_H
diff --git a/src/gui/windows/statuswindow.cpp b/src/gui/windows/statuswindow.cpp
deleted file mode 100644
index 092e401c2..000000000
--- a/src/gui/windows/statuswindow.cpp
+++ /dev/null
@@ -1,652 +0,0 @@
-/*
- * The ManaPlus Client
- * Copyright (C) 2004-2009 The Mana World Development Team
- * Copyright (C) 2009-2010 The Mana Developers
- * Copyright (C) 2011-2017 The ManaPlus Developers
- *
- * This file is part of The ManaPlus Client.
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-#include "gui/windows/statuswindow.h"
-
-#include "configuration.h"
-#include "gamemodifiers.h"
-#include "settings.h"
-
-#include "being/localplayer.h"
-#include "being/playerinfo.h"
-
-#include "enums/gui/layouttype.h"
-
-#include "gui/windows/chatwindow.h"
-
-#include "gui/windows/equipmentwindow.h"
-#include "gui/windows/setupwindow.h"
-
-#include "gui/widgets/button.h"
-#include "gui/widgets/createwidget.h"
-#include "gui/widgets/layout.h"
-#include "gui/widgets/progressbar.h"
-#include "gui/widgets/statspage.h"
-#include "gui/widgets/statspagebasic.h"
-#include "gui/widgets/tabbedarea.h"
-#include "gui/widgets/windowcontainer.h"
-
-#include "net/inventoryhandler.h"
-#include "net/playerhandler.h"
-
-#include "resources/db/groupdb.h"
-#include "resources/db/unitsdb.h"
-#include "resources/db/statdb.h"
-
-#include "resources/item/item.h"
-
-#include "utils/delete2.h"
-#include "utils/dtor.h"
-#include "utils/foreach.h"
-#include "utils/gettext.h"
-
-#include "debug.h"
-
-StatusWindow *statusWindow = nullptr;
-
-StatusWindow::StatusWindow() :
- Window(localPlayer != nullptr ? localPlayer->getName() :
- "?", Modal_false, nullptr, "status.xml"),
- ActionListener(),
- AttributeListener(),
- mPages(),
- mTabs(CREATEWIDGETR(TabbedArea, this)),
- // TRANSLATORS: status window label
- mLvlLabel(new Label(this, strprintf(_("Level: %d"), 0))),
- // TRANSLATORS: status window label
- mMoneyLabel(new Label(this, strprintf(_("Money: %s"), ""))),
- // TRANSLATORS: status window label
- mHpLabel(new Label(this, _("HP:"))),
- mMpLabel(nullptr),
- // TRANSLATORS: status window label
- mXpLabel(new Label(this, _("Exp:"))),
- mHpBar(nullptr),
- mMpBar(nullptr),
- mXpBar(nullptr),
- mJobLvlLabel(nullptr),
- mJobLabel(nullptr),
- mJobBar(nullptr),
- mBasicStatsPage(new StatsPageBasic(this)),
- // TRANSLATORS: status window button
- mCopyButton(new Button(this, _("Copy to chat"), "copy", this))
-{
- setWindowName("Status");
- if (setupWindow != nullptr)
- setupWindow->registerWindowForReset(this);
- setResizable(true);
- setCloseButton(true);
- setSaveVisible(true);
- setStickyButtonLock(true);
- setDefaultSize((windowContainer->getWidth() - 480) / 2,
- (windowContainer->getHeight() - 500) / 2, 480, 500);
-
- mTabs->setSelectable(false);
- mTabs->getWidgetContainer()->setSelectable(false);
- mTabs->getTabContainer()->setSelectable(false);
-
- if ((localPlayer != nullptr) && !localPlayer->getRaceName().empty())
- {
- setCaption(strprintf("%s (%s)", localPlayer->getName().c_str(),
- localPlayer->getRaceName().c_str()));
- }
-
- int max = PlayerInfo::getAttribute(Attributes::PLAYER_MAX_HP);
- if (max == 0)
- max = 1;
-
- mHpBar = new ProgressBar(this,
- static_cast<float>(PlayerInfo::getAttribute(Attributes::PLAYER_HP))
- / static_cast<float>(max),
- 80,
- 0,
- ProgressColorId::PROG_HP,
- "hpprogressbar.xml", "hpprogressbar_fill.xml");
- mHpBar->setColor(getThemeColor(ThemeColorId::HP_BAR),
- getThemeColor(ThemeColorId::HP_BAR_OUTLINE));
- mHpBar->setSelectable(false);
-
- const int64_t maxExp = PlayerInfo::getAttribute64(
- Attributes::PLAYER_EXP_NEEDED);
- mXpBar = new ProgressBar(this,
- maxExp != 0 ?
- static_cast<float>(PlayerInfo::getAttribute64(
- Attributes::PLAYER_EXP)) /
- static_cast<float>(maxExp) : static_cast<float>(0),
- 80,
- 0,
- ProgressColorId::PROG_EXP,
- "xpprogressbar.xml", "xpprogressbar_fill.xml");
- mXpBar->setColor(getThemeColor(ThemeColorId::XP_BAR),
- getThemeColor(ThemeColorId::XP_BAR_OUTLINE));
- mXpBar->setSelectable(false);
-
- const bool job = serverConfig.getValueBool("showJob", true);
-
- max = PlayerInfo::getAttribute(Attributes::PLAYER_MAX_MP);
- // TRANSLATORS: status window label
- mMpLabel = new Label(this, _("MP:"));
- const bool useMagic = playerHandler->canUseMagic();
- mMpBar = new ProgressBar(this,
- max != 0 ? static_cast<float>(PlayerInfo::getAttribute(
- Attributes::PLAYER_MAX_MP)) / static_cast<float>(max)
- : static_cast<float>(0),
- 80,
- 0,
- useMagic ? ProgressColorId::PROG_MP : ProgressColorId::PROG_NO_MP,
- useMagic ? "mpprogressbar.xml" : "nompprogressbar.xml",
- useMagic ? "mpprogressbar_fill.xml" : "nompprogressbar_fill.xml");
- mMpBar->setSelectable(false);
- if (useMagic)
- {
- mMpBar->setColor(getThemeColor(ThemeColorId::MP_BAR),
- getThemeColor(ThemeColorId::MP_BAR_OUTLINE));
- }
- else
- {
- mMpBar->setColor(getThemeColor(ThemeColorId::NO_MP_BAR),
- getThemeColor(ThemeColorId::NO_MP_BAR_OUTLINE));
- }
-
- place(0, 0, mLvlLabel, 3);
- place(0, 1, mHpLabel).setPadding(3);
- place(1, 1, mHpBar, 4);
- place(5, 1, mXpLabel).setPadding(3);
- place(6, 1, mXpBar, 5);
- place(0, 2, mMpLabel).setPadding(3);
- // 5, 2 and 6, 2 Job Progress Bar
- if (job)
- place(1, 2, mMpBar, 4);
- else
- place(1, 2, mMpBar, 10);
-
- if (job)
- {
- // TRANSLATORS: status window label
- mJobLvlLabel = new Label(this, strprintf(_("Job: %d"), 0));
- // TRANSLATORS: status window label
- mJobLabel = new Label(this, _("Job:"));
- mJobBar = new ProgressBar(this, 0.0F, 80, 0, ProgressColorId::PROG_JOB,
- "jobprogressbar.xml", "jobprogressbar_fill.xml");
- mJobBar->setColor(getThemeColor(ThemeColorId::JOB_BAR),
- getThemeColor(ThemeColorId::JOB_BAR_OUTLINE));
- mJobBar->setSelectable(false);
-
- place(3, 0, mJobLvlLabel, 3);
- place(5, 2, mJobLabel).setPadding(3);
- place(6, 2, mJobBar, 5);
- place(6, 0, mMoneyLabel, 3);
- }
- else
- {
- mJobLvlLabel = nullptr;
- mJobLabel = nullptr;
- mJobBar = nullptr;
- place(3, 0, mMoneyLabel, 3);
- }
-
- place(0, 3, mTabs, 11, 3);
-
- getLayout().setRowHeight(3, LayoutType::SET);
-
- place(0, 5, mCopyButton);
-
- loadWindowState();
- enableVisibleSound(true);
-
- // Update bars
- updateHPBar(mHpBar, true);
- updateMPBar(mMpBar, true);
- updateXPBar(mXpBar, false);
-
- // TRANSLATORS: status window label
- mMoneyLabel->setCaption(strprintf(_("Money: %s"),
- UnitsDb::formatCurrency(PlayerInfo::getAttribute(
- Attributes::MONEY)).c_str()));
- mMoneyLabel->adjustSize();
-
- updateLevelLabel();
- addTabs();
-}
-
-StatusWindow::~StatusWindow()
-{
- delete2(mBasicStatsPage);
- delete_all(mPages);
-}
-
-void StatusWindow::addTabs()
-{
- // TRANSLATORS: status window tab name
- addTabBasic(_("Basic"));
- const STD_VECTOR<std::string> &pages = StatDb::getPages();
- FOR_EACH(STD_VECTOR<std::string>::const_iterator, it, pages)
- {
- addTab(*it);
- }
- mTabs->adjustSize();
-}
-
-void StatusWindow::addTab(const std::string &name)
-{
- StatsPage *const page = new StatsPage(this, name);
- mTabs->addTab(name,
- page);
- mPages.push_back(page);
-}
-
-void StatusWindow::addTabBasic(const std::string &name)
-{
- mTabs->addTab(name,
- mBasicStatsPage);
-}
-
-void StatusWindow::updateLevelLabel()
-{
- if (localPlayer == nullptr)
- return;
-
- const int groupId = localPlayer->getGroupId();
- const std::string &name = GroupDb::getName(groupId);
- if (!name.empty())
- {
- // TRANSLATORS: status window label
- mLvlLabel->setCaption(strprintf(_("Level: %d (%s %d)"),
- PlayerInfo::getAttribute(Attributes::PLAYER_BASE_LEVEL),
- name.c_str(),
- groupId));
- }
- else
- {
- // TRANSLATORS: status window label
- mLvlLabel->setCaption(strprintf(_("Level: %d"),
- PlayerInfo::getAttribute(Attributes::PLAYER_BASE_LEVEL)));
- }
- mLvlLabel->adjustSize();
-}
-
-void StatusWindow::attributeChanged(const AttributesT id,
- const int64_t oldVal,
- const int64_t newVal)
-{
- static bool blocked = false;
-
- PRAGMA45(GCC diagnostic push)
- PRAGMA45(GCC diagnostic ignored "-Wswitch-enum")
- switch (id)
- {
- case Attributes::PLAYER_HP:
- case Attributes::PLAYER_MAX_HP:
- updateHPBar(mHpBar, true);
- break;
-
- case Attributes::PLAYER_MP:
- case Attributes::PLAYER_MAX_MP:
- updateMPBar(mMpBar, true);
- break;
-
- case Attributes::PLAYER_EXP:
- case Attributes::PLAYER_EXP_NEEDED:
- updateXPBar(mXpBar, false);
- break;
-
- case Attributes::MONEY:
- // TRANSLATORS: status window label
- mMoneyLabel->setCaption(strprintf(_("Money: %s"),
- UnitsDb::formatCurrency64(newVal).c_str()));
- mMoneyLabel->adjustSize();
- break;
-
- case Attributes::PLAYER_BASE_LEVEL:
- // TRANSLATORS: status window label
- mLvlLabel->setCaption(strprintf(_("Level: %d"),
- CAST_S32(newVal)));
- mLvlLabel->adjustSize();
- break;
-
- // +++ probable need use only some attributes here
- case Attributes::PLAYER_JOB_LEVEL:
- case Attributes::PLAYER_JOB_EXP:
- case Attributes::PLAYER_JOB_EXP_NEEDED:
- if (blocked)
- return;
- if (mJobLvlLabel != nullptr)
- {
- int lvl = PlayerInfo::getAttribute(
- Attributes::PLAYER_JOB_LEVEL);
- const int64_t exp = PlayerInfo::getAttribute(
- Attributes::PLAYER_JOB_EXP);
- const int64_t expNeed = PlayerInfo::getAttribute(
- Attributes::PLAYER_JOB_EXP_NEEDED);
-
- if (lvl == 0)
- {
- // possible server broken and don't send job level,
- // then we fixing it.
- if (expNeed < 20000)
- {
- lvl = 0;
- }
- else
- {
- lvl = CAST_S32((expNeed - 20000) / 150);
- blocked = true;
- PlayerInfo::setAttribute(Attributes::PLAYER_JOB_LEVEL,
- lvl);
- blocked = false;
- }
- }
-
- if (id == Attributes::PLAYER_JOB_EXP &&
- exp < oldVal &&
- expNeed >= 20000)
- { // possible job level up. but server broken and don't send
- // new job exp limit, we fixing it
- lvl ++;
- blocked = true;
- PlayerInfo::setAttribute(Attributes::PLAYER_JOB_EXP_NEEDED,
- 20000 + lvl * 150);
- PlayerInfo::setAttribute(Attributes::PLAYER_JOB_LEVEL,
- lvl);
- blocked = false;
- }
-
- // TRANSLATORS: status window label
- mJobLvlLabel->setCaption(strprintf(_("Job: %d"), lvl));
- mJobLvlLabel->adjustSize();
-
- updateJobBar(mJobBar, false);
- }
- break;
-
- default:
- break;
- }
- PRAGMA45(GCC diagnostic pop)
-}
-
-void StatusWindow::setPointsNeeded(const AttributesT id,
- const int needed)
-{
- mBasicStatsPage->setPointsNeeded(id, needed);
-}
-
-void StatusWindow::updateHPBar(ProgressBar *const bar, const bool showMax)
-{
- if (bar == nullptr)
- return;
-
- const int hp = PlayerInfo::getAttribute(Attributes::PLAYER_HP);
- const int maxHp = PlayerInfo::getAttribute(Attributes::PLAYER_MAX_HP);
- if (showMax)
- bar->setText(toString(hp).append("/").append(toString(maxHp)));
- else
- bar->setText(toString(hp));
-
- float prog = 1.0;
- if (maxHp > 0)
- prog = static_cast<float>(hp) / static_cast<float>(maxHp);
- bar->setProgress(prog);
-}
-
-void StatusWindow::updateMPBar(ProgressBar *const bar,
- const bool showMax) const
-{
- if (bar == nullptr)
- return;
-
- const int mp = PlayerInfo::getAttribute(Attributes::PLAYER_MP);
- const int maxMp = PlayerInfo::getAttribute(Attributes::PLAYER_MAX_MP);
- if (showMax)
- bar->setText(toString(mp).append("/").append(toString(maxMp)));
- else
- bar->setText(toString(mp));
-
- float prog = 1.0F;
- if (maxMp > 0)
- prog = static_cast<float>(mp) / static_cast<float>(maxMp);
-
- if (playerHandler->canUseMagic())
- {
- bar->setColor(getThemeColor(ThemeColorId::MP_BAR),
- getThemeColor(ThemeColorId::MP_BAR_OUTLINE));
- bar->setProgressPalette(ProgressColorId::PROG_MP);
- }
- else
- {
- bar->setColor(getThemeColor(ThemeColorId::NO_MP_BAR),
- getThemeColor(ThemeColorId::NO_MP_BAR_OUTLINE));
- bar->setProgressPalette(ProgressColorId::PROG_NO_MP);
- }
-
- bar->setProgress(prog);
-}
-
-void StatusWindow::updateProgressBar(ProgressBar *const bar,
- const int64_t value,
- const int64_t max,
- const bool percent)
-{
- if (bar == nullptr)
- return;
-
- if (max == 0)
- {
- // TRANSLATORS: status bar label
- bar->setText(_("Max"));
- bar->setProgress(1);
- bar->setText(toString(CAST_U64(value)));
- }
- else
- {
- const float progress = static_cast<float>(value)
- / static_cast<float>(max);
- if (percent)
- {
- bar->setText(strprintf("%2.5f%%",
- static_cast<double>(100 * progress)));
- }
- else
- {
- bar->setText(toString(
- CAST_U64(value)).append(
- "/").append(toString(
- CAST_U64(max))));
- }
- bar->setProgress(progress);
- }
-}
-
-void StatusWindow::updateXPBar(ProgressBar *const bar, const bool percent)
-{
- if (bar == nullptr)
- return;
-
- updateProgressBar(bar,
- PlayerInfo::getAttribute(Attributes::PLAYER_EXP),
- PlayerInfo::getAttribute(Attributes::PLAYER_EXP_NEEDED),
- percent);
-}
-
-void StatusWindow::updateJobBar(ProgressBar *const bar, const bool percent)
-{
- if (bar == nullptr)
- return;
-
- updateProgressBar(bar,
- PlayerInfo::getAttribute(Attributes::PLAYER_JOB_EXP),
- PlayerInfo::getAttribute(Attributes::PLAYER_JOB_EXP_NEEDED),
- percent);
-}
-
-void StatusWindow::updateProgressBar(ProgressBar *const bar,
- const AttributesT id,
- const bool percent)
-{
- const std::pair<int, int> exp = PlayerInfo::getStatExperience(id);
- updateProgressBar(bar, exp.first, exp.second, percent);
-}
-
-void StatusWindow::updateWeightBar(ProgressBar *const bar)
-{
- if (bar == nullptr)
- return;
-
- if (PlayerInfo::getAttribute(Attributes::MAX_WEIGHT) == 0)
- {
- // TRANSLATORS: status bar label
- bar->setText(_("Max"));
- bar->setProgress(1.0);
- }
- else
- {
- const int totalWeight = PlayerInfo::getAttribute(
- Attributes::TOTAL_WEIGHT);
- const int maxWeight = PlayerInfo::getAttribute(Attributes::MAX_WEIGHT);
- float progress = 1.0F;
- if (maxWeight != 0)
- {
- progress = static_cast<float>(totalWeight)
- / static_cast<float>(maxWeight);
- }
- bar->setText(strprintf("%s/%s",
- UnitsDb::formatWeight(totalWeight).c_str(),
- UnitsDb::formatWeight(maxWeight).c_str()));
- bar->setProgress(progress);
- }
-}
-
-void StatusWindow::updateMoneyBar(ProgressBar *const bar)
-{
- if (bar == nullptr)
- return;
-
- const int money = PlayerInfo::getAttribute(Attributes::MONEY);
- bar->setText(UnitsDb::formatCurrency(money));
- if (money > 0)
- {
- const float progress = static_cast<float>(money)
- / static_cast<float>(1000000000);
- bar->setProgress(progress);
- }
- else
- {
- bar->setProgress(1.0);
- }
-}
-
-void StatusWindow::updateArrowsBar(ProgressBar *const bar)
-{
- if ((bar == nullptr) || (equipmentWindow == nullptr))
- return;
-
- const Item *const item = equipmentWindow->getEquipment(
- inventoryHandler->getProjectileSlot());
-
- if ((item != nullptr) && item->getQuantity() > 0)
- bar->setText(toString(item->getQuantity()));
- else
- bar->setText("0");
-}
-
-void StatusWindow::updateInvSlotsBar(ProgressBar *const bar)
-{
- if (bar == nullptr)
- return;
-
- const Inventory *const inv = PlayerInfo::getInventory();
- if (inv == nullptr)
- return;
-
- const int usedSlots = inv->getNumberOfSlotsUsed();
- const int maxSlots = inv->getSize();
-
- if (maxSlots != 0)
- {
- bar->setProgress(static_cast<float>(usedSlots)
- / static_cast<float>(maxSlots));
- }
-
- bar->setText(strprintf("%d", usedSlots));
-}
-
-std::string StatusWindow::translateLetter(const char *const letters)
-{
- char buf[2];
- char *const str = gettext(letters);
- if ((str == nullptr) || strlen(str) != 3)
- return letters;
-
- buf[0] = str[1];
- buf[1] = 0;
- return std::string(buf);
-}
-
-std::string StatusWindow::translateLetter2(const std::string &letters)
-{
- if (letters.size() < 5)
- return "";
-
- return std::string(gettext(letters.substr(1, 1).c_str()));
-}
-
-void StatusWindow::updateStatusBar(ProgressBar *const bar,
- const bool percent A_UNUSED) const
-{
- if (bar == nullptr)
- return;
- bar->setText(translateLetter2(GameModifiers::getMoveTypeString())
- .append(translateLetter2(GameModifiers::getCrazyMoveTypeString()))
- .append(translateLetter2(GameModifiers::getMoveToTargetTypeString()))
- .append(translateLetter2(GameModifiers::getFollowModeString()))
- .append(" ").append(translateLetter2(
- GameModifiers::getAttackWeaponTypeString()))
- .append(translateLetter2(GameModifiers::getAttackTypeString()))
- .append(translateLetter2(GameModifiers::getMagicAttackTypeString()))
- .append(translateLetter2(GameModifiers::getPvpAttackTypeString()))
- .append(" ").append(translateLetter2(
- GameModifiers::getQuickDropCounterString()))
- .append(translateLetter2(GameModifiers::getPickUpTypeString()))
- .append(" ").append(translateLetter2(
- GameModifiers::getMapDrawTypeString()))
- .append(" ").append(translateLetter2(
- GameModifiers::getImitationModeString()))
- .append(translateLetter2(GameModifiers::getCameraModeString()))
- .append(translateLetter2(GameModifiers::getAwayModeString()))
- .append(translateLetter2(GameModifiers::getTargetingTypeString())));
-
- bar->setProgress(50);
- if (settings.disableGameModifiers)
- bar->setBackgroundColor(getThemeColor(ThemeColorId::STATUSBAR_ON));
- else
- bar->setBackgroundColor(getThemeColor(ThemeColorId::STATUSBAR_OFF));
-}
-
-void StatusWindow::action(const ActionEvent &event)
-{
- if (chatWindow == nullptr)
- return;
-
- if (event.getId() == "copy")
- {
- chatWindow->addInputText(mBasicStatsPage->getStatsStr());
- }
-}
diff --git a/src/gui/windows/statuswindow.h b/src/gui/windows/statuswindow.h
deleted file mode 100644
index 233840d17..000000000
--- a/src/gui/windows/statuswindow.h
+++ /dev/null
@@ -1,119 +0,0 @@
-/*
- * The ManaPlus Client
- * Copyright (C) 2004-2009 The Mana World Development Team
- * Copyright (C) 2009-2010 The Mana Developers
- * Copyright (C) 2011-2017 The ManaPlus Developers
- *
- * This file is part of The ManaPlus Client.
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-#ifndef GUI_WINDOWS_STATUSWINDOW_H
-#define GUI_WINDOWS_STATUSWINDOW_H
-
-#include "gui/widgets/window.h"
-
-#include "listeners/actionlistener.h"
-#include "listeners/attributelistener.h"
-
-class Button;
-class Label;
-class ProgressBar;
-class StatsPage;
-class StatsPageBasic;
-class TabbedArea;
-
-/**
- * The player status dialog.
- *
- * \ingroup Interface
- */
-class StatusWindow final : public Window,
- public ActionListener,
- public AttributeListener
-{
- public:
- /**
- * Constructor.
- */
- StatusWindow();
-
- A_DELETE_COPY(StatusWindow)
-
- ~StatusWindow();
-
- void setPointsNeeded(const AttributesT id,
- const int needed);
-
- static void updateHPBar(ProgressBar *const bar,
- const bool showMax = false);
- void updateMPBar(ProgressBar *bar, const bool showMax = false) const;
- static void updateJobBar(ProgressBar *const bar,
- const bool percent = true);
- static void updateXPBar(ProgressBar *const bar,
- const bool percent = true);
- static void updateWeightBar(ProgressBar *const bar);
- static void updateInvSlotsBar(ProgressBar *const bar);
- static void updateMoneyBar(ProgressBar *const bar);
- static void updateArrowsBar(ProgressBar *const bar);
- void updateStatusBar(ProgressBar *const bar,
- const bool percent = true) const;
- static void updateProgressBar(ProgressBar *const bar,
- const int64_t value,
- const int64_t max,
- const bool percent);
- static void updateProgressBar(ProgressBar *const bar,
- const AttributesT id,
- const bool percent = true);
-
- void action(const ActionEvent &event) override;
-
- void attributeChanged(const AttributesT id,
- const int64_t oldVal,
- const int64_t newVal) override final;
-
- void updateLevelLabel();
-
- private:
- void addTabs();
- void addTab(const std::string &name);
- void addTabBasic(const std::string &name);
-
- static std::string translateLetter(const char *const letters);
- static std::string translateLetter2(const std::string &letters);
-
- STD_VECTOR<StatsPage*> mPages;
-
- TabbedArea *mTabs A_NONNULLPOINTER;
- Label *mLvlLabel A_NONNULLPOINTER;
- Label *mMoneyLabel A_NONNULLPOINTER;
- Label *mHpLabel A_NONNULLPOINTER;
- Label *mMpLabel A_NONNULLPOINTER;
- Label *mXpLabel A_NONNULLPOINTER;
- ProgressBar *mHpBar A_NONNULLPOINTER;
- ProgressBar *mMpBar A_NONNULLPOINTER;
- ProgressBar *mXpBar A_NONNULLPOINTER;
-
- Label *mJobLvlLabel;
- Label *mJobLabel;
- ProgressBar *mJobBar;
-
- StatsPageBasic *mBasicStatsPage;
- Button *mCopyButton;
-};
-
-extern StatusWindow *statusWindow;
-
-#endif // GUI_WINDOWS_STATUSWINDOW_H
diff --git a/src/gui/windows/textcommandeditor.cpp b/src/gui/windows/textcommandeditor.cpp
deleted file mode 100644
index 88d88af8a..000000000
--- a/src/gui/windows/textcommandeditor.cpp
+++ /dev/null
@@ -1,344 +0,0 @@
-/*
- * The ManaPlus Client
- * Copyright (C) 2009 The Mana World Development Team
- * Copyright (C) 2009-2010 Andrei Karas
- * Copyright (C) 2011-2017 The ManaPlus Developers
- *
- * This file is part of The ManaPlus Client.
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-#include "gui/windows/textcommandeditor.h"
-
-#include "spellmanager.h"
-#include "textcommand.h"
-
-#include "input/keyboardconfig.h"
-
-#include "gui/models/iconsmodel.h"
-#include "gui/models/targettypemodel.h"
-
-#include "gui/widgets/button.h"
-#include "gui/widgets/containerplacer.h"
-#include "gui/widgets/dropdown.h"
-#include "gui/widgets/inttextfield.h"
-#include "gui/widgets/label.h"
-#include "gui/widgets/layoutcell.h"
-
-#ifdef TMWA_SUPPORT
-#include "gui/models/magicschoolmodel.h"
-
-#include "gui/widgets/radiobutton.h"
-#endif // TMWA_SUPPORT
-
-#include "utils/delete2.h"
-
-#include "debug.h"
-
-#ifdef TMWA_SUPPORT
-const unsigned int MAGIC_START_ID = 340;
-#endif // TMWA_SUPPORT
-
-TextCommandEditor::TextCommandEditor(TextCommand *const command) :
- // TRANSLATORS: command editor name
- Window(_("Command Editor"), Modal_false, nullptr, "commandeditor.xml"),
- ActionListener(),
-#ifdef TMWA_SUPPORT
- mIsMagicCommand(command != nullptr ?
- (command->getCommandType() == TextCommandType::Magic) : false),
-#endif // TMWA_SUPPORT
- mCommand(command),
-#ifdef TMWA_SUPPORT
- // TRANSLATORS: command editor button
- mIsMagic(new RadioButton(this, _("magic"), "magic", mIsMagicCommand)),
- // TRANSLATORS: command editor button
- mIsOther(new RadioButton(this, _("other"), "magic", !mIsMagicCommand)),
-#endif // TMWA_SUPPORT
- // TRANSLATORS: command editor label
- mSymbolLabel(new Label(this, _("Symbol:"))),
- mSymbolTextField(new TextField(this)),
- // TRANSLATORS: command editor label
- mCommandLabel(new Label(this, _("Command:"))),
- mCommandTextField(new TextField(this)),
- // TRANSLATORS: command editor label
- mCommentLabel(new Label(this, _("Comment:"))),
- mCommentTextField(new TextField(this)),
- mTargetTypeModel(new TargetTypeModel),
- // TRANSLATORS: command editor label
- mTypeLabel(new Label(this, _("Target Type:"))),
- mTypeDropDown(new DropDown(this, mTargetTypeModel)),
- mIconsModel(new IconsModel),
- // TRANSLATORS: command editor label
- mIconLabel(new Label(this, _("Icon:"))),
- mIconDropDown(new DropDown(this, mIconsModel)),
-#ifdef TMWA_SUPPORT
- // TRANSLATORS: command editor label
- mManaLabel(new Label(this, _("Mana:"))),
- mManaField(new IntTextField(this, 0)),
- // TRANSLATORS: command editor label
- mMagicLvlLabel(new Label(this, _("Magic level:"))),
- mMagicLvlField(new IntTextField(this, 0)),
- mMagicSchoolModel(new MagicSchoolModel),
- // TRANSLATORS: command editor label
- mSchoolLabel(new Label(this, _("Magic School:"))),
- mSchoolDropDown(new DropDown(this, mMagicSchoolModel)),
- // TRANSLATORS: command editor label
- mSchoolLvlLabel(new Label(this, _("School level:"))),
- mSchoolLvlField(new IntTextField(this, 0)),
-#endif // TMWA_SUPPORT
- // TRANSLATORS: command editor button
- mCancelButton(new Button(this, _("Cancel"), "cancel", this)),
- // TRANSLATORS: command editor button
- mSaveButton(new Button(this, _("Save"), "save", this)),
- // TRANSLATORS: command editor button
- mDeleteButton(new Button(this, _("Delete"), "delete", this)),
- mEnabledKeyboard(keyboard.isEnabled())
-{
- const int w = 350;
- const int h = 370;
-
- keyboard.setEnabled(false);
-
- setWindowName("TextCommandEditor");
- setDefaultSize(w, h, ImagePosition::CENTER);
-
-#ifdef TMWA_SUPPORT
- mIsMagic->setActionEventId("magic");
- mIsMagic->addActionListener(this);
-
- mIsOther->setActionEventId("other");
- mIsOther->addActionListener(this);
-
- mManaField->setRange(0, 500);
- mManaField->setWidth(20);
-
- mMagicLvlField->setRange(0, 5);
- mMagicLvlField->setWidth(20);
-
- mSchoolDropDown->setActionEventId("school");
- mSchoolDropDown->addActionListener(this);
- mSchoolDropDown->setSelected(0);
-
- mSchoolLvlField->setRange(0, 5);
- mSchoolLvlField->setWidth(20);
-#endif // TMWA_SUPPORT
-
- mTypeDropDown->setActionEventId("type");
- mTypeDropDown->addActionListener(this);
-
- mIconDropDown->setActionEventId("icon");
- mIconDropDown->addActionListener(this);
- if (mCommand != nullptr)
- mIconDropDown->setSelectedString(mCommand->getIcon());
-
- mSaveButton->adjustSize();
- mCancelButton->adjustSize();
- mDeleteButton->adjustSize();
-
- if (command != nullptr)
- {
-#ifdef TMWA_SUPPORT
- if (command->getCommandType() == TextCommandType::Magic)
- showControls(Visible_true);
- else
- showControls(Visible_false);
-
- mManaField->setValue(command->getMana());
- mMagicLvlField->setValue(command->getBaseLvl());
- mSchoolDropDown->setSelected(CAST_S32(command->getSchool())
- - MAGIC_START_ID);
- mSchoolLvlField->setValue(command->getSchoolLvl());
-#endif // TMWA_SUPPORT
- }
-
- ContainerPlacer placer;
- placer = getPlacer(0, 0);
-
-#ifdef TMWA_SUPPORT
- placer(0, 0, mIsMagic, 1);
- placer(2, 0, mIsOther, 1);
- placer(0, 1, mSymbolLabel, 2).setPadding(3);
- placer(2, 1, mSymbolTextField, 3).setPadding(3);
- placer(0, 2, mCommandLabel, 2).setPadding(3);
- placer(2, 2, mCommandTextField, 4).setPadding(3);
-
- placer(0, 3, mCommentLabel, 2).setPadding(3);
- placer(2, 3, mCommentTextField, 4).setPadding(3);
-
- placer(0, 4, mTypeLabel, 2).setPadding(3);
- placer(2, 4, mTypeDropDown, 3).setPadding(3);
-
- placer(0, 5, mIconLabel, 2).setPadding(3);
- placer(2, 5, mIconDropDown, 3).setPadding(3);
-
- placer(0, 6, mManaLabel, 2).setPadding(3);
- placer(2, 6, mManaField, 3).setPadding(3);
- placer(0, 7, mMagicLvlLabel, 2).setPadding(3);
- placer(2, 7, mMagicLvlField, 3).setPadding(3);
-
- placer(0, 8, mSchoolLabel, 2).setPadding(3);
- placer(2, 8, mSchoolDropDown, 3).setPadding(3);
- placer(0, 9, mSchoolLvlLabel, 2).setPadding(3);
- placer(2, 9, mSchoolLvlField, 3).setPadding(3);
-
- placer(0, 10, mSaveButton, 2).setPadding(3);
- placer(2, 10, mCancelButton, 2).setPadding(3);
- placer(4, 10, mDeleteButton, 2).setPadding(3);
-#else // TMWA_SUPPORT
-
- placer(0, 0, mSymbolLabel, 2).setPadding(3);
- placer(2, 0, mSymbolTextField, 3).setPadding(3);
- placer(0, 1, mCommandLabel, 2).setPadding(3);
- placer(2, 1, mCommandTextField, 4).setPadding(3);
-
- placer(0, 2, mCommentLabel, 2).setPadding(3);
- placer(2, 2, mCommentTextField, 4).setPadding(3);
-
- placer(0, 3, mTypeLabel, 2).setPadding(3);
- placer(2, 3, mTypeDropDown, 3).setPadding(3);
-
- placer(0, 4, mIconLabel, 2).setPadding(3);
- placer(2, 4, mIconDropDown, 3).setPadding(3);
-
- placer(0, 5, mSaveButton, 2).setPadding(3);
- placer(2, 5, mCancelButton, 2).setPadding(3);
- placer(4, 5, mDeleteButton, 2).setPadding(3);
-#endif // TMWA_SUPPORT
-
- setWidth(w);
- setHeight(h);
-
- reflowLayout(w);
-
- center();
-}
-
-void TextCommandEditor::postInit()
-{
- Window::postInit();
- enableVisibleSound(true);
- setVisible(Visible_true);
-}
-
-TextCommandEditor::~TextCommandEditor()
-{
- delete2(mIconsModel);
- delete2(mTargetTypeModel);
-#ifdef TMWA_SUPPORT
- delete2(mMagicSchoolModel);
-#endif // TMWA_SUPPORT
-}
-
-void TextCommandEditor::action(const ActionEvent &event)
-{
- const std::string &eventId = event.getId();
- if (eventId == "save")
- {
- save();
- scheduleDelete();
- }
- else if (eventId == "cancel")
- {
- scheduleDelete();
- }
- else if (eventId == "delete")
- {
- deleteCommand();
- scheduleDelete();
- }
-#ifdef TMWA_SUPPORT
- else if (eventId == "magic")
- {
- mIsMagicCommand = true;
- showControls(Visible_true);
- }
- else if (eventId == "other")
- {
- mIsMagicCommand = false;
- showControls(Visible_false);
- }
-#endif // TMWA_SUPPORT
-}
-
-#ifdef TMWA_SUPPORT
-void TextCommandEditor::showControls(const Visible show)
-{
- mManaField->setVisible(show);
- mManaLabel->setVisible(show);
- mMagicLvlLabel->setVisible(show);
- mMagicLvlField->setVisible(show);
- mSchoolLabel->setVisible(show);
- mSchoolDropDown->setVisible(show);
- mSchoolLvlLabel->setVisible(show);
- mSchoolLvlField->setVisible(show);
-}
-#endif // TMWA_SUPPORT
-
-void TextCommandEditor::scheduleDelete()
-{
- keyboard.setEnabled(mEnabledKeyboard);
- Window::scheduleDelete();
-}
-
-void TextCommandEditor::save()
-{
- if (mCommand == nullptr)
- return;
-#ifdef TMWA_SUPPORT
- if (mIsMagicCommand)
- mCommand->setCommandType(TextCommandType::Magic);
- else
- mCommand->setCommandType(TextCommandType::Text);
-#endif // TMWA_SUPPORT
-
- mCommand->setSymbol(mSymbolTextField->getText());
- mCommand->setCommand(mCommandTextField->getText());
- mCommand->setComment(mCommentTextField->getText());
- mCommand->setTargetType(
- static_cast<CommandTargetT>(mTypeDropDown->getSelected()));
- mCommand->setIcon(mIconDropDown->getSelectedString());
-
-#ifdef TMWA_SUPPORT
- mCommand->setMana(mManaField->getValue());
- mCommand->setBaseLvl(mMagicLvlField->getValue());
- mCommand->setSchool(static_cast<MagicSchoolT>(
- mSchoolDropDown->getSelected() + MAGIC_START_ID));
- mCommand->setSchoolLvl(mSchoolLvlField->getValue());
-#endif // TMWA_SUPPORT
-
- if (spellManager != nullptr)
- spellManager->save();
-}
-
-void TextCommandEditor::deleteCommand()
-{
- if (mCommand == nullptr)
- return;
- mCommand->setSymbol("");
- mCommand->setCommand("");
- mCommand->setComment("");
- mCommand->setTargetType(CommandTarget::NoTarget);
- mCommand->setIcon("");
-#ifdef TMWA_SUPPORT
- mCommand->setCommandType(TextCommandType::Text);
- mCommand->setMana(0);
- mCommand->setBaseLvl(0);
- mCommand->setSchool(MagicSchool::SkillMagic);
- mCommand->setSchoolLvl(0);
-#endif // TMWA_SUPPORT
-
- if (spellManager != nullptr)
- spellManager->save();
-}
diff --git a/src/gui/windows/textcommandeditor.h b/src/gui/windows/textcommandeditor.h
deleted file mode 100644
index 88bfd48d4..000000000
--- a/src/gui/windows/textcommandeditor.h
+++ /dev/null
@@ -1,116 +0,0 @@
-/*
- * The ManaPlus Client
- * Copyright (C) 2009 The Mana World Development Team
- * Copyright (C) 2009-2010 Andrei Karas
- * Copyright (C) 2011-2017 The ManaPlus Developers
- *
- * This file is part of The ManaPlus Client.
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-#ifndef GUI_WINDOWS_TEXTCOMMANDEDITOR_H
-#define GUI_WINDOWS_TEXTCOMMANDEDITOR_H
-
-#include "gui/widgets/window.h"
-
-#include "listeners/actionlistener.h"
-
-class Button;
-class DropDown;
-class IconsModel;
-class IntTextField;
-class Label;
-#ifdef TMWA_SUPPORT
-class MagicSchoolModel;
-#endif // TMWA_SUPPORT
-
-class RadioButton;
-class TargetTypeModel;
-class TextCommand;
-class TextField;
-
-class TextCommandEditor final : public Window,
- public ActionListener
-{
- public:
- /**
- * Constructor.
- */
- explicit TextCommandEditor(TextCommand *const command);
-
- A_DELETE_COPY(TextCommandEditor)
-
- /**
- * Destructor.
- */
- ~TextCommandEditor();
-
- void postInit() override final;
-
- void action(const ActionEvent &event) override final;
-
- void scheduleDelete() override final;
-
- private:
-#ifdef TMWA_SUPPORT
- void showControls(const Visible show);
-#endif // TMWA_SUPPORT
-
- void save();
-
- void deleteCommand();
-
-#ifdef TMWA_SUPPORT
- bool mIsMagicCommand;
-#endif // TMWA_SUPPORT
-
- TextCommand* mCommand;
-#ifdef TMWA_SUPPORT
- RadioButton* mIsMagic A_NONNULLPOINTER;
-#endif // TMWA_SUPPORT
-
- RadioButton* mIsOther A_NONNULLPOINTER;
- Label* mSymbolLabel A_NONNULLPOINTER;
- TextField* mSymbolTextField A_NONNULLPOINTER;
- Label* mCommandLabel A_NONNULLPOINTER;
- TextField* mCommandTextField A_NONNULLPOINTER;
- Label* mCommentLabel A_NONNULLPOINTER;
- TextField* mCommentTextField A_NONNULLPOINTER;
- TargetTypeModel* mTargetTypeModel A_NONNULLPOINTER;
- Label* mTypeLabel A_NONNULLPOINTER;
- DropDown* mTypeDropDown A_NONNULLPOINTER;
- IconsModel* mIconsModel A_NONNULLPOINTER;
- Label* mIconLabel A_NONNULLPOINTER;
- DropDown* mIconDropDown A_NONNULLPOINTER;
-#ifdef TMWA_SUPPORT
- Label* mManaLabel A_NONNULLPOINTER;
- IntTextField* mManaField A_NONNULLPOINTER;
- Label* mMagicLvlLabel A_NONNULLPOINTER;
- IntTextField* mMagicLvlField A_NONNULLPOINTER;
- MagicSchoolModel* mMagicSchoolModel A_NONNULLPOINTER;
- Label* mSchoolLabel A_NONNULLPOINTER;
- DropDown* mSchoolDropDown A_NONNULLPOINTER;
- Label* mSchoolLvlLabel A_NONNULLPOINTER;
- IntTextField* mSchoolLvlField A_NONNULLPOINTER;
-#endif // TMWA_SUPPORT
-
- Button* mCancelButton A_NONNULLPOINTER;
- Button* mSaveButton A_NONNULLPOINTER;
- Button* mDeleteButton A_NONNULLPOINTER;
-
- bool mEnabledKeyboard;
-};
-
-#endif // GUI_WINDOWS_TEXTCOMMANDEDITOR_H
diff --git a/src/gui/windows/textdialog.cpp b/src/gui/windows/textdialog.cpp
deleted file mode 100644
index 87c9dcfa8..000000000
--- a/src/gui/windows/textdialog.cpp
+++ /dev/null
@@ -1,135 +0,0 @@
-/*
- * The ManaPlus Client
- * Copyright (C) 2004-2009 The Mana World Development Team
- * Copyright (C) 2009-2010 The Mana Developers
- * Copyright (C) 2011-2017 The ManaPlus Developers
- *
- * This file is part of The ManaPlus Client.
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-#include "gui/windows/textdialog.h"
-
-#include "input/keyboardconfig.h"
-
-#include "gui/widgets/button.h"
-#include "gui/widgets/label.h"
-#include "gui/widgets/passwordfield.h"
-
-#include "utils/gettext.h"
-
-#include "gui/fonts/font.h"
-
-#include "debug.h"
-
-int TextDialog::instances = 0;
-
-namespace
-{
- const std::string emptyStr;
-} // namespace
-
-TextDialog::TextDialog(const std::string &restrict title,
- const std::string &restrict msg,
- Window *const parent,
- const bool isPassword) :
- Window(title, Modal_true, parent, "textdialog.xml"),
- ActionListener(),
- mTextField(nullptr),
- mPasswordField(nullptr),
- // TRANSLATORS: text dialog button
- mOkButton(new Button(this, _("OK"), "OK", this)),
- mEnabledKeyboard(keyboard.isEnabled())
-{
- keyboard.setEnabled(false);
-
- Label *const textLabel = new Label(this, msg);
- // TRANSLATORS: text dialog button
- Button *const cancelButton = new Button(this, _("Cancel"), "CANCEL", this);
-
- place(0, 0, textLabel, 4);
- if (isPassword)
- {
- mPasswordField = new PasswordField(this);
- place(0, 1, mPasswordField, 4);
- }
- else
- {
- mTextField = new TextField(this);
- place(0, 1, mTextField, 4);
- }
- place(2, 2, mOkButton);
- place(3, 2, cancelButton);
-
- int width = getFont()->getWidth(title);
- if (width < textLabel->getWidth())
- width = textLabel->getWidth();
- reflowLayout(CAST_S32(width + 20));
-}
-
-void TextDialog::postInit()
-{
- Window::postInit();
- if (getParent() != nullptr)
- {
- setLocationRelativeTo(getParent());
- getParent()->moveToTop(this);
- }
- setVisible(Visible_true);
- requestModalFocus();
- if (mPasswordField != nullptr)
- mPasswordField->requestFocus();
- else if (mTextField != nullptr)
- mTextField->requestFocus();
-
- instances++;
-}
-
-TextDialog::~TextDialog()
-{
- instances--;
-}
-
-void TextDialog::action(const ActionEvent &event)
-{
- if (event.getId() == "CANCEL")
- setActionEventId("~" + getActionEventId());
-
- distributeActionEvent();
- close();
-}
-
-const std::string &TextDialog::getText() const
-{
- if (mTextField != nullptr)
- return mTextField->getText();
- else if (mPasswordField != nullptr)
- return mPasswordField->getText();
- return emptyStr;
-}
-
-void TextDialog::setText(const std::string &text)
-{
- if (mTextField != nullptr)
- mTextField->setText(text);
- else if (mPasswordField != nullptr)
- mPasswordField->setText(text);
-}
-
-void TextDialog::close()
-{
- keyboard.setEnabled(mEnabledKeyboard);
- scheduleDelete();
-}
diff --git a/src/gui/windows/textdialog.h b/src/gui/windows/textdialog.h
deleted file mode 100644
index a2901e04e..000000000
--- a/src/gui/windows/textdialog.h
+++ /dev/null
@@ -1,85 +0,0 @@
-/*
- * The ManaPlus Client
- * Copyright (C) 2004-2009 The Mana World Development Team
- * Copyright (C) 2009-2010 The Mana Developers
- * Copyright (C) 2011-2017 The ManaPlus Developers
- *
- * This file is part of The ManaPlus Client.
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-#ifndef GUI_WINDOWS_TEXTDIALOG_H
-#define GUI_WINDOWS_TEXTDIALOG_H
-
-#include "gui/widgets/window.h"
-
-#include "listeners/actionlistener.h"
-
-class Button;
-class PasswordField;
-class TextField;
-
-/**
-* An option dialog.
- *
- * \ingroup GUI
- */
-class TextDialog final : public Window,
- public ActionListener
-{
- public:
- /**
- * Constructor.
- *
- * @see Window::Window
- */
- TextDialog(const std::string &restrict title,
- const std::string &restrict msg,
- Window *const parent = nullptr,
- const bool isPassword = false);
-
- A_DELETE_COPY(TextDialog)
-
- ~TextDialog();
-
- void postInit() override final;
-
- /**
- * Called when receiving actions from the widgets.
- */
- void action(const ActionEvent &event) override final;
-
- /**
- * Get the text in the textfield
- */
- const std::string &getText() const A_WARN_UNUSED;
-
- void setText(const std::string &text);
-
- static bool isActive() noexcept2 A_WARN_UNUSED
- { return instances != 0; }
-
- void close() override final;
-
- private:
- static int instances;
-
- TextField *mTextField;
- PasswordField *mPasswordField;
- Button *mOkButton;
- bool mEnabledKeyboard;
-};
-
-#endif // GUI_WINDOWS_TEXTDIALOG_H
diff --git a/src/gui/windows/textselectdialog.cpp b/src/gui/windows/textselectdialog.cpp
deleted file mode 100644
index 11100d2d8..000000000
--- a/src/gui/windows/textselectdialog.cpp
+++ /dev/null
@@ -1,192 +0,0 @@
-/*
- * The ManaPlus Client
- * Copyright (C) 2004-2009 The Mana World Development Team
- * Copyright (C) 2009-2010 The Mana Developers
- * Copyright (C) 2011-2017 The ManaPlus Developers
- *
- * This file is part of The ManaPlus Client.
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-#include "gui/windows/textselectdialog.h"
-
-#include "enums/gui/layouttype.h"
-
-#include "gui/windows/setupwindow.h"
-
-#include "gui/models/namesmodel.h"
-
-#include "gui/widgets/button.h"
-#include "gui/widgets/containerplacer.h"
-#include "gui/widgets/createwidget.h"
-#include "gui/widgets/layout.h"
-#include "gui/widgets/listbox.h"
-#include "gui/widgets/scrollarea.h"
-
-#include "utils/delete2.h"
-#include "utils/gettext.h"
-
-#include "debug.h"
-
-TextSelectDialog::TextSelectDialog(const std::string &name,
- const std::string &selectButton,
- const AllowQuit allowQuit) :
- // TRANSLATORS: sell dialog name
- Window(name, Modal_false, nullptr, "sell.xml"),
- ActionListener(),
- SelectionListener(),
- mSelectButtonName(selectButton),
- mText(),
- mSelectButton(nullptr),
- mQuitButton(nullptr),
- mItemList(nullptr),
- mScrollArea(nullptr),
- mModel(nullptr),
- mAllowQuit(allowQuit),
- mTag(0)
-{
-}
-
-void TextSelectDialog::postInit()
-{
- Window::postInit();
- setWindowName("TextSelectDialog");
- setResizable(true);
- setCloseButton(mAllowQuit == AllowQuit_true);
- setStickyButtonLock(true);
- setMinWidth(260);
- setMinHeight(220);
- setDefaultSize(260, 230, ImagePosition::CENTER);
-
- if (setupWindow != nullptr)
- setupWindow->registerWindowForReset(this);
-
- setActionEventId("OK");
- mModel = new NamesModel;
- mItemList = CREATEWIDGETR(ListBox,
- this,
- mModel,
- "listbox.xml");
- mScrollArea = new ScrollArea(this, mItemList,
- fromBool(getOptionBool("showbackground"), Opaque),
- "sell_background.xml");
- mScrollArea->setHorizontalScrollPolicy(ScrollArea::SHOW_NEVER);
-
- mSelectButton = new Button(this,
- mSelectButtonName,
- "select",
- this);
- if (mAllowQuit == AllowQuit_true)
- {
- // TRANSLATORS: sell dialog button
- mQuitButton = new Button(this, _("Quit"), "quit", this);
- }
-
- mSelectButton->setEnabled(false);
-
- mItemList->setDistributeMousePressed(false);
- mItemList->addSelectionListener(this);
- mItemList->setActionEventId("item");
- mItemList->addActionListener(this);
-
- ContainerPlacer placer;
- placer = getPlacer(0, 0);
-
- placer(0, 0, mScrollArea, 8, 5).setPadding(3);
- if (mQuitButton != nullptr)
- {
- placer(6, 5, mSelectButton);
- placer(7, 5, mQuitButton);
- }
- else
- {
- placer(7, 5, mSelectButton);
- }
-
- Layout &layout = getLayout();
- layout.setRowHeight(0, LayoutType::SET);
-
- center();
- loadWindowState();
-
- setVisible(Visible_true);
- enableVisibleSound(true);
-}
-
-TextSelectDialog::~TextSelectDialog()
-{
- delete2(mModel);
-}
-
-void TextSelectDialog::action(const ActionEvent &event)
-{
- const std::string &eventId = event.getId();
-
- if (eventId == "quit")
- {
- close();
- return;
- }
-
- const int selectedItem = mItemList->getSelected();
-
- // The following actions require a valid item selection
- if (selectedItem == -1 ||
- selectedItem >= mModel->getNumberOfElements())
- {
- return;
- }
- else if (eventId == "select")
- {
- const int index = mItemList->getSelected();
- if (index < 0 || index >= CAST_S32(mModel->size()))
- return;
- mText = mModel->getElementAt(index);
- distributeActionEvent();
- close();
- }
-}
-
-void TextSelectDialog::updateButtonsAndLabels()
-{
- mSelectButton->setEnabled(mItemList->getSelected() > -1);
-}
-
-void TextSelectDialog::valueChanged(const SelectionEvent &event A_UNUSED)
-{
- updateButtonsAndLabels();
-}
-
-void TextSelectDialog::setVisible(Visible visible)
-{
- Window::setVisible(visible);
-
- if (visible == Visible_true)
- {
- if (mItemList != nullptr)
- mItemList->requestFocus();
- }
- else
- {
- scheduleDelete();
- }
-}
-
-void TextSelectDialog::addText(const std::string &text)
-{
- if (text.empty())
- return;
- mModel->add(text);
-}
diff --git a/src/gui/windows/textselectdialog.h b/src/gui/windows/textselectdialog.h
deleted file mode 100644
index 30e596d32..000000000
--- a/src/gui/windows/textselectdialog.h
+++ /dev/null
@@ -1,104 +0,0 @@
-/*
- * The ManaPlus Client
- * Copyright (C) 2004-2009 The Mana World Development Team
- * Copyright (C) 2009-2010 The Mana Developers
- * Copyright (C) 2011-2017 The ManaPlus Developers
- *
- * This file is part of The ManaPlus Client.
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-#ifndef GUI_WINDOWS_TEXTSELECTDIALOG_H
-#define GUI_WINDOWS_TEXTSELECTDIALOG_H
-
-#include "gui/widgets/window.h"
-
-#include "enums/simpletypes/allowquit.h"
-
-#include "listeners/actionlistener.h"
-#include "listeners/selectionlistener.h"
-
-class Button;
-class ScrollArea;
-class NamesModel;
-class ListBox;
-
-class TextSelectDialog notfinal : public Window,
- public ActionListener,
- private SelectionListener
-{
- public:
- /**
- * Constructor.
- */
- TextSelectDialog(const std::string &name,
- const std::string &selectButton,
- const AllowQuit allowQuit);
-
- A_DELETE_COPY(TextSelectDialog)
-
- /**
- * Destructor
- */
- ~TextSelectDialog();
-
- /**
- * Called when receiving actions from the widgets.
- */
- void action(const ActionEvent &event) override final;
-
- /**
- * Updates labels according to selected item.
- *
- * @see SelectionListener::selectionChanged
- */
- void valueChanged(const SelectionEvent &event) override final;
-
- /**
- * Sets the visibility of this window.
- */
- void setVisible(Visible visible) override final;
-
- void postInit() override;
-
- void addText(const std::string &text);
-
- std::string getText() const noexcept2 A_WARN_UNUSED
- { return mText; }
-
- void setTag(const int tag) noexcept2
- { mTag = tag; }
-
- int getTag() const noexcept2 A_WARN_UNUSED
- { return mTag; }
-
- protected:
- /**
- * Updates the state of buttons and labels.
- */
- void updateButtonsAndLabels();
-
- std::string mSelectButtonName;
- std::string mText;
- Button *mSelectButton A_NONNULLPOINTER;
- Button *mQuitButton A_NONNULLPOINTER;
- ListBox *mItemList A_NONNULLPOINTER;
- ScrollArea *mScrollArea A_NONNULLPOINTER;
- NamesModel *mModel A_NONNULLPOINTER;
- AllowQuit mAllowQuit;
- int mTag;
-};
-
-#endif // GUI_WINDOWS_TEXTSELECTDIALOG_H
diff --git a/src/gui/windows/tradewindow.cpp b/src/gui/windows/tradewindow.cpp
deleted file mode 100644
index 66f4e0550..000000000
--- a/src/gui/windows/tradewindow.cpp
+++ /dev/null
@@ -1,553 +0,0 @@
-/*
- * The ManaPlus Client
- * Copyright (C) 2004-2009 The Mana World Development Team
- * Copyright (C) 2009-2010 The Mana Developers
- * Copyright (C) 2011-2017 The ManaPlus Developers
- *
- * This file is part of The ManaPlus Client.
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-#include "gui/windows/tradewindow.h"
-
-#include "configuration.h"
-#include "game.h"
-
-#include "being/localplayer.h"
-#include "being/playerinfo.h"
-#include "being/playerrelations.h"
-
-#include "enums/gui/layouttype.h"
-
-#include "gui/gui.h"
-
-#include "gui/fonts/font.h"
-
-#include "gui/windows/inventorywindow.h"
-#include "gui/windows/itemamountwindow.h"
-#include "gui/windows/setupwindow.h"
-
-#include "gui/widgets/button.h"
-#include "gui/widgets/containerplacer.h"
-#include "gui/widgets/itemcontainer.h"
-#include "gui/widgets/label.h"
-#include "gui/widgets/layout.h"
-#include "gui/widgets/scrollarea.h"
-#include "gui/widgets/textfield.h"
-
-#include "gui/widgets/tabs/chat/chattab.h"
-
-#include "resources/db/unitsdb.h"
-
-#include "resources/item/item.h"
-
-#include "net/net.h"
-#include "net/tradehandler.h"
-
-#include "utils/delete2.h"
-#include "utils/gettext.h"
-
-#include "debug.h"
-
-TradeWindow *tradeWindow = nullptr;
-
-// TRANSLATORS: trade window button
-#define CAPTION_PROPOSE _("Propose trade")
-// TRANSLATORS: trade window button
-#define CAPTION_CONFIRMED _("Confirmed. Waiting...")
-// TRANSLATORS: trade window button
-#define CAPTION_ACCEPT _("Agree trade")
-// TRANSLATORS: trade window button
-#define CAPTION_ACCEPTED _("Agreed. Waiting...")
-
-TradeWindow::TradeWindow() :
- // TRANSLATORS: trade window caption
- Window(_("Trade: You"), Modal_false, nullptr, "trade.xml"),
- ActionListener(),
- SelectionListener(),
- mMyInventory(new Inventory(InventoryType::Trade)),
- mPartnerInventory(new Inventory(InventoryType::Trade)),
- mMyItemContainer(new ItemContainer(this, mMyInventory)),
- mPartnerItemContainer(new ItemContainer(this, mPartnerInventory)),
- // TRANSLATORS: trade window money label
- mMoneyLabel(new Label(this, strprintf(_("You get %s"), ""))),
- // TRANSLATORS: trade window button
- mAddButton(new Button(this, _("Add"), "add", this)),
- mOkButton(new Button(this, "", "", this)), // Will be filled in later
- // TRANSLATORS: trade window money change button
- mMoneyChangeButton(new Button(this, _("Change"), "money", this)),
- mMoneyField(new TextField(this)),
- mAutoAddItem(nullptr),
- mAutoAddToNick(""),
- mGotMoney(0),
- mGotMaxMoney(0),
- mAutoMoney(0),
- mAutoAddAmount(0),
- mStatus(PROPOSING),
- mOkOther(false),
- mOkMe(false)
-{
- setWindowName("Trade");
- setResizable(true);
- setCloseButton(true);
- setStickyButtonLock(true);
- setDefaultSize(386, 180, ImagePosition::CENTER);
- setMinWidth(310);
- setMinHeight(180);
-
- if (setupWindow != nullptr)
- setupWindow->registerWindowForReset(this);
-
- const Font *const fnt = mOkButton->getFont();
- int width = std::max(fnt->getWidth(CAPTION_PROPOSE),
- fnt->getWidth(CAPTION_CONFIRMED));
- width = std::max(width, fnt->getWidth(CAPTION_ACCEPT));
- width = std::max(width, fnt->getWidth(CAPTION_ACCEPTED));
-
- mOkButton->setWidth(8 + width);
-
- mMyItemContainer->addSelectionListener(this);
-
- ScrollArea *const myScroll = new ScrollArea(this, mMyItemContainer,
- Opaque_true, "trade_background.xml");
- myScroll->setHorizontalScrollPolicy(ScrollArea::SHOW_NEVER);
-
- mPartnerItemContainer->addSelectionListener(this);
-
- ScrollArea *const partnerScroll = new ScrollArea(this,
- mPartnerItemContainer,
- Opaque_true, "trade_background.xml");
- partnerScroll->setHorizontalScrollPolicy(ScrollArea::SHOW_NEVER);
-
- // TRANSLATORS: trade window money label
- Label *const moneyLabel2 = new Label(this, _("You give:"));
-
- mMoneyField->setWidth(40);
-
- place(1, 0, mMoneyLabel);
- place(0, 1, myScroll).setPadding(3);
- place(1, 1, partnerScroll).setPadding(3);
- ContainerPlacer placer = getPlacer(0, 0);
- placer(0, 0, moneyLabel2);
- placer(1, 0, mMoneyField, 2);
- placer(3, 0, mMoneyChangeButton).setHAlign(LayoutCell::LEFT);
- placer = getPlacer(0, 2);
- placer(0, 0, mAddButton);
- placer(1, 0, mOkButton);
- Layout &layout = getLayout();
- layout.extend(0, 2, 2, 1);
- layout.setRowHeight(1, LayoutType::SET);
- layout.setRowHeight(2, 0);
- layout.setColWidth(0, LayoutType::SET);
- layout.setColWidth(1, LayoutType::SET);
-
- loadWindowState();
- enableVisibleSound(true);
-
- reset();
-}
-
-TradeWindow::~TradeWindow()
-{
- delete2(mMyInventory);
- delete2(mPartnerInventory);
-}
-
-void TradeWindow::setMoney(const int amount)
-{
- if (amount < 0 || amount < mGotMaxMoney)
- {
- if (config.getBoolValue("securetrades"))
- {
- close();
- return;
- }
- mMoneyLabel->setForegroundColorAll(
- getThemeColor(ThemeColorId::WARNING),
- getThemeColor(ThemeColorId::WARNING_OUTLINE));
- }
- else
- {
- mMoneyLabel->setForegroundColorAll(
- getThemeColor(ThemeColorId::LABEL),
- getThemeColor(ThemeColorId::LABEL_OUTLINE));
- mGotMaxMoney = amount;
- }
-
- mGotMoney = amount;
- // TRANSLATORS: trade window money label
- mMoneyLabel->setCaption(strprintf(_("You get %s"),
- UnitsDb::formatCurrency(amount).c_str()));
- mMoneyLabel->adjustSize();
-}
-
-void TradeWindow::addItem(const int id,
- const ItemTypeT type,
- const bool own,
- const int quantity,
- const uint8_t refine,
- const ItemColor color,
- const Identified identified,
- const Damaged damaged,
- const Favorite favorite) const
-{
- Inventory *const inv = own ? mMyInventory : mPartnerInventory;
- inv->addItem(id,
- type,
- quantity,
- refine,
- color,
- identified,
- damaged,
- favorite,
- Equipm_false,
- Equipped_false);
-}
-
-void TradeWindow::addItem2(const int id,
- const ItemTypeT type,
- const int *const cards,
- const ItemOptionsList *const options,
- const int sz,
- const bool own,
- const int quantity,
- const uint8_t refine,
- const ItemColor color,
- const Identified identified,
- const Damaged damaged,
- const Favorite favorite,
- const Equipm equipment) const
-{
- Inventory *const inv = own ? mMyInventory : mPartnerInventory;
- const int slot = inv->addItem(id,
- type,
- quantity,
- refine,
- color,
- identified,
- damaged,
- favorite,
- equipment,
- Equipped_false);
- if (slot >= 0)
- {
- inv->setCards(slot, cards, sz);
- inv->setOptions(slot, options);
- }
-}
-
-void TradeWindow::changeQuantity(const int index, const bool own,
- const int quantity) const
-{
- Item *item;
- if (own)
- item = mMyInventory->getItem(index);
- else
- item = mPartnerInventory->getItem(index);
- if (item != nullptr)
- item->setQuantity(quantity);
-}
-
-void TradeWindow::increaseQuantity(const int index, const bool own,
- const int quantity) const
-{
- Item *item;
- if (own)
- item = mMyInventory->getItem(index);
- else
- item = mPartnerInventory->getItem(index);
- if (item != nullptr)
- item->increaseQuantity(quantity);
-}
-
-void TradeWindow::reset()
-{
- mMyInventory->clear();
- mPartnerInventory->clear();
- mOkOther = false;
- mOkMe = false;
- setMoney(0);
- mMoneyField->setEnabled(true);
- mMoneyField->setText("");
- mMoneyLabel->setForegroundColorAll(
- getThemeColor(ThemeColorId::LABEL),
- getThemeColor(ThemeColorId::LABEL_OUTLINE));
- mAddButton->setEnabled(true);
- mMoneyChangeButton->setEnabled(true);
- mGotMoney = 0;
- mGotMaxMoney = 0;
- setStatus(PREPARING);
-}
-
-void TradeWindow::receivedOk(const bool own)
-{
- if (own)
- mOkMe = true;
- else
- mOkOther = true;
-
- if (mOkMe && mOkOther)
- setStatus(ACCEPTING);
-}
-
-void TradeWindow::completeTrade()
-{
- if (config.getBoolValue("tradescreenshot"))
- Game::createScreenshot(std::string());
- setVisible(Visible_false);
- reset();
-}
-
-void TradeWindow::tradeItem(const Item *const item, const int quantity,
- const bool check) const
-{
- if (check && !checkItem(item))
- return;
-
- tradeHandler->addItem(item, quantity);
-}
-
-void TradeWindow::valueChanged(const SelectionEvent &event)
-{
- if ((mMyItemContainer == nullptr) || (mPartnerItemContainer == nullptr))
- return;
-
- /* If an item is selected in one container, make sure no item is selected
- * in the other container.
- */
- if (event.getSource() == mMyItemContainer &&
- (mMyItemContainer->getSelectedItem() != nullptr))
- {
- mPartnerItemContainer->selectNone();
- }
- else if (mPartnerItemContainer->getSelectedItem() != nullptr)
- {
- mMyItemContainer->selectNone();
- }
-}
-
-void TradeWindow::setStatus(const Status s)
-{
- if (s == mStatus)
- return;
- mStatus = s;
-
- switch (s)
- {
- case PREPARING:
- mOkButton->setCaption(CAPTION_PROPOSE);
- mOkButton->setActionEventId("ok");
- break;
- case PROPOSING:
- mOkButton->setCaption(CAPTION_CONFIRMED);
- mOkButton->setActionEventId("");
- break;
- case ACCEPTING:
- mOkButton->setCaption(CAPTION_ACCEPT);
- mOkButton->setActionEventId("trade");
- break;
- case ACCEPTED:
- mOkButton->setCaption(CAPTION_ACCEPTED);
- mOkButton->setActionEventId("");
- break;
- default:
- break;
- }
-
- mOkButton->setEnabled((s != PROPOSING && s != ACCEPTED));
-}
-
-void TradeWindow::action(const ActionEvent &event)
-{
- if (inventoryWindow == nullptr)
- return;
-
- Item *const item = inventoryWindow->getSelectedItem();
- const std::string &eventId = event.getId();
-
- if (eventId == "add")
- {
- if (mStatus != PREPARING)
- return;
-
- if (!inventoryWindow->isWindowVisible())
- {
- inventoryWindow->setVisible(Visible_true);
- return;
- }
-
- if (item == nullptr)
- return;
-
- if (mMyInventory->getFreeSlot() == -1)
- return;
-
- if (!checkItem(item))
- return;
-
- // Choose amount of items to trade
- ItemAmountWindow::showWindow(ItemAmountWindowUsage::TradeAdd,
- this, item);
-
- setStatus(PREPARING);
- }
- else if (eventId == "cancel")
- {
- setVisible(Visible_false);
- reset();
- PlayerInfo::setTrading(Trading_false);
- tradeHandler->cancel();
- }
- else if (eventId == "ok")
- {
- mMoneyField->setEnabled(false);
- mAddButton->setEnabled(false);
- mMoneyChangeButton->setEnabled(false);
- receivedOk(true);
- setStatus(PROPOSING);
- tradeHandler->confirm();
- }
- else if (eventId == "trade")
- {
- receivedOk(true);
- setStatus(ACCEPTED);
- tradeHandler->finish();
- }
- else if (eventId == "money")
- {
- if (mStatus != PREPARING)
- return;
-
- int v = atoi(mMoneyField->getText().c_str());
- const int curMoney = PlayerInfo::getAttribute(Attributes::MONEY);
- if (v > curMoney)
- {
- if (localChatTab != nullptr)
- {
- // TRANSLATORS: trade error
- localChatTab->chatLog(_("You don't have enough money."),
- ChatMsgType::BY_SERVER);
- }
- v = curMoney;
- }
- tradeHandler->setMoney(v);
- mMoneyField->setText(strprintf("%d", v));
- }
-}
-
-void TradeWindow::close()
-{
- tradeHandler->cancel();
- clear();
-}
-
-void TradeWindow::clear()
-{
- mAutoAddItem = nullptr;
- mAutoAddToNick.clear();
- mAutoMoney = 0;
- mAutoAddAmount = 0;
- mGotMoney = 0;
- mGotMaxMoney = 0;
- mMoneyLabel->setForegroundColorAll(
- getThemeColor(ThemeColorId::LABEL),
- getThemeColor(ThemeColorId::LABEL_OUTLINE));
-}
-
-void TradeWindow::addAutoItem(const std::string &nick, Item* const item,
- const int amount)
-{
- mAutoAddToNick = nick;
- mAutoAddItem = item;
- mAutoAddAmount = amount;
-}
-
-void TradeWindow::addAutoMoney(const std::string &nick, const int money)
-{
- mAutoAddToNick = nick;
- mAutoMoney = money;
-}
-
-void TradeWindow::initTrade(const std::string &nick)
-{
- if (localPlayer == nullptr)
- return;
-
- if (!mAutoAddToNick.empty() && mAutoAddToNick == nick)
- {
- if ((mAutoAddItem != nullptr) && (mAutoAddItem->getQuantity() != 0))
- {
- const Inventory *const inv = PlayerInfo::getInventory();
- if (inv != nullptr)
- {
- const Item *const item = inv->findItem(mAutoAddItem->getId(),
- mAutoAddItem->getColor());
- if (item != nullptr)
- tradeItem(item, mAutoAddAmount);
- }
- }
- if (mAutoMoney != 0)
- {
- tradeHandler->setMoney(mAutoMoney);
- mMoneyField->setText(strprintf("%d", mAutoMoney));
- }
- }
- clear();
- if (!playerRelations.isGoodName(nick))
- setCaptionFont(gui->getSecureFont());
-}
-
-bool TradeWindow::checkItem(const Item *const item) const
-{
- if (item == nullptr)
- return false;
-
- const int itemId = item->getId();
- if (PlayerInfo::isItemProtected(itemId))
- return false;
- const Item *const tItem = mMyInventory->findItem(
- itemId, item->getColor());
-
- if ((tItem != nullptr) && (tItem->getQuantity() > 1
- || item->getQuantity() > 1))
- {
- if (localChatTab != nullptr)
- {
- // TRANSLATORS: trade error
- localChatTab->chatLog(_("Failed adding item. You can not "
- "overlap one kind of item on the window."),
- ChatMsgType::BY_SERVER);
- }
- return false;
- }
- if (Net::getNetworkType() != ServerType::TMWATHENA &&
- item->isEquipped() == Equipped_true)
- {
- if (localChatTab != nullptr)
- {
- localChatTab->chatLog(
- // TRANSLATORS: trade error
- _("Failed adding item. You can not trade equipped items."),
- ChatMsgType::BY_SERVER);
- }
- return false;
- }
- return true;
-}
-
-bool TradeWindow::isInpupFocused() const
-{
- return mMoneyField != nullptr && mMoneyField->isFocused();
-}
diff --git a/src/gui/windows/tradewindow.h b/src/gui/windows/tradewindow.h
deleted file mode 100644
index 6cfc89a3f..000000000
--- a/src/gui/windows/tradewindow.h
+++ /dev/null
@@ -1,214 +0,0 @@
-/*
- * The ManaPlus Client
- * Copyright (C) 2004-2009 The Mana World Development Team
- * Copyright (C) 2009-2010 The Mana Developers
- * Copyright (C) 2011-2017 The ManaPlus Developers
- *
- * This file is part of The ManaPlus Client.
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-#ifndef GUI_WINDOWS_TRADEWINDOW_H
-#define GUI_WINDOWS_TRADEWINDOW_H
-
-#include "gui/widgets/window.h"
-
-#include "enums/resources/item/itemtype.h"
-
-#include "enums/simpletypes/damaged.h"
-#include "enums/simpletypes/equipm.h"
-#include "enums/simpletypes/favorite.h"
-#include "enums/simpletypes/identified.h"
-#include "enums/simpletypes/itemcolor.h"
-
-#include "listeners/actionlistener.h"
-#include "listeners/selectionlistener.h"
-
-class Button;
-class Inventory;
-class Item;
-class ItemContainer;
-class Label;
-class TextField;
-
-struct ItemOptionsList;
-
-/**
- * Trade dialog.
- *
- * \ingroup Interface
- */
-class TradeWindow final : public Window,
- private ActionListener,
- private SelectionListener
-{
- public:
- /**
- * Constructor.
- */
- TradeWindow();
-
- A_DELETE_COPY(TradeWindow)
-
- /**
- * Destructor.
- */
- ~TradeWindow();
-
- /**
- * Displays expected money in the trade window.
- */
- void setMoney(const int quantity);
-
- /**
- * Add an item to the trade window.
- */
- void addItem(const int id,
- const ItemTypeT type,
- const bool own,
- const int quantity,
- const uint8_t refine,
- const ItemColor color,
- const Identified identified,
- const Damaged damaged,
- const Favorite favorite) const;
-
- /**
- * Reset both item containers
- */
- void reset();
-
- /**
- * Add an item to the trade window.
- */
- void addItem2(const int id,
- const ItemTypeT type,
- const int *const cards,
- const ItemOptionsList *const options,
- const int sz,
- const bool own,
- const int quantity,
- const uint8_t refine,
- const ItemColor color,
- const Identified identified,
- const Damaged damaged,
- const Favorite favorite,
- const Equipm equipment) const;
-
- /**
- * Change quantity of an item.
- */
- void changeQuantity(const int index, const bool own,
- const int quantity) const;
-
- /**
- * Increase quantity of an item.
- */
- void increaseQuantity(const int index, const bool own,
- const int quantity) const;
-
- /**
- * Player received ok message from server
- */
- void receivedOk(const bool own);
-
- /**
- * Send trade packet.
- */
- void tradeItem(const Item *const item,
- const int quantity,
- const bool check = false) const;
-
- /**
- * Updates the labels and makes sure only one item is selected in
- * either my inventory or partner inventory.
- */
- void valueChanged(const SelectionEvent &event) override final;
-
- /**
- * Called when receiving actions from the widgets.
- */
- void action(const ActionEvent &event) override final;
-
- /**
- * Closes the Trade Window, as well as telling the server that the
- * window has been closed.
- */
- void close() override final;
-
- /**
- * Clear auto trade items.
- */
- void clear() override final;
-
- /**
- * Add item what will be added to trade.
- */
- void addAutoItem(const std::string &nick, Item *const item,
- const int amount);
-
- void addAutoMoney(const std::string &nick, const int money);
-
- void initTrade(const std::string &nick);
-
- std::string getAutoTradeNick() const noexcept2 A_WARN_UNUSED
- { return mAutoAddToNick; }
-
- bool checkItem(const Item *const item) const A_WARN_UNUSED;
-
- bool isInpupFocused() const A_WARN_UNUSED;
-
- void completeTrade();
-
- private:
- enum Status
- {
- PREPARING = 0, /**< Players are adding items. (1) */
- PROPOSING, /**< Local player has confirmed the trade. (1) */
- ACCEPTING, /**< Accepting the trade. (2) */
- ACCEPTED /**< Local player has accepted the trade. */
- };
-
- /**
- * Sets the current status of the trade.
- */
- void setStatus(const Status s);
-
- Inventory *mMyInventory A_NONNULLPOINTER;
- Inventory *mPartnerInventory A_NONNULLPOINTER;
-
- ItemContainer *mMyItemContainer A_NONNULLPOINTER;
- ItemContainer *mPartnerItemContainer A_NONNULLPOINTER;
-
- Label *mMoneyLabel A_NONNULLPOINTER;
- Button *mAddButton A_NONNULLPOINTER;
- Button *mOkButton A_NONNULLPOINTER;
- Button *mMoneyChangeButton A_NONNULLPOINTER;
- TextField *mMoneyField A_NONNULLPOINTER;
-
- Item* mAutoAddItem;
- std::string mAutoAddToNick;
- int mGotMoney;
- int mGotMaxMoney;
- int mAutoMoney;
- int mAutoAddAmount;
- Status mStatus;
- bool mOkOther;
- bool mOkMe;
-};
-
-extern TradeWindow *tradeWindow;
-
-#endif // GUI_WINDOWS_TRADEWINDOW_H
diff --git a/src/gui/windows/updaterwindow.cpp b/src/gui/windows/updaterwindow.cpp
deleted file mode 100644
index 3858b0a5e..000000000
--- a/src/gui/windows/updaterwindow.cpp
+++ /dev/null
@@ -1,1217 +0,0 @@
-/*
- * The ManaPlus Client
- * Copyright (C) 2004-2009 The Mana World Development Team
- * Copyright (C) 2009-2010 The Mana Developers
- * Copyright (C) 2011-2017 The ManaPlus Developers
- *
- * This file is part of The ManaPlus Client.
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-#include "gui/windows/updaterwindow.h"
-
-#include "client.h"
-#include "configuration.h"
-#include "main.h"
-#include "settings.h"
-
-#include "enums/gui/layouttype.h"
-
-#include "fs/files.h"
-#include "fs/mkdir.h"
-#include "fs/paths.h"
-
-#include "fs/virtfs/fs.h"
-
-#include "gui/widgets/button.h"
-#include "gui/widgets/containerplacer.h"
-#include "gui/widgets/itemlinkhandler.h"
-#include "gui/widgets/label.h"
-#include "gui/widgets/layout.h"
-#include "gui/widgets/progressbar.h"
-#include "gui/widgets/scrollarea.h"
-#include "gui/widgets/staticbrowserbox.h"
-
-#include "net/download.h"
-#include "net/updatetypeoperators.h"
-
-#include "resources/db/moddb.h"
-
-#include "utils/delete2.h"
-#include "utils/foreach.h"
-#include "utils/gettext.h"
-
-#include <sys/stat.h>
-
-#include <sstream>
-
-#include "debug.h"
-
-UpdaterWindow *updaterWindow = nullptr;
-
-const std::string xmlUpdateFile("resources.xml");
-const std::string txtUpdateFile("resources2.txt");
-const std::string updateServer2
- ("http://download.manaplus.org/manaplus/updates/");
-const std::string updateServer3
- ("http://download2.manaplus.org/manaplus/updates/");
-const std::string updateServer4
- ("http://download.evolonline.org/manaplus/updates/");
-const std::string updateServer5
- ("http://download3.manaplus.org/manaplus/updates/");
-
-/**
- * Load the given file into a vector of updateFiles.
- */
-static STD_VECTOR<UpdateFile> loadXMLFile(const std::string &fileName,
- const bool loadMods)
-{
- STD_VECTOR<UpdateFile> files;
- XML::Document doc(fileName, UseVirtFs_false, SkipError_false);
- XmlNodeConstPtrConst rootNode = doc.rootNode();
-
- if ((rootNode == nullptr) || !xmlNameEqual(rootNode, "updates"))
- {
- logger->log("Error loading update file: %s", fileName.c_str());
- return files;
- }
-
- for_each_xml_child_node(fileNode, rootNode)
- {
- const bool isMod = xmlNameEqual(fileNode, "mod");
- if (!xmlNameEqual(fileNode, "update") && !isMod)
- continue;
-
- UpdateFile file;
- file.name = XML::getProperty(fileNode, "file", "");
- file.hash = XML::getProperty(fileNode, "hash", "");
- file.type = XML::getProperty(fileNode, "type", "data");
- file.desc = XML::getProperty(fileNode, "description", "");
- file.group = XML::getProperty(fileNode, "group", "");
- if (!file.group.empty() && (!isMod || !loadMods))
- continue;
-
- const std::string version = XML::getProperty(
- fileNode, "version", "");
- if (!version.empty())
- {
- if (version > CHECK_VERSION)
- continue;
- }
- const std::string notVersion = XML::getProperty(
- fileNode, "notVersion", "");
- if (!notVersion.empty())
- {
- if (notVersion <= CHECK_VERSION)
- continue;
- }
- if (XML::getProperty(fileNode, "required", "yes") == "yes")
- file.required = true;
- else
- file.required = false;
-
- if (checkPath(file.name))
- files.push_back(file);
- }
-
- return files;
-}
-
-static STD_VECTOR<UpdateFile> loadTxtFile(const std::string &fileName)
-{
- STD_VECTOR<UpdateFile> files;
- std::ifstream fileHandler;
- fileHandler.open(fileName.c_str(), std::ios::in);
-
- if (fileHandler.is_open())
- {
- while (fileHandler.good())
- {
- char name[256];
- char hash[50];
- fileHandler.getline(name, 256, ' ');
- fileHandler.getline(hash, 50);
-
- UpdateFile thisFile;
- thisFile.name = name;
- thisFile.hash = hash;
- thisFile.type = "data";
- thisFile.group.clear();
- thisFile.required = true;
- thisFile.desc.clear();
-
- if (!thisFile.name.empty() && checkPath(thisFile.name))
- files.push_back(thisFile);
- }
- }
- else
- {
- logger->log("Error loading update file: %s", fileName.c_str());
- }
- fileHandler.close();
-
- return files;
-}
-
-UpdaterWindow::UpdaterWindow(const std::string &restrict updateHost,
- const std::string &restrict updatesDir,
- const bool applyUpdates,
- const UpdateTypeT updateType) :
- // TRANSLATORS: updater window name
- Window(_("Updating..."), Modal_false, nullptr, "update.xml"),
- ActionListener(),
- KeyListener(),
- mDownloadProgress(0.0F),
- mUpdateHost(updateHost),
- mUpdatesDir(updatesDir),
- mUpdatesDirReal(updatesDir),
- mCurrentFile("news.txt"),
- mNewLabelCaption(),
- mDownloadMutex(),
- mCurrentChecksum(0),
- mMemoryBuffer(nullptr),
- mDownload(nullptr),
- mUpdateFiles(),
- mTempUpdateFiles(),
- mUpdateServerPath(mUpdateHost),
- mItemLinkHandler(new ItemLinkHandler),
- // TRANSLATORS: updater window label
- mLabel(new Label(this, _("Connecting..."))),
- // TRANSLATORS: updater window button
- mCancelButton(new Button(this, _("Cancel"), "cancel", this)),
- // TRANSLATORS: updater window button
- mPlayButton(new Button(this, _("Play"), "play", this)),
- mProgressBar(new ProgressBar(this, 0.0, 310, 0,
- ProgressColorId::PROG_UPDATE,
- "updateprogressbar.xml", "updateprogressbar_fill.xml")),
- mBrowserBox(new StaticBrowserBox(this, Opaque_true,
- "browserbox.xml")),
- mScrollArea(new ScrollArea(this, mBrowserBox,
- Opaque_true, "update_background.xml")),
- mDownloadStatus(UpdateDownloadStatus::UPDATE_NEWS),
- mDownloadedBytes(0),
- mUpdateIndex(0),
- mUpdateIndexOffset(0),
- mUpdateType(updateType),
- mStoreInMemory(true),
- mDownloadComplete(true),
- mUserCancel(false),
- mLoadUpdates(applyUpdates),
- mValidateXml(false),
- mSkipPatches(false)
-{
- setWindowName("UpdaterWindow");
- setResizable(true);
- setDefaultSize(450, 400, ImagePosition::CENTER);
- setMinWidth(310);
- setMinHeight(220);
-
- mProgressBar->setSmoothProgress(false);
- mBrowserBox->setOpaque(Opaque_false);
- mBrowserBox->setLinkHandler(mItemLinkHandler);
- mBrowserBox->setProcessVars(true);
- mBrowserBox->setEnableKeys(true);
- mBrowserBox->setEnableTabs(true);
- mPlayButton->setEnabled(false);
-
- ContainerPlacer placer;
- placer = getPlacer(0, 0);
-
- placer(0, 0, mScrollArea, 5, 3).setPadding(3);
- placer(0, 3, mLabel, 5);
- placer(0, 4, mProgressBar, 5);
- placer(3, 5, mCancelButton);
- placer(4, 5, mPlayButton);
-
- Layout &layout = getLayout();
- layout.setRowHeight(0, LayoutType::SET);
-
- addKeyListener(this);
-
- if (mUpdateHost.empty())
- {
- const STD_VECTOR<std::string> &mirrors = settings.updateMirrors;
- if (mirrors.begin() != mirrors.end())
- mUpdateHost = *mirrors.begin();
- mSkipPatches = true;
- }
-
- loadWindowState();
-}
-
-void UpdaterWindow::postInit()
-{
- Window::postInit();
- setVisible(Visible_true);
- mCancelButton->requestFocus();
- removeProtocol(mUpdateServerPath);
-
- download();
-}
-
-UpdaterWindow::~UpdaterWindow()
-{
- if (mLoadUpdates)
- loadUpdates();
-
- if (mDownload != nullptr)
- {
- mDownload->cancel();
-
- delete2(mDownload)
- }
- free(mMemoryBuffer);
- delete2(mItemLinkHandler);
-}
-
-void UpdaterWindow::setProgress(const float p)
-{
- // Do delayed progress bar update, since Guichan isn't thread-safe
- MutexLocker lock(&mDownloadMutex);
- mDownloadProgress = p;
-}
-
-void UpdaterWindow::setLabel(const std::string &str)
-{
- // Do delayed label text update, since Guichan isn't thread-safe
- MutexLocker lock(&mDownloadMutex);
- mNewLabelCaption = str;
-}
-
-void UpdaterWindow::enable()
-{
- mCancelButton->setEnabled(false);
- mPlayButton->setEnabled(true);
- mPlayButton->requestFocus();
-
- if (client->getState() != State::GAME)
- {
- if ((mUpdateType & UpdateType::Close) != 0)
- client->setState(State::LOAD_DATA);
- }
- else
- {
- deleteSelf();
- }
-}
-
-void UpdaterWindow::action(const ActionEvent &event)
-{
- const std::string &eventId = event.getId();
- if (eventId == "cancel")
- {
- // Register the user cancel
- mUserCancel = true;
- // Skip the updating process
- if (mDownloadStatus != UpdateDownloadStatus::UPDATE_COMPLETE)
- {
- if (mDownload != nullptr)
- mDownload->cancel();
- mDownloadStatus = UpdateDownloadStatus::UPDATE_ERROR;
- }
- }
- else if (eventId == "play")
- {
- if (client->getState() != State::GAME)
- client->setState(State::LOAD_DATA);
- else
- deleteSelf();
- }
-}
-
-void UpdaterWindow::keyPressed(KeyEvent &event)
-{
- const InputActionT actionId = event.getActionId();
- if (actionId == InputAction::GUI_CANCEL)
- {
- action(ActionEvent(nullptr, mCancelButton->getActionEventId()));
- if (client->getState() != State::GAME)
- client->setState(State::LOGIN);
- else
- deleteSelf();
- }
- else if (actionId == InputAction::GUI_SELECT ||
- actionId == InputAction::GUI_SELECT2)
- {
- if (mDownloadStatus == UpdateDownloadStatus::UPDATE_COMPLETE ||
- mDownloadStatus == UpdateDownloadStatus::UPDATE_ERROR ||
- mDownloadStatus == UpdateDownloadStatus::UPDATE_IDLE)
- {
- action(ActionEvent(nullptr, mPlayButton->getActionEventId()));
- }
- else
- {
- action(ActionEvent(nullptr, mCancelButton->getActionEventId()));
- }
- }
-}
-
-void UpdaterWindow::loadNews()
-{
- if (mMemoryBuffer == nullptr)
- {
- logger->log1("Couldn't load news");
- return;
- }
-
- // Reallocate and include terminating 0 character
- mMemoryBuffer = static_cast<char*>(realloc(
- mMemoryBuffer, mDownloadedBytes + 1));
- if (mMemoryBuffer == nullptr)
- {
- logger->log1("Couldn't load news");
- return;
- }
- mMemoryBuffer[mDownloadedBytes] = '\0';
- mBrowserBox->clearRows();
-
- std::string newsName = mUpdatesDir + "/local/help/news.txt";
- mkdir_r((mUpdatesDir + "/local/help/").c_str());
- bool firstLine(true);
- std::ofstream file;
- std::stringstream ss(mMemoryBuffer);
- std::string line;
- file.open(newsName.c_str(), std::ios::out);
- int cnt = 0;
- const int maxNews = 50;
- while (std::getline(ss, line, '\n'))
- {
- cnt ++;
- if (firstLine)
- {
- firstLine = false;
- const size_t i = line.find("##9 Latest client version: ##6");
- if (i == 0u)
- continue;
-
- if (file.is_open())
- file << line << std::endl;
- if (cnt < maxNews)
- mBrowserBox->addRow(line);
- }
- else
- {
- if (file.is_open())
- file << line << std::endl;
- if (cnt < maxNews)
- mBrowserBox->addRow(line);
- }
- }
-
- file.close();
- if (cnt > maxNews)
- {
- mBrowserBox->addRow("");
- // TRANSLATORS: updater window checkbox
- mBrowserBox->addRow("news", _("Show all news (can be slow)"));
- mBrowserBox->addRow("");
- }
- // Free the memory buffer now that we don't need it anymore
- free(mMemoryBuffer);
- mMemoryBuffer = nullptr;
- mDownloadedBytes = 0;
-
- mBrowserBox->updateHeight();
- mScrollArea->setVerticalScrollAmount(0);
-}
-
-void UpdaterWindow::loadPatch()
-{
- if (mMemoryBuffer == nullptr)
- {
- logger->log1("Couldn't load patch");
- return;
- }
-
- // Reallocate and include terminating 0 character
- mMemoryBuffer = static_cast<char*>(
- realloc(mMemoryBuffer, mDownloadedBytes + 1));
- if (mMemoryBuffer == nullptr)
- {
- logger->log1("Couldn't load patch");
- return;
- }
- mMemoryBuffer[mDownloadedBytes] = '\0';
-
- std::string version;
-
- // Tokenize and add each line separately
- char *line = strtok(mMemoryBuffer, "\n");
- if (line != nullptr)
- {
- version = line;
- if (serverVersion < 1)
- {
- line = strtok(nullptr, "\n");
- if (line != nullptr)
- {
- mBrowserBox->addRow(strprintf("##9 Latest client version: "
- "##6ManaPlus %s##0", line), true);
- }
- }
- if (version > CHECK_VERSION)
- {
- mBrowserBox->addRow("", true);
-#if defined(ANDROID)
- const std::string url = "androidDownloadUrl";
- const std::string text = "androidDownloadUrl";
-#elif defined(WIN32)
- const std::string url = "windowsDownloadUrl";
- const std::string text = "windowsDownloadUrl";
-#else // defined(ANDROID)
-
- const std::string url = "otherDownloadUrl";
- const std::string text = "otherDownloadUrl";
-#endif // defined(ANDROID)
-
- mBrowserBox->addRow(std::string(" ##1[@@").append(
- branding.getStringValue(url)).append("|").append(
- branding.getStringValue(text)).append("@@]"), true);
- mBrowserBox->addRow("##1You can download it from", true);
- mBrowserBox->addRow("##1ManaPlus updated.", true);
- }
- else
- {
- mBrowserBox->addRow("You have latest client version.", true);
- }
- }
-
- // Free the memory buffer now that we don't need it anymore
- free(mMemoryBuffer);
- mMemoryBuffer = nullptr;
- mDownloadedBytes = 0;
-
- mBrowserBox->updateHeight();
- mScrollArea->setVerticalScrollAmount(0);
-}
-
-int UpdaterWindow::updateProgress(void *ptr,
- const DownloadStatusT status,
- size_t dt,
- const size_t dn)
-{
- UpdaterWindow *const uw = reinterpret_cast<UpdaterWindow *>(ptr);
- if (uw == nullptr)
- return -1;
-
- if (status == DownloadStatus::Complete)
- {
- uw->mDownloadComplete = true;
- }
- else if (status == DownloadStatus::Error ||
- status == DownloadStatus::Cancelled)
- {
- if (uw->mDownloadStatus == UpdateDownloadStatus::UPDATE_COMPLETE ||
- uw->mDownloadStatus == UpdateDownloadStatus::UPDATE_NEWS)
- { // ignoring error in last state (was UPDATE_PATCH)
- uw->mDownloadStatus = UpdateDownloadStatus::UPDATE_COMPLETE;
- uw->mDownloadComplete = true;
- free(uw->mMemoryBuffer);
- uw->mMemoryBuffer = nullptr;
- }
- else
- {
- uw->mDownloadStatus = UpdateDownloadStatus::UPDATE_ERROR;
- }
- }
-
- if (dt == 0u)
- dt = 1;
-
- float progress = static_cast<float>(dn) /
- static_cast<float>(dt);
-
- if (progress != progress)
- progress = 0.0F; // check for NaN
- if (progress < 0.0F)
- progress = 0.0F; // no idea how this could ever happen,
- // but why not check for it anyway.
- if (progress > 1.0F)
- progress = 1.0F;
-
- uw->setLabel(std::string(uw->mCurrentFile).append(" (")
- .append(toString(CAST_S32(progress * 100))).append("%)"));
-
- uw->setProgress(progress);
-
- if ((client->getState() != State::UPDATE &&
- client->getState() != State::GAME) ||
- uw->mDownloadStatus == UpdateDownloadStatus::UPDATE_ERROR)
- {
- // If the action was canceled return an error code to stop the mThread
- return -1;
- }
-
- return 0;
-}
-
-size_t UpdaterWindow::memoryWrite(void *ptr, size_t size,
- size_t nmemb, void *stream)
-{
- UpdaterWindow *const uw = reinterpret_cast<UpdaterWindow *>(stream);
- const size_t totalMem = size * nmemb;
- if (uw == nullptr)
- return 0;
- uw->mMemoryBuffer = static_cast<char*>(realloc(uw->mMemoryBuffer,
- CAST_SIZE(uw->mDownloadedBytes) + totalMem));
- if (uw->mMemoryBuffer != nullptr)
- {
- memcpy(&(uw->mMemoryBuffer[uw->mDownloadedBytes]), ptr, totalMem);
- uw->mDownloadedBytes += CAST_S32(totalMem);
- }
-
- return totalMem;
-}
-
-void UpdaterWindow::download()
-{
- if (mDownload != nullptr)
- {
- mDownload->cancel();
- delete mDownload;
- }
- if (mDownloadStatus == UpdateDownloadStatus::UPDATE_PATCH)
- {
- mDownload = new Net::Download(this,
- branding.getStringValue("updateMirror1") + mCurrentFile,
- &updateProgress,
- true, false, mValidateXml);
- for (int f = 2; f < 8; f ++)
- {
- const std::string url = branding.getStringValue(
- "updateMirror" + toString(f));
- if (!url.empty())
- mDownload->addMirror(url + mCurrentFile);
- }
- }
- else
- {
- mDownload = new Net::Download(this,
- urlJoin(mUpdateHost, mCurrentFile),
- &updateProgress,
- false, false, mValidateXml);
-
- if (mDownloadStatus == UpdateDownloadStatus::UPDATE_LIST2 ||
- mDownloadStatus == UpdateDownloadStatus::UPDATE_RESOURCES2)
- {
- const std::string str = urlJoin(mUpdateServerPath, mCurrentFile);
- mDownload->addMirror(updateServer3 + str);
- mDownload->addMirror(updateServer4 + str);
- mDownload->addMirror(updateServer5 + str);
- }
- else
- {
- const STD_VECTOR<std::string> &mirrors = settings.updateMirrors;
- FOR_EACH (STD_VECTOR<std::string>::const_iterator, it, mirrors)
- {
- mDownload->addMirror(pathJoin(*it,
- mCurrentFile));
- }
- }
- }
-
- if (mStoreInMemory)
- {
- mDownload->setWriteFunction(&UpdaterWindow::memoryWrite);
- }
- else
- {
- if (mDownloadStatus == UpdateDownloadStatus::UPDATE_RESOURCES)
- {
- mDownload->setFile(pathJoin(mUpdatesDir, mCurrentFile),
- mCurrentChecksum);
- }
- else
- {
- mDownload->setFile(pathJoin(mUpdatesDir,
- mCurrentFile));
- }
- }
-
- if (mDownloadStatus != UpdateDownloadStatus::UPDATE_RESOURCES)
- mDownload->noCache();
-
- setLabel(mCurrentFile + " (0%)");
- mDownloadComplete = false;
-
- mDownload->start();
-}
-
-void UpdaterWindow::loadUpdates()
-{
- if (mUpdateFiles.empty())
- { // updates not downloaded
- mUpdateFiles = loadXMLFile(pathJoin(mUpdatesDir, xmlUpdateFile),
- false);
- if (mUpdateFiles.empty())
- {
- logger->log("Warning this server does not have a"
- " %s file falling back to %s", xmlUpdateFile.c_str(),
- txtUpdateFile.c_str());
- mUpdateFiles = loadTxtFile(pathJoin(mUpdatesDir,
- txtUpdateFile));
- }
- }
-
- std::string fixPath = mUpdatesDir + "/fix";
- const unsigned sz = CAST_U32(mUpdateFiles.size());
- for (mUpdateIndex = 0; mUpdateIndex < sz; mUpdateIndex++)
- {
- const UpdateFile &file = mUpdateFiles[mUpdateIndex];
- if (!file.group.empty())
- continue;
- UpdaterWindow::addUpdateFile(mUpdatesDir,
- fixPath,
- file.name,
- Append_false);
- }
- loadManaPlusUpdates(mUpdatesDir);
- loadMods(mUpdatesDir, mUpdateFiles);
-}
-
-void UpdaterWindow::loadLocalUpdates(const std::string &dir)
-{
- STD_VECTOR<UpdateFile> updateFiles = loadXMLFile(
- pathJoin(dir, xmlUpdateFile),
- false);
-
- if (updateFiles.empty())
- {
- logger->log("Warning this server does not have a"
- " %s file falling back to %s", xmlUpdateFile.c_str(),
- txtUpdateFile.c_str());
- updateFiles = loadTxtFile(pathJoin(dir,
- txtUpdateFile));
- }
-
- const std::string fixPath = dir + "/fix";
- for (unsigned int updateIndex = 0,
- fsz = CAST_U32(updateFiles.size());
- updateIndex < fsz;
- updateIndex++)
- {
- const UpdateFile &file = updateFiles[updateIndex];
- if (!file.group.empty())
- continue;
- UpdaterWindow::addUpdateFile(dir,
- fixPath,
- file.name,
- Append_false);
- }
- loadManaPlusUpdates(dir);
- loadMods(dir, updateFiles);
-}
-
-void UpdaterWindow::unloadUpdates(const std::string &dir)
-{
- STD_VECTOR<UpdateFile> updateFiles = loadXMLFile(
- pathJoin(dir, xmlUpdateFile),
- true);
-
- if (updateFiles.empty())
- {
- updateFiles = loadTxtFile(pathJoin(dir,
- txtUpdateFile));
- }
-
- const std::string fixPath = dir + "/fix";
- for (unsigned int updateIndex = 0,
- fsz = CAST_U32(updateFiles.size());
- updateIndex < fsz;
- updateIndex++)
- {
- UpdaterWindow::removeUpdateFile(dir,
- fixPath,
- updateFiles[updateIndex].name);
- }
- unloadManaPlusUpdates(dir);
-}
-
-void UpdaterWindow::loadManaPlusUpdates(const std::string &dir)
-{
- std::string fixPath = dir + "/fix";
- STD_VECTOR<UpdateFile> updateFiles = loadXMLFile(
- pathJoin(fixPath, xmlUpdateFile),
- false);
-
- for (unsigned int updateIndex = 0,
- fsz = CAST_U32(updateFiles.size());
- updateIndex < fsz;
- updateIndex++)
- {
- const UpdateFile &file = updateFiles[updateIndex];
- if (!file.group.empty())
- continue;
- const std::string name = file.name;
- if (strStartWith(name, "manaplus_"))
- {
- struct stat statbuf;
- std::string fileName = pathJoin(fixPath,
- name);
- if (stat(fileName.c_str(), &statbuf) == 0)
- {
- VirtFs::mountZip(fileName,
- Append_false);
- }
- }
- }
-}
-
-void UpdaterWindow::unloadManaPlusUpdates(const std::string &dir)
-{
- const std::string fixPath = dir + "/fix";
- const STD_VECTOR<UpdateFile> updateFiles = loadXMLFile(
- pathJoin(fixPath, xmlUpdateFile),
- true);
-
- for (unsigned int updateIndex = 0,
- fsz = CAST_U32(updateFiles.size());
- updateIndex < fsz;
- updateIndex++)
- {
- std::string name = updateFiles[updateIndex].name;
- if (strStartWith(name, "manaplus_"))
- {
- struct stat statbuf;
- const std::string file = pathJoin(
- fixPath, name);
- if (stat(file.c_str(), &statbuf) == 0)
- VirtFs::unmountZip(file);
- }
- }
-}
-
-void UpdaterWindow::addUpdateFile(const std::string &restrict path,
- const std::string &restrict fixPath,
- const std::string &restrict file,
- const Append append)
-{
- const std::string tmpPath = pathJoin(path, file);
- if (append == Append_false)
- VirtFs::mountZip(tmpPath, append);
-
- const std::string fixFile = pathJoin(fixPath, file);
- struct stat statbuf;
- if (stat(fixFile.c_str(), &statbuf) == 0)
- VirtFs::mountZip(fixFile, append);
-
- if (append == Append_true)
- VirtFs::mountZip(tmpPath, append);
-}
-
-void UpdaterWindow::removeUpdateFile(const std::string &restrict path,
- const std::string &restrict fixPath,
- const std::string &restrict file)
-{
- VirtFs::unmountZip(pathJoin(path, file));
- const std::string fixFile = pathJoin(fixPath, file);
- struct stat statbuf;
- if (stat(fixFile.c_str(), &statbuf) == 0)
- VirtFs::unmountZip(fixFile);
-}
-
-void UpdaterWindow::logic()
-{
- BLOCK_START("UpdaterWindow::logic")
- // Update Scroll logic
- mScrollArea->logic();
-
- // Synchronize label caption when necessary
- {
- MutexLocker lock(&mDownloadMutex);
-
- if (mLabel->getCaption() != mNewLabelCaption)
- {
- mLabel->setCaption(mNewLabelCaption);
- mLabel->adjustSize();
- }
-
- mProgressBar->setProgress(mDownloadProgress);
- if (!mUpdateFiles.empty() &&
- CAST_SIZE(mUpdateIndex) <= mUpdateFiles.size())
- {
- mProgressBar->setText(strprintf("%u/%u", mUpdateIndex
- + mUpdateIndexOffset + 1, CAST_U32(
- mUpdateFiles.size()) + CAST_S32(
- mTempUpdateFiles.size()) + 1));
- }
- else
- {
- mProgressBar->setText("");
- }
- }
-
- switch (mDownloadStatus)
- {
- case UpdateDownloadStatus::UPDATE_ERROR:
- mBrowserBox->addRow("");
- // TRANSLATORS: update message
- mBrowserBox->addRow(_("##1 The update process is incomplete."));
- // TRANSLATORS: Continues "The update process is incomplete.".
- mBrowserBox->addRow(_("##1 It is strongly recommended that"));
- // TRANSLATORS: Begins "It is strongly recommended that".
- mBrowserBox->addRow(_("##1 you try again later."));
- if (mDownload != nullptr)
- mBrowserBox->addRow(mDownload->getError());
- mBrowserBox->updateHeight();
- mScrollArea->setVerticalScrollAmount(
- mScrollArea->getVerticalMaxScroll());
- mDownloadStatus = UpdateDownloadStatus::UPDATE_COMPLETE;
- break;
- case UpdateDownloadStatus::UPDATE_NEWS:
- if (mDownloadComplete)
- {
- // Parse current memory buffer as news and dispose of the data
- loadNews();
-
- mValidateXml = true;
- mCurrentFile = xmlUpdateFile;
- mStoreInMemory = false;
- mDownloadStatus = UpdateDownloadStatus::UPDATE_LIST;
- download(); // download() changes mDownloadComplete to false
- }
- break;
- case UpdateDownloadStatus::UPDATE_PATCH:
- if (mDownloadComplete)
- {
- // Parse current memory buffer as news and dispose of the data
- loadPatch();
-
- mUpdateHost = updateServer2 + mUpdateServerPath;
- mUpdatesDir = pathJoin(mUpdatesDir, "fix");
- mCurrentFile = xmlUpdateFile;
- mValidateXml = true;
- mStoreInMemory = false;
- mDownloadStatus = UpdateDownloadStatus::UPDATE_LIST2;
- download();
- }
- break;
-
- case UpdateDownloadStatus::UPDATE_LIST:
- if (mDownloadComplete)
- {
- if (mCurrentFile == xmlUpdateFile)
- {
- mUpdateFiles = loadXMLFile(pathJoin(
- mUpdatesDir, xmlUpdateFile),
- true);
-
- if (mUpdateFiles.empty())
- {
- logger->log("Warning this server does not have a %s"
- " file falling back to %s",
- xmlUpdateFile.c_str(),
- txtUpdateFile.c_str());
-
- // If the resources.xml file fails,
- // fall back onto a older version
- mCurrentFile = txtUpdateFile;
- mValidateXml = false;
- mStoreInMemory = false;
- mDownloadStatus = UpdateDownloadStatus::UPDATE_LIST;
- download();
- break;
- }
- }
- else if (mCurrentFile == txtUpdateFile)
- {
- mValidateXml = true;
- mUpdateFiles = loadTxtFile(pathJoin(mUpdatesDir,
- txtUpdateFile));
- }
- mStoreInMemory = false;
- mDownloadStatus = UpdateDownloadStatus::UPDATE_RESOURCES;
- }
- break;
- case UpdateDownloadStatus::UPDATE_RESOURCES:
- if (mDownloadComplete)
- {
- if (CAST_SIZE(mUpdateIndex) < mUpdateFiles.size())
- {
- UpdateFile thisFile = mUpdateFiles[mUpdateIndex];
- if (thisFile.type == "music"
- && !config.getBoolValue("download-music"))
- {
- mUpdateIndex++;
- break;
- }
- mCurrentFile = thisFile.name;
- std::string checksum;
- checksum = thisFile.hash;
- std::stringstream ss(checksum);
- ss >> std::hex >> mCurrentChecksum;
-
- std::ifstream temp(pathJoin(mUpdatesDir,
- mCurrentFile).c_str());
-
- mValidateXml = false;
- if (!temp.is_open() || !validateFile(pathJoin(
- mUpdatesDir, mCurrentFile),
- mCurrentChecksum))
- {
- temp.close();
- download();
- }
- else
- {
- temp.close();
- logger->log("%s already here", mCurrentFile.c_str());
- }
- mUpdateIndex++;
- }
- else
- {
- if (!mSkipPatches)
- {
- // Download of updates completed
- mCurrentFile = "latest.txt";
- mStoreInMemory = true;
- mDownloadStatus = UpdateDownloadStatus::UPDATE_PATCH;
- mValidateXml = false;
- download(); // download() changes
- // mDownloadComplete to false
- }
- else
- {
- mDownloadStatus =
- UpdateDownloadStatus::UPDATE_COMPLETE;
- }
- }
- }
- break;
- case UpdateDownloadStatus::UPDATE_LIST2:
- if (mDownloadComplete)
- {
- if (mCurrentFile == xmlUpdateFile)
- {
- mTempUpdateFiles = loadXMLFile(pathJoin(
- mUpdatesDir, xmlUpdateFile),
- true);
- }
- mUpdateIndexOffset = mUpdateIndex;
- mUpdateIndex = 0;
- mValidateXml = true;
- mStoreInMemory = false;
- mDownloadStatus = UpdateDownloadStatus::UPDATE_RESOURCES2;
- download();
- }
- break;
- case UpdateDownloadStatus::UPDATE_RESOURCES2:
- if (mDownloadComplete)
- {
- mValidateXml = false;
- if (CAST_SIZE(mUpdateIndex)
- < mTempUpdateFiles.size())
- {
- const UpdateFile thisFile = mTempUpdateFiles[mUpdateIndex];
- mCurrentFile = thisFile.name;
- std::string checksum;
- checksum = thisFile.hash;
- std::stringstream ss(checksum);
- ss >> std::hex >> mCurrentChecksum;
-
- std::ifstream temp((pathJoin(mUpdatesDir,
- mCurrentFile)).c_str());
-
- if (!temp.is_open() || !validateFile(pathJoin(
- mUpdatesDir, mCurrentFile),
- mCurrentChecksum))
- {
- temp.close();
- download();
- }
- else
- {
- temp.close();
- logger->log("%s already here", mCurrentFile.c_str());
- }
- mUpdateIndex++;
- }
- else
- {
- mUpdatesDir = mUpdatesDirReal;
- mDownloadStatus = UpdateDownloadStatus::UPDATE_COMPLETE;
- }
- }
- break;
- case UpdateDownloadStatus::UPDATE_COMPLETE:
- mUpdatesDir = mUpdatesDirReal;
- enable();
- // TRANSLATORS: updater window label
- setLabel(_("Completed"));
- mDownloadStatus = UpdateDownloadStatus::UPDATE_IDLE;
- break;
- case UpdateDownloadStatus::UPDATE_IDLE:
- break;
- default:
- logger->log("UpdaterWindow::logic unknown status: "
- + toString(CAST_U32(mDownloadStatus)));
- break;
- }
- BLOCK_END("UpdaterWindow::logic")
-}
-
-bool UpdaterWindow::validateFile(const std::string &filePath,
- const unsigned long hash)
-{
- FILE *const file = fopen(filePath.c_str(), "rb");
- if (file == nullptr)
- return false;
-
- const unsigned long adler = Net::Download::fadler32(file);
- fclose(file);
- return adler == hash;
-}
-
-unsigned long UpdaterWindow::getFileHash(const std::string &filePath)
-{
- int size = 0;
- const char *const buf = VirtFs::loadFile(filePath, size);
- if (buf == nullptr)
- return 0;
- unsigned long res = Net::Download::adlerBuffer(buf, size);
- delete [] buf;
- return res;
-}
-
-void UpdaterWindow::loadFile(std::string file)
-{
- mBrowserBox->clearRows();
- trim(file);
-
- StringVect lines;
- Files::loadTextFileLocal(mUpdatesDir + "/local/help/news.txt", lines);
-
- for (size_t i = 0, sz = lines.size(); i < sz; ++i)
- mBrowserBox->addRow(lines[i]);
- mBrowserBox->updateHeight();
-}
-
-void UpdaterWindow::loadMods(const std::string &dir,
- const STD_VECTOR<UpdateFile> &updateFiles)
-{
- ModDB::load();
- std::string modsString = serverConfig.getValue("mods", "");
- std::set<std::string> modsList;
- splitToStringSet(modsList, modsString, '|');
-
- const std::string fixPath = dir + "/fix";
- for (unsigned int updateIndex = 0,
- fsz = CAST_U32(updateFiles.size());
- updateIndex < fsz;
- updateIndex ++)
- {
- const UpdateFile &file = updateFiles[updateIndex];
- if (file.group.empty())
- continue;
- const std::set<std::string>::const_iterator
- it = modsList.find(file.group);
- if (it != modsList.end())
- {
- UpdaterWindow::addUpdateFile(dir,
- fixPath,
- file.name,
- Append_false);
- }
- }
-
- STD_VECTOR<UpdateFile> updateFiles2 = loadXMLFile(
- pathJoin(fixPath, xmlUpdateFile),
- true);
-
- for (unsigned int updateIndex = 0,
- fsz = CAST_U32(updateFiles2.size());
- updateIndex < fsz;
- updateIndex++)
- {
- const UpdateFile &file = updateFiles2[updateIndex];
- if (file.group.empty())
- continue;
- std::string name = file.name;
- if (strStartWith(name, "manaplus_"))
- {
- const std::set<std::string>::const_iterator
- it = modsList.find(file.group);
- if (it != modsList.end())
- {
- struct stat statbuf;
- std::string fileName = pathJoin(fixPath,
- name);
- if (stat(fileName.c_str(), &statbuf) == 0)
- {
- VirtFs::mountZip(fileName,
- Append_false);
- }
- }
- }
- }
-
- loadDirMods(dir + "/local/");
-}
-
-void UpdaterWindow::loadDirMods(const std::string &dir)
-{
- ModDB::load();
- const ModInfos &mods = ModDB::getAll();
-
- std::string modsString = serverConfig.getValue("mods", "");
- StringVect modsList;
- splitToStringVector(modsList, modsString, '|');
- FOR_EACH (StringVectCIter, it, modsList)
- {
- const std::string &name = *it;
- const ModInfoCIterator modIt = mods.find(name);
- if (modIt == mods.end())
- continue;
- const ModInfo *const mod = (*modIt).second;
- if (mod != nullptr)
- {
- const std::string &localDir = mod->getLocalDir();
- if (!localDir.empty())
- {
- VirtFs::mountDir(pathJoin(dir, localDir),
- Append_false);
- }
- }
- }
-}
-
-void UpdaterWindow::unloadMods(const std::string &dir)
-{
- const ModInfos &mods = ModDB::getAll();
- std::string modsString = serverConfig.getValue("mods", "");
- StringVect modsList;
- splitToStringVector(modsList, modsString, '|');
- FOR_EACH (StringVectCIter, it, modsList)
- {
- const std::string &name = *it;
- const ModInfoCIterator modIt = mods.find(name);
- if (modIt == mods.end())
- continue;
- const ModInfo *const mod = (*modIt).second;
- if (mod != nullptr)
- {
- const std::string &localDir = mod->getLocalDir();
- if (!localDir.empty())
- VirtFs::unmountDir(pathJoin(dir, localDir));
- }
- }
-}
-
-void UpdaterWindow::deleteSelf()
-{
- scheduleDelete();
- updaterWindow = nullptr;
-}
diff --git a/src/gui/windows/updaterwindow.h b/src/gui/windows/updaterwindow.h
deleted file mode 100644
index 661168a9f..000000000
--- a/src/gui/windows/updaterwindow.h
+++ /dev/null
@@ -1,252 +0,0 @@
-/*
- * The ManaPlus Client
- * Copyright (C) 2004-2009 The Mana World Development Team
- * Copyright (C) 2009-2010 The Mana Developers
- * Copyright (C) 2011-2017 The ManaPlus Developers
- *
- * This file is part of The ManaPlus Client.
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-#ifndef GUI_WINDOWS_UPDATERWINDOW_H
-#define GUI_WINDOWS_UPDATERWINDOW_H
-
-#include "enums/gui/updatedownloadstatus.h"
-
-#include "enums/net/downloadstatus.h"
-#include "enums/net/updatetype.h"
-
-#include "enums/simpletypes/append.h"
-
-#include "gui/widgets/window.h"
-
-#include "resources/updatefile.h"
-
-#include "utils/mutex.h"
-
-#include "listeners/actionlistener.h"
-#include "listeners/keylistener.h"
-
-class Button;
-class ItemLinkHandler;
-class Label;
-class ProgressBar;
-class ScrollArea;
-class StaticBrowserBox;
-
-namespace Net
-{
- class Download;
-} // namespace Net
-
-/**
- * Update progress window GUI
- *
- * \ingroup GUI
- */
-class UpdaterWindow final : public Window,
- public ActionListener,
- public KeyListener
-{
- public:
- /**
- * Constructor.
- *
- * @param updateHost Host where to get the updated files.
- * @param updatesDir Directory where to store updates (should be
- * absolute and already created).
- * @param applyUpdates If true, the update window will pass the updates
- * to teh resource manager.
- */
- UpdaterWindow(const std::string &restrict updateHost,
- const std::string &restrict updatesDir,
- const bool applyUpdates,
- const UpdateTypeT updateType);
-
- A_DELETE_COPY(UpdaterWindow)
-
- /**
- * Destructor
- */
- ~UpdaterWindow();
-
- void postInit() override final;
-
- /**
- * Set's progress bar status
- */
- void setProgress(const float p);
-
- /**
- * Set's label above progress
- */
- void setLabel(const std::string &);
-
- /**
- * Enables play button
- */
- void enable();
-
- /**
- * Loads and display news. Assumes the news file contents have been
- * loaded into the memory buffer.
- */
- void loadNews();
-
- void loadPatch();
-
- void action(const ActionEvent &event) override final;
-
- void keyPressed(KeyEvent &event) override final;
-
- void logic() override final;
-
- void loadFile(std::string file);
-
- void deleteSelf();
-
- static void loadLocalUpdates(const std::string &dir);
-
- static void unloadUpdates(const std::string &dir);
-
- static void addUpdateFile(const std::string &restrict path,
- const std::string &restrict fixPath,
- const std::string &restrict file,
- const Append append);
-
- static void removeUpdateFile(const std::string &restrict path,
- const std::string &restrict fixPath,
- const std::string &filerestrict);
-
- static void loadManaPlusUpdates(const std::string &dir);
-
- static void unloadManaPlusUpdates(const std::string &dir);
-
- static unsigned long getFileHash(const std::string &filePath);
-
- static void loadMods(const std::string &dir,
- const STD_VECTOR<UpdateFile> &updateFiles);
-
- static void loadDirMods(const std::string &dir);
-
- static void unloadMods(const std::string &dir);
-
- private:
- void download();
-
- /**
- * Loads the updates this window has gotten into the resource manager
- */
- void loadUpdates();
-
- /**
- * A download callback for progress updates.
- */
- static int updateProgress(void *ptr,
- const DownloadStatusT status,
- size_t dt,
- const size_t dn);
-
- /**
- * A libcurl callback for writing to memory.
- */
- static size_t memoryWrite(void *ptr, size_t size, size_t nmemb,
- void *stream);
-
- static bool validateFile(const std::string &filePath,
- const unsigned long hash) A_WARN_UNUSED;
-
- /** The new progress value to be set in the logic method. */
- float mDownloadProgress;
-
- /** Host where we get the updated files. */
- std::string mUpdateHost;
-
- /** Place where the updates are stored (absolute path). */
- std::string mUpdatesDir;
-
- std::string mUpdatesDirReal;
-
- /** The file currently downloading. */
- std::string mCurrentFile;
-
- /** The new label caption to be set in the logic method. */
- std::string mNewLabelCaption;
-
- // The mutex used to guard access to mNewLabelCaption
- // and mDownloadProgress.
- Mutex mDownloadMutex;
-
- /** The Adler32 checksum of the file currently downloading. */
- unsigned long mCurrentChecksum;
-
- /** Buffer for files downloaded to memory. */
- char *mMemoryBuffer;
-
- /** Download handle. */
- Net::Download *mDownload;
-
- /** List of files to download. */
- STD_VECTOR<UpdateFile> mUpdateFiles;
-
- /** List of temp files to download. */
- STD_VECTOR<UpdateFile> mTempUpdateFiles;
-
- std::string mUpdateServerPath;
-
- ItemLinkHandler *mItemLinkHandler A_NONNULLPOINTER;
- Label *mLabel A_NONNULLPOINTER;
- Button *mCancelButton A_NONNULLPOINTER;
- Button *mPlayButton A_NONNULLPOINTER;
- ProgressBar *mProgressBar A_NONNULLPOINTER;
- StaticBrowserBox *mBrowserBox A_NONNULLPOINTER;
- ScrollArea *mScrollArea A_NONNULLPOINTER;
-
- /** Status of the current download. */
- UpdateDownloadStatusT mDownloadStatus;
-
- /** Byte count currently downloaded in mMemoryBuffer. */
- int mDownloadedBytes;
-
- /** Index of the file to be downloaded. */
- unsigned int mUpdateIndex;
-
- /** Index offset for disaplay downloaded file. */
- unsigned int mUpdateIndexOffset;
-
- UpdateTypeT mUpdateType;
-
- /** A flag to indicate whether to use a memory buffer or a regular
- * file.
- */
- bool mStoreInMemory;
-
- /** Flag that show if current download is complete. */
- bool mDownloadComplete;
-
- /** Flag that show if the user has canceled the update. */
- bool mUserCancel;
-
- /** Tells ~UpdaterWindow() if it should load updates */
- bool mLoadUpdates;
-
- bool mValidateXml;
-
- bool mSkipPatches;
-};
-
-extern UpdaterWindow *updaterWindow;
-
-#endif // GUI_WINDOWS_UPDATERWINDOW_H
diff --git a/src/gui/windows/whoisonline.cpp b/src/gui/windows/whoisonline.cpp
deleted file mode 100644
index e123d3941..000000000
--- a/src/gui/windows/whoisonline.cpp
+++ /dev/null
@@ -1,909 +0,0 @@
-/*
- * The ManaPlus Client
- * Copyright (C) 2009 The Mana World Development Team
- * Copyright (C) 2009-2010 Andrei Karas
- * Copyright (C) 2011-2017 The ManaPlus Developers
- *
- * This file is part of The ManaPlus Client.
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-#include "gui/windows/whoisonline.h"
-
-#include "actormanager.h"
-#include "configuration.h"
-#include "guild.h"
-#include "party.h"
-#ifdef TMWA_SUPPORT
-#include "settings.h"
-#endif // TMWA_SUPPORT
-
-#include "gui/onlineplayer.h"
-#include "gui/popupmanager.h"
-#include "gui/viewport.h"
-
-#include "gui/popups/popupmenu.h"
-
-#include "gui/windows/chatwindow.h"
-#include "gui/windows/setupwindow.h"
-#include "gui/windows/socialwindow.h"
-
-#include "gui/widgets/button.h"
-#include "gui/widgets/scrollarea.h"
-#include "gui/widgets/staticbrowserbox.h"
-
-#include "being/beingflag.h"
-#include "being/localplayer.h"
-#include "being/playerrelations.h"
-
-#ifdef TMWA_SUPPORT
-#include "net/download.h"
-#endif // TMWA_SUPPORT
-#include "net/packetlimiter.h"
-#include "net/playerhandler.h"
-#include "net/serverfeatures.h"
-
-#include "utils/foreach.h"
-#include "utils/gettext.h"
-#include "utils/sdlhelper.h"
-
-#ifdef TMWA_SUPPORT
-#include "net/net.h"
-#else // TMWA_SUPPORT
-#include <curl/curl.h>
-#endif // TMWA_SUPPORT
-
-#include "debug.h"
-
-#ifdef free
-#undef free
-#endif // free
-
-#ifdef malloc
-#undef malloc
-#endif // malloc
-
-WhoIsOnline *whoIsOnline = nullptr;
-
-namespace
-{
- class NameFunctuator final
- {
- public:
- A_DEFAULT_COPY(NameFunctuator)
-
- bool operator()(const OnlinePlayer *left,
- const OnlinePlayer *right) const
- {
- return (compareStrI(left->getNick(), right->getNick()) < 0);
- }
- } nameCompare;
-} // namespace
-
-WhoIsOnline::WhoIsOnline() :
- // TRANSLATORS: who is online window name
- Window(_("Who Is Online - Updating"),
- Modal_false,
- nullptr,
- "whoisonline.xml"),
- mUpdateTimer(0),
- mThread(nullptr),
- mMemoryBuffer(nullptr),
- mCurlError(new char[CURL_ERROR_SIZE]),
- mBrowserBox(new StaticBrowserBox(this, Opaque_true,
- "onlinebrowserbox.xml")),
- mScrollArea(new ScrollArea(this, mBrowserBox, Opaque_false)),
- // TRANSLATORS: who is online. button.
- mUpdateButton(new Button(this, _("Update"), "update", this)),
- mOnlinePlayers(),
- mOnlineNicks(),
- mFriends(),
- mNeutral(),
- mDisregard(),
- mEnemy(),
- mDownloadedBytes(0),
- mDownloadStatus(UPDATE_LIST),
- mDownloadComplete(true),
- mAllowUpdate(true),
- mShowLevel(false),
- mUpdateOnlineList(config.getBoolValue("updateOnlineList")),
- mGroupFriends(true),
-#ifdef TMWA_SUPPORT
- mWebList(Net::getNetworkType() == ServerType::TMWATHENA),
-#endif
- mServerSideList(serverFeatures->haveServerOnlineList())
-{
- mCurlError[0] = 0;
- setWindowName("WhoIsOnline");
-}
-
-void WhoIsOnline::postInit()
-{
- Window::postInit();
- const int h = 350;
- const int w = 200;
- setDefaultSize(w, h, ImagePosition::CENTER);
-
- setVisible(Visible_false);
- setCloseButton(true);
- setResizable(true);
- setStickyButtonLock(true);
- setSaveVisible(true);
-
- if (setupWindow != nullptr)
- setupWindow->registerWindowForReset(this);
-
- mUpdateButton->setEnabled(false);
- mUpdateButton->setDimension(Rect(5, 5, w - 10, 20 + 5));
-
- mBrowserBox->setOpaque(Opaque_false);
- mScrollArea->setDimension(Rect(5, 20 + 10, w - 10, h - 10 - 30));
- mScrollArea->setSize(w - 10, h - 10 - 30);
- mScrollArea->setSelectable(false);
- mBrowserBox->setLinkHandler(this);
-
- add(mUpdateButton);
- add(mScrollArea);
-
- setLocationRelativeTo(getParent());
-
- loadWindowState();
- enableVisibleSound(true);
-
- download();
-
- widgetResized(Event(nullptr));
- config.addListener("updateOnlineList", this);
- config.addListener("groupFriends", this);
- mGroupFriends = config.getBoolValue("groupFriends");
-}
-
-WhoIsOnline::~WhoIsOnline()
-{
- config.removeListeners(this);
- CHECKLISTENERS
-
- SDL::WaitThread(mThread);
- mThread = nullptr;
- free(mMemoryBuffer);
- mMemoryBuffer = nullptr;
-
- // Remove possibly leftover temporary download
- delete []mCurlError;
-
- FOR_EACH (std::set<OnlinePlayer*>::iterator, itd, mOnlinePlayers)
- delete *itd;
- mOnlinePlayers.clear();
- mOnlineNicks.clear();
-}
-
-void WhoIsOnline::handleLink(const std::string& link, MouseEvent *event)
-{
- if ((event == nullptr) || event->getButton() == MouseButton::LEFT)
- {
- if (chatWindow != nullptr)
- {
- const std::string text = decodeLinkText(link);
- if (config.getBoolValue("whispertab"))
- {
- chatWindow->localChatInput("/q " + text);
- }
- else
- {
- chatWindow->addInputText(std::string("/w \"").append(
- text).append("\" "));
- }
- }
- }
- else if (event->getButton() == MouseButton::RIGHT)
- {
- if ((localPlayer != nullptr) && link == localPlayer->getName())
- return;
-
- if (popupMenu != nullptr)
- {
- if (actorManager != nullptr)
- {
- const std::string text = decodeLinkText(link);
- Being *const being = actorManager->findBeingByName(
- text, ActorType::Player);
-
- if ((being != nullptr) && (popupManager != nullptr))
- {
- popupMenu->showPopup(viewport->mMouseX,
- viewport->mMouseY,
- being);
- return;
- }
- }
- popupMenu->showPlayerPopup(link);
- }
- }
-}
-
-void WhoIsOnline::updateWindow(size_t numOnline)
-{
- // Set window caption
- // TRANSLATORS: who is online window name
- setCaption(_("Who Is Online - ") + toString(CAST_U32(numOnline)));
-
- // List the online people
- std::sort(mFriends.begin(), mFriends.end(), nameCompare);
- std::sort(mNeutral.begin(), mNeutral.end(), nameCompare);
- std::sort(mDisregard.begin(), mDisregard.end(), nameCompare);
- bool addedFromSection(false);
- FOR_EACH (STD_VECTOR<OnlinePlayer*>::const_iterator, it, mFriends)
- {
- mBrowserBox->addRow((*it)->getText());
- addedFromSection = true;
- }
- if (addedFromSection == true)
- {
- mBrowserBox->addRow("---");
- addedFromSection = false;
- }
- FOR_EACH (STD_VECTOR<OnlinePlayer*>::const_iterator, it, mEnemy)
- {
- mBrowserBox->addRow((*it)->getText());
- addedFromSection = true;
- }
- if (addedFromSection == true)
- {
- mBrowserBox->addRow("---");
- addedFromSection = false;
- }
- FOR_EACH (STD_VECTOR<OnlinePlayer*>::const_iterator, it, mNeutral)
- {
- mBrowserBox->addRow((*it)->getText());
- addedFromSection = true;
- }
- if (addedFromSection == true && !mDisregard.empty())
- mBrowserBox->addRow("---");
-
- FOR_EACH (STD_VECTOR<OnlinePlayer*>::const_iterator, it, mDisregard)
- mBrowserBox->addRow((*it)->getText());
-
- if (mScrollArea->getVerticalMaxScroll() <
- mScrollArea->getVerticalScrollAmount())
- {
- mScrollArea->setVerticalScrollAmount(
- mScrollArea->getVerticalMaxScroll());
- }
- mBrowserBox->updateHeight();
-}
-
-void WhoIsOnline::handlerPlayerRelation(const std::string &nick,
- OnlinePlayer *const player)
-{
- if (player == nullptr)
- return;
- switch (playerRelations.getRelation(nick))
- {
- case Relation::NEUTRAL:
- default:
- setNeutralColor(player);
- mNeutral.push_back(player);
- break;
-
- case Relation::FRIEND:
- player->setText("2");
- if (mGroupFriends)
- mFriends.push_back(player);
- else
- mNeutral.push_back(player);
- break;
-
- case Relation::DISREGARDED:
- case Relation::BLACKLISTED:
- player->setText("8");
- mDisregard.push_back(player);
- break;
-
- case Relation::ENEMY2:
- player->setText("1");
- mEnemy.push_back(player);
- break;
-
- case Relation::IGNORED:
- case Relation::ERASED:
- // Ignore the ignored.
- break;
- }
-}
-
-void WhoIsOnline::loadList(const STD_VECTOR<OnlinePlayer*> &list)
-{
- mBrowserBox->clearRows();
- const size_t numOnline = list.size();
-
- FOR_EACH (std::set<OnlinePlayer*>::iterator, itd, mOnlinePlayers)
- delete *itd;
- mOnlinePlayers.clear();
- mOnlineNicks.clear();
-
- mShowLevel = config.getBoolValue("showlevel");
-
- FOR_EACH (STD_VECTOR<OnlinePlayer*>::const_iterator, it, list)
- {
- OnlinePlayer *player = *it;
- const std::string nick = player->getNick();
- mOnlinePlayers.insert(player);
- mOnlineNicks.insert(nick);
-
- if (!mShowLevel)
- player->setLevel(0);
-
- handlerPlayerRelation(nick, player);
- }
-
- updateWindow(numOnline);
- if (!mOnlineNicks.empty())
- {
- if (chatWindow != nullptr)
- chatWindow->updateOnline(mOnlineNicks);
- if (socialWindow != nullptr)
- socialWindow->updateActiveList();
- if (actorManager != nullptr)
- actorManager->updateSeenPlayers(mOnlineNicks);
- }
- updateSize();
- mFriends.clear();
- mNeutral.clear();
- mDisregard.clear();
- mEnemy.clear();
-}
-
-#ifdef TMWA_SUPPORT
-void WhoIsOnline::loadWebList()
-{
- if (mMemoryBuffer == nullptr)
- return;
-
- // Reallocate and include terminating 0 character
- mMemoryBuffer = static_cast<char*>(
- realloc(mMemoryBuffer, mDownloadedBytes + 1));
- if (mMemoryBuffer == nullptr)
- return;
-
- mMemoryBuffer[mDownloadedBytes] = '\0';
-
- mBrowserBox->clearRows();
- bool listStarted(false);
- std::string lineStr;
- size_t numOnline(0U);
-
- // Tokenize and add each line separately
- char *line = strtok(mMemoryBuffer, "\n");
- const std::string gmText("(GM)");
- const std::string gmText2("(gm)");
-
- FOR_EACH (std::set<OnlinePlayer*>::iterator, itd, mOnlinePlayers)
- delete *itd;
-
- mOnlinePlayers.clear();
- mOnlineNicks.clear();
-
- mShowLevel = config.getBoolValue("showlevel");
-
- while (line != nullptr)
- {
- std::string nick;
- lineStr = line;
- trim(lineStr);
- if (listStarted == true)
- {
- if (lineStr.find(" users are online.") == std::string::npos)
- {
- if (lineStr.length() > 24)
- {
- nick = lineStr.substr(0, 24);
- lineStr = lineStr.substr(25);
- }
- else
- {
- nick = lineStr;
- lineStr.clear();
- }
- trim(nick);
-
- bool isGM(false);
- size_t pos = lineStr.find(gmText, 0);
- if (pos != std::string::npos)
- {
- lineStr = lineStr.substr(pos + gmText.length());
- isGM = true;
- }
- else
- {
- pos = lineStr.find(gmText2, 0);
- if (pos != std::string::npos)
- {
- lineStr = lineStr.substr(pos + gmText.length());
- isGM = true;
- }
- }
-
- trim(lineStr);
- pos = lineStr.find('/', 0);
-
- if (pos != std::string::npos)
- lineStr = lineStr.substr(0, pos);
-
- int level = 0;
- if (!lineStr.empty())
- level = atoi(lineStr.c_str());
-
- if (actorManager != nullptr)
- {
- Being *const being = actorManager->findBeingByName(
- nick, ActorType::Player);
- if (being != nullptr)
- {
- if (level > 0)
- {
- being->setLevel(level);
- being->updateName();
- }
- else
- {
- if (being->getLevel() > 1)
- level = being->getLevel();
- }
- }
- }
-
- if (!mShowLevel)
- level = 0;
-
- OnlinePlayer *const player = new OnlinePlayer(nick,
- CAST_U8(255), level,
- Gender::UNSPECIFIED, -1);
- mOnlinePlayers.insert(player);
- mOnlineNicks.insert(nick);
-
- if (isGM)
- player->setIsGM(true);
-
- numOnline++;
- handlerPlayerRelation(nick, player);
- }
- }
- else if (lineStr.find("------------------------------")
- != std::string::npos)
- {
- listStarted = true;
- }
- line = strtok(nullptr, "\n");
- }
-
- updateWindow(numOnline);
- mBrowserBox->updateHeight();
-
- // Free the memory buffer now that we don't need it anymore
- free(mMemoryBuffer);
- mMemoryBuffer = nullptr;
- mFriends.clear();
- mNeutral.clear();
- mDisregard.clear();
- mEnemy.clear();
-}
-
-size_t WhoIsOnline::memoryWrite(void *restrict ptr,
- size_t size,
- size_t nmemb,
- FILE *restrict stream)
-{
- if (stream == nullptr)
- return 0;
-
- WhoIsOnline *restrict const wio =
- reinterpret_cast<WhoIsOnline *restrict>(stream);
- const size_t totalMem = size * nmemb;
- wio->mMemoryBuffer = static_cast<char*>(realloc(wio->mMemoryBuffer,
- CAST_SIZE(wio->mDownloadedBytes) + totalMem));
- if (wio->mMemoryBuffer != nullptr)
- {
- memcpy(&(wio->mMemoryBuffer[wio->mDownloadedBytes]), ptr, totalMem);
- wio->mDownloadedBytes += CAST_S32(totalMem);
- }
-
- return totalMem;
-}
-
-int WhoIsOnline::downloadThread(void *ptr)
-{
- int attempts = 0;
- WhoIsOnline *const wio = reinterpret_cast<WhoIsOnline *>(ptr);
- if (wio == nullptr)
- return 0;
- CURLcode res;
- const std::string url(settings.onlineListUrl + "/online.txt");
-
- while (attempts < 1 && !wio->mDownloadComplete)
- {
- CURL *curl = curl_easy_init();
- if (curl != nullptr)
- {
- if (!wio->mAllowUpdate)
- {
- curl_easy_cleanup(curl);
- curl = nullptr;
- break;
- }
- wio->mDownloadedBytes = 0;
- curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
- curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1);
- curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION,
- &WhoIsOnline::memoryWrite);
- curl_easy_setopt(curl, CURLOPT_WRITEDATA, ptr);
-
- curl_easy_setopt(curl,
- CURLOPT_USERAGENT,
- settings.userAgent.c_str());
-
- curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, wio->mCurlError);
- curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
- curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 1);
- curl_easy_setopt(curl, CURLOPT_PROGRESSDATA, ptr);
-
-#if LIBCURL_VERSION_NUM >= 0x070a00
- curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);
-#endif // LIBCURL_VERSION_NUM >= 0x070a00
- curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 7);
- curl_easy_setopt(curl, CURLOPT_TIMEOUT, 30);
- Net::Download::addHeaders(curl);
- Net::Download::addProxy(curl);
- Net::Download::secureCurl(curl);
-
- // Make sure the resources2.txt and news.txt aren't cached,
- // in order to always get the latest version.
- struct curl_slist *pHeaders = nullptr;
- pHeaders = curl_slist_append(
- pHeaders, "pragma: no-cache");
- pHeaders = curl_slist_append(pHeaders,
- "Cache-Control: no-cache");
- curl_easy_setopt(curl, CURLOPT_HTTPHEADER, pHeaders);
-
- if ((res = curl_easy_perform(curl)) != 0)
- {
- wio->mDownloadStatus = UPDATE_ERROR;
- PRAGMA45(GCC diagnostic push)
- PRAGMA45(GCC diagnostic ignored "-Wswitch-enum")
- switch (res)
- {
- case CURLE_COULDNT_CONNECT:
- default:
- std::cerr << "curl error "
- << CAST_U32(res) << ": "
- << wio->mCurlError << " host: "
- << url.c_str() << std::endl;
- break;
- }
- PRAGMA45(GCC diagnostic pop)
- attempts++;
- curl_easy_cleanup(curl);
- curl_slist_free_all(pHeaders);
- curl = nullptr;
- continue;
- }
-
- curl_easy_cleanup(curl);
- curl_slist_free_all(pHeaders);
-
- // It's stored in memory, we're done
- wio->mDownloadComplete = true;
- }
- if (!wio->mAllowUpdate)
- break;
- attempts++;
- }
-
- if (!wio->mDownloadComplete)
- wio->mDownloadStatus = UPDATE_ERROR;
- return 0;
-}
-#endif // TMWA_SUPPORT
-
-void WhoIsOnline::download()
-{
- if (mServerSideList)
- {
- if (PacketLimiter::limitPackets(PacketType::PACKET_ONLINELIST))
- playerHandler->requestOnlineList();
- }
-#ifdef TMWA_SUPPORT
- else if (mWebList)
- {
- mDownloadComplete = true;
- SDL::WaitThread(mThread);
- mThread = nullptr;
- mDownloadComplete = false;
- mThread = SDL::createThread(&WhoIsOnline::downloadThread,
- "whoisonline", this);
- if (mThread == nullptr)
- mDownloadStatus = UPDATE_ERROR;
- }
-#endif // TMWA_SUPPORT
-}
-
-void WhoIsOnline::logic()
-{
- BLOCK_START("WhoIsOnline::logic")
- mScrollArea->logic();
- BLOCK_END("WhoIsOnline::logic")
-}
-
-void WhoIsOnline::slowLogic()
-{
- if (!mAllowUpdate)
- return;
-
- BLOCK_START("WhoIsOnline::slowLogic")
- if (mUpdateTimer == 0)
- mUpdateTimer = cur_time;
-
- const double timeDiff = difftime(cur_time, mUpdateTimer);
- const int timeLimit = isWindowVisible() ? 20 : 120;
-
- if (mUpdateOnlineList && timeDiff >= timeLimit
- && mDownloadStatus != UPDATE_LIST)
- {
- if (mDownloadComplete == true)
- {
- // TRANSLATORS: who is online window name
- setCaption(_("Who Is Online - Updating"));
- mUpdateTimer = 0;
- mDownloadStatus = UPDATE_LIST;
- download();
- }
- }
-
-#ifdef TMWA_SUPPORT
- switch (mDownloadStatus)
- {
- case UPDATE_ERROR:
- logger->assertLog("Failed to fetch the online list:");
- if (mCurlError != nullptr)
- logger->assertLog("%s", mCurlError);
- mDownloadStatus = UPDATE_COMPLETE;
- // TRANSLATORS: who is online window name
- setCaption(_("Who Is Online - error"));
- mUpdateButton->setEnabled(true);
- mUpdateTimer = cur_time + 240;
- mDownloadComplete = true;
- updateSize();
- break;
- case UPDATE_LIST:
- if (mDownloadComplete == true)
- {
- loadWebList();
- mDownloadStatus = UPDATE_COMPLETE;
- mUpdateButton->setEnabled(true);
- mUpdateTimer = 0;
- updateSize();
- if (!mOnlineNicks.empty())
- {
- if (chatWindow != nullptr)
- chatWindow->updateOnline(mOnlineNicks);
- if (socialWindow != nullptr)
- socialWindow->updateActiveList();
- if (actorManager != nullptr)
- actorManager->updateSeenPlayers(mOnlineNicks);
- }
- }
- break;
- case UPDATE_COMPLETE:
- default:
- break;
- }
-#endif // TMWA_SUPPORT
-
- BLOCK_END("WhoIsOnline::slowLogic")
-}
-
-void WhoIsOnline::action(const ActionEvent &event)
-{
- if (event.getId() == "update")
- {
-#ifdef TMWA_SUPPORT
- if (!mServerSideList)
- {
- if (mDownloadStatus == UPDATE_COMPLETE)
- {
- mUpdateTimer = cur_time - 20;
- if (mUpdateButton != nullptr)
- mUpdateButton->setEnabled(false);
- // TRANSLATORS: who is online window name
- setCaption(_("Who Is Online - Update"));
- SDL::WaitThread(mThread);
- mThread = nullptr;
- mDownloadComplete = true;
- }
- }
- else
-#endif // TMWA_SUPPORT
- {
- if (PacketLimiter::limitPackets(PacketType::PACKET_ONLINELIST))
- {
- mUpdateTimer = cur_time;
- playerHandler->requestOnlineList();
- }
- }
- }
-}
-
-void WhoIsOnline::widgetResized(const Event &event)
-{
- Window::widgetResized(event);
- updateSize();
-}
-
-void WhoIsOnline::updateSize()
-{
- const Rect area = getChildrenArea();
- if (mUpdateButton != nullptr)
- mUpdateButton->setWidth(area.width - 10);
-
- if (mScrollArea != nullptr)
- mScrollArea->setSize(area.width - 10, area.height - 10 - 30);
-}
-
-const std::string WhoIsOnline::prepareNick(const std::string &restrict nick,
- const int level,
- const std::string &restrict
- color) const
-{
- const std::string text = encodeLinkText(nick);
- if (mShowLevel && level > 1)
- {
- return strprintf("@@%s|##%s%s (%d)@@", text.c_str(),
- color.c_str(), text.c_str(), level);
- }
- return strprintf("@@%s|##%s%s@@", text.c_str(),
- color.c_str(), text.c_str());
-}
-
-void WhoIsOnline::optionChanged(const std::string &name)
-{
- if (name == "updateOnlineList")
- mUpdateOnlineList = config.getBoolValue("updateOnlineList");
- else if (name == "groupFriends")
- mGroupFriends = config.getBoolValue("groupFriends");
-}
-
-void WhoIsOnline::setNeutralColor(OnlinePlayer *const player)
-{
- if (player == nullptr)
- return;
-
- if ((actorManager != nullptr) && (localPlayer != nullptr))
- {
- const std::string &nick = player->getNick();
- if (nick == localPlayer->getName())
- {
- player->setText("s");
- return;
- }
- if (localPlayer->isInParty())
- {
- const Party *const party = localPlayer->getParty();
- if (party != nullptr)
- {
- if (party->getMember(nick) != nullptr)
- {
- player->setText("P");
- return;
- }
- }
- }
-
- const Being *const being = actorManager->findBeingByName(nick);
- if (being != nullptr)
- {
- const Guild *const guild2 = localPlayer->getGuild();
- if (guild2 != nullptr)
- {
- const Guild *const guild1 = being->getGuild();
- if (guild1 != nullptr)
- {
- if (guild1->getId() == guild2->getId()
- || (guild2->getMember(nick) != nullptr))
- {
- player->setText("U");
- return;
- }
- }
- else if (guild2->isMember(nick))
- {
- player->setText("U");
- return;
- }
- }
- }
- const Guild *const guild3 = Guild::getGuild(1);
- if ((guild3 != nullptr) && guild3->isMember(nick))
- {
- player->setText("U");
- return;
- }
- }
- player->setText("0");
-}
-
-void WhoIsOnline::getPlayerNames(StringVect &names)
-{
- names.clear();
- FOR_EACH (std::set<std::string>::const_iterator, it, mOnlineNicks)
- names.push_back(*it);
-}
-
-void OnlinePlayer::setText(std::string color)
-{
- mText.clear();
-
- if (mStatus != 255 && (actorManager != nullptr))
- {
- Being *const being = actorManager->findBeingByName(
- mNick, ActorType::Player);
- if (being != nullptr)
- {
- being->setState(mStatus);
- // for now highlight versions > 3
- if (mVersion > 3)
- being->setAdvanced(true);
- }
- }
-
- if ((mStatus != 255 && ((mStatus & BeingFlag::GM) != 0)) || mIsGM)
- mText.append("(GM) ");
-
- if (mLevel > 0)
- mText.append(strprintf("%d", mLevel));
-
- if (mGender == Gender::FEMALE)
- mText.append("\u2640");
- else if (mGender == Gender::MALE)
- mText.append("\u2642");
-
- if (mStatus > 0 && mStatus != 255)
- {
- if ((mStatus & BeingFlag::SHOP) != 0)
- mText.append("$");
- if ((mStatus & BeingFlag::AWAY) != 0)
- {
- // TRANSLATORS: this away status writed in player nick
- mText.append(_("A"));
- }
- if ((mStatus & BeingFlag::INACTIVE) != 0)
- {
- // TRANSLATORS: this inactive status writed in player nick
- mText.append(_("I"));
- }
-
- if (((mStatus & BeingFlag::GM) != 0) && color == "0")
- color = "2";
- }
- else if (mIsGM && color == "0")
- {
- color = "2";
- }
-
- if (mVersion > 0)
- mText.append(strprintf(" - %d", mVersion));
-
- const std::string text = encodeLinkText(mNick);
- mText = strprintf("@@%s|##%s%s %s@@", text.c_str(), color.c_str(),
- text.c_str(), mText.c_str());
-}
diff --git a/src/gui/windows/whoisonline.h b/src/gui/windows/whoisonline.h
deleted file mode 100644
index afdb43785..000000000
--- a/src/gui/windows/whoisonline.h
+++ /dev/null
@@ -1,182 +0,0 @@
-/*
- * The ManaPlus Client
- * Copyright (C) 2009 The Mana World Development Team
- * Copyright (C) 2009-2010 Andrei Karas
- * Copyright (C) 2011-2017 The ManaPlus Developers
- *
- * This file is part of The ManaPlus Client.
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-#ifndef GUI_WINDOWS_WHOISONLINE_H
-#define GUI_WINDOWS_WHOISONLINE_H
-
-#include "gui/widgets/linkhandler.h"
-#include "gui/widgets/window.h"
-
-#include "listeners/actionlistener.h"
-
-class Button;
-class OnlinePlayer;
-class ScrollArea;
-class StaticBrowserBox;
-
-/**
- * Update progress window GUI
- *
- * \ingroup GUI
- */
-class WhoIsOnline final : public Window,
- public LinkHandler,
- public ActionListener,
- public ConfigListener
-{
- public:
- /**
- * Constructor.
- */
- WhoIsOnline();
-
- A_DELETE_COPY(WhoIsOnline)
-
- /**
- * Destructor
- */
- ~WhoIsOnline();
-
- void postInit() override final;
-
-#ifdef TMWA_SUPPORT
- /**
- * Loads and display online list from the memory buffer.
- */
- void loadWebList();
-#endif // TMWA_SUPPORT
-
- void loadList(const STD_VECTOR<OnlinePlayer*> &list);
-
- void handleLink(const std::string& link,
- MouseEvent *event) override final;
-
- void logic() override final;
-
- void slowLogic();
-
- void action(const ActionEvent &event) override final;
-
- void widgetResized(const Event &event) override final;
-
- const std::set<OnlinePlayer*> &getOnlinePlayers() const noexcept2
- A_WARN_UNUSED
- { return mOnlinePlayers; }
-
- const std::set<std::string> &getOnlineNicks() const noexcept2
- A_WARN_UNUSED
- { return mOnlineNicks; }
-
- void setAllowUpdate(const bool n) noexcept2
- { mAllowUpdate = n; }
-
- void optionChanged(const std::string &name) override final;
-
- void updateList(StringVect &list);
-
- void readFromWeb();
-
- static void setNeutralColor(OnlinePlayer *const player);
-
- void getPlayerNames(StringVect &names);
-
- private:
- void download();
-
- void updateSize();
-
- void handlerPlayerRelation(const std::string &nick,
- OnlinePlayer *const player);
-
-#ifdef TMWA_SUPPORT
- /**
- * The thread function that download the files.
- */
- static int downloadThread(void *ptr);
-
- /**
- * A libcurl callback for writing to memory.
- */
- static size_t memoryWrite(void *restrict ptr,
- size_t size,
- size_t nmemb,
- FILE *restrict stream);
-#endif // TMWA_SUPPORT
-
- const std::string prepareNick(const std::string &restrict nick,
- const int level,
- const std::string &restrict color)
- const A_WARN_UNUSED;
-
- void updateWindow(size_t numOnline);
-
- enum DownloadStatus
- {
- UPDATE_ERROR = 0,
- UPDATE_COMPLETE,
- UPDATE_LIST
- };
-
- time_t mUpdateTimer;
-
- /** A thread that use libcurl to download updates. */
- SDL_Thread *mThread;
-
- /** Buffer for files downloaded to memory. */
- char *mMemoryBuffer;
-
- /** Buffer to handler human readable error provided by curl. */
- char *mCurlError A_NONNULLPOINTER;
-
- StaticBrowserBox *mBrowserBox A_NONNULLPOINTER;
- ScrollArea *mScrollArea A_NONNULLPOINTER;
- Button *mUpdateButton A_NONNULLPOINTER;
-
- std::set<OnlinePlayer*> mOnlinePlayers;
- std::set<std::string> mOnlineNicks;
-
- STD_VECTOR<OnlinePlayer*> mFriends;
- STD_VECTOR<OnlinePlayer*> mNeutral;
- STD_VECTOR<OnlinePlayer*> mDisregard;
- STD_VECTOR<OnlinePlayer*> mEnemy;
-
- /** Byte count currently downloaded in mMemoryBuffer. */
- int mDownloadedBytes;
-
- /** Status of the current download. */
- WhoIsOnline::DownloadStatus mDownloadStatus;
-
- /** Flag that show if current download is complete. */
- bool mDownloadComplete;
- bool mAllowUpdate;
- bool mShowLevel;
- bool mUpdateOnlineList;
- bool mGroupFriends;
-#ifdef TMWA_SUPPORT
- bool mWebList;
-#endif
- bool mServerSideList;
-};
-
-extern WhoIsOnline *whoIsOnline;
-
-#endif // GUI_WINDOWS_WHOISONLINE_H
diff --git a/src/gui/windows/worldselectdialog.cpp b/src/gui/windows/worldselectdialog.cpp
deleted file mode 100644
index 919440a40..000000000
--- a/src/gui/windows/worldselectdialog.cpp
+++ /dev/null
@@ -1,134 +0,0 @@
-/*
- * The ManaPlus Client
- * Copyright (C) 2004-2009 The Mana World Development Team
- * Copyright (C) 2009-2010 The Mana Developers
- * Copyright (C) 2011-2017 The ManaPlus Developers
- *
- * This file is part of The ManaPlus Client.
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-#include "gui/windows/worldselectdialog.h"
-
-#include "client.h"
-#include "settings.h"
-
-#include "gui/widgets/button.h"
-#include "gui/widgets/createwidget.h"
-#include "gui/widgets/layout.h"
-#include "gui/widgets/listbox.h"
-#include "gui/widgets/scrollarea.h"
-
-#include "gui/models/worldlistmodel.h"
-
-#include "net/loginhandler.h"
-
-#include "utils/delete2.h"
-#include "utils/gettext.h"
-
-#include "debug.h"
-
-extern WorldInfo **server_info;
-
-WorldSelectDialog::WorldSelectDialog(const Worlds &worlds) :
- // TRANSLATORS: world select dialog name
- Window(_("Select World"), Modal_false, nullptr, "world.xml"),
- ActionListener(),
- KeyListener(),
- mWorldListModel(new WorldListModel(worlds)),
- mWorldList(CREATEWIDGETR(ListBox, this, mWorldListModel, "")),
- // TRANSLATORS: world dialog button
- mChangeLoginButton(new Button(this, _("Change Login"), "login", this)),
- // TRANSLATORS: world dialog button
- mChooseWorld(new Button(this, _("Choose World"), "world", this))
-{
- ScrollArea *const worldsScroll = new ScrollArea(this, mWorldList,
- fromBool(getOptionBool("showbackground"), Opaque),
- "world_background.xml");
-
- worldsScroll->setHorizontalScrollPolicy(ScrollArea::SHOW_NEVER);
-
- place(0, 0, worldsScroll, 3, 5).setPadding(2);
- place(1, 5, mChangeLoginButton);
- place(2, 5, mChooseWorld);
-
- // Make sure the list has enough height
- getLayout().setRowHeight(0, 60);
-
- reflowLayout(0, 0);
-
- if (worlds.empty())
- {
- // Disable Ok button
- mChooseWorld->setEnabled(false);
- }
- else
- {
- // Select first server
- mWorldList->setSelected(0);
- }
-
- addKeyListener(this);
-
- center();
-}
-
-void WorldSelectDialog::postInit()
-{
- Window::postInit();
- setVisible(Visible_true);
- mChooseWorld->requestFocus();
-}
-
-WorldSelectDialog::~WorldSelectDialog()
-{
- delete2(mWorldListModel);
-}
-
-void WorldSelectDialog::action(const ActionEvent &event)
-{
- const std::string &eventId = event.getId();
- if (eventId == "world")
- {
- mChangeLoginButton->setEnabled(false);
- mChooseWorld->setEnabled(false);
- loginHandler->chooseServer(mWorldList->getSelected(),
- settings.persistentIp);
-
- // Check in case netcode moves us forward
- if (client->getState() == State::WORLD_SELECT)
- client->setState(State::WORLD_SELECT_ATTEMPT);
- }
- else if (eventId == "login")
- {
- client->setState(State::PRE_LOGIN);
- }
-}
-
-void WorldSelectDialog::keyPressed(KeyEvent &event)
-{
- const InputActionT actionId = event.getActionId();
-
- if (actionId == InputAction::GUI_CANCEL)
- {
- action(ActionEvent(nullptr,
- mChangeLoginButton->getActionEventId()));
- }
- else if (actionId == InputAction::GUI_SELECT ||
- actionId == InputAction::GUI_SELECT2)
- {
- action(ActionEvent(nullptr, mChooseWorld->getActionEventId()));
- }
-}
diff --git a/src/gui/windows/worldselectdialog.h b/src/gui/windows/worldselectdialog.h
deleted file mode 100644
index 4c6dc0f8c..000000000
--- a/src/gui/windows/worldselectdialog.h
+++ /dev/null
@@ -1,77 +0,0 @@
-/*
- * The ManaPlus Client
- * Copyright (C) 2004-2009 The Mana World Development Team
- * Copyright (C) 2009-2010 The Mana Developers
- * Copyright (C) 2011-2017 The ManaPlus Developers
- *
- * This file is part of The ManaPlus Client.
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-
-#ifndef GUI_WINDOWS_WORLDSELECTDIALOG_H
-#define GUI_WINDOWS_WORLDSELECTDIALOG_H
-
-#include "gui/widgets/window.h"
-
-#include "net/worldinfo.h"
-
-#include "listeners/actionlistener.h"
-#include "listeners/keylistener.h"
-
-class Button;
-class ListBox;
-class WorldListModel;
-
-/**
- * The server select dialog.
- *
- * \ingroup Interface
- */
-class WorldSelectDialog final : public Window,
- public ActionListener,
- public KeyListener
-{
- public:
- /**
- * Constructor
- *
- * @see Window::Window
- */
- explicit WorldSelectDialog(const Worlds &worlds);
-
- A_DELETE_COPY(WorldSelectDialog)
-
- void postInit() override final;
-
- /**
- * Destructor.
- */
- ~WorldSelectDialog();
-
- /**
- * Called when receiving actions from the widgets.
- */
- void action(const ActionEvent &event) override final;
-
- void keyPressed(KeyEvent &event) override final;
-
- private:
- WorldListModel *mWorldListModel A_NONNULLPOINTER;
- ListBox *mWorldList A_NONNULLPOINTER;
- Button *mChangeLoginButton A_NONNULLPOINTER;
- Button *mChooseWorld A_NONNULLPOINTER;
-};
-
-#endif // GUI_WINDOWS_WORLDSELECTDIALOG_H