Esempio n. 1
0
/**
 *  @brief: Compute all the permutations of the given string that has all
 *      unique characters.
 *  @param: [in] str: The given string whose permutations will be computed.
 *  @return: StringVect
 *      A list of all the permutations of the given string.
 */
StringVect permutation_str_no_dup(const std::string & str) {
    const int STR_SIZE = static_cast<int>(str.size());

    // Handle special cases.
    if (STR_SIZE == 0) {
        // If str is empty, return an empty set.
        return StringVect();
    } else if (STR_SIZE == 1) {
        // One-char string has only one permutation which is itself.
        return StringVect(1, str);
    }

    // Now the STR_SIZE > 1.

    // Compute the permutations.
    char ch = str[0];
    StringVect sub_perms = permutation_str_no_dup(str.substr(1));

    // Insert ch to every possible position of perms.
    StringVect perms;
    for (size_t i = 0; i < sub_perms.size(); ++i) {
        const std::string & subperm = sub_perms[i];
        for (size_t j = 0; j < subperm.size(); ++j) {
            std::string replica(subperm);
            replica.insert(replica.begin() + j, ch);
            perms.push_back(replica);
        }
        // Finally, we need to insert ch to the end of replica.
        std::string replica(subperm);
        replica.push_back(ch);
        perms.push_back(replica);
    }

    return perms;
}
Esempio n. 2
0
void CharCreateDialog::setAttributes(const StringVect &labels,
                                     const int available,
                                     const int min, const int max)
{
    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(labels.size());
    mAttributeSlider.resize(labels.size());
    mAttributeValue.resize(labels.size());

    const int w = 480;
    int h = 350;
    const int y = 118 + 29;

    for (unsigned i = 0, sz = static_cast<unsigned>(labels.size());
         i < sz; i++)
    {
        mAttributeLabel[i] = new Label(this, labels[i]);
        mAttributeLabel[i]->setWidth(70);
        mAttributeLabel[i]->setPosition(5, y + i * 24);
        mAttributeLabel[i]->adjustSize();
        add(mAttributeLabel[i]);

        mAttributeSlider[i] = new Slider(this, min, max, 1.0);
        mAttributeSlider[i]->setDimension(Rect(140, y + 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, y + i * 24);
        add(mAttributeValue[i]);
    }

    updateSliders();
    if (!available)
    {
        mAttributesLeft->setVisible(Visible_false);
        h = y;
        setContentSize(w, h);
    }
    if (serverFeatures->haveCreateCharGender() && y < 160)
    {
        h = 160;
        setContentSize(w, h);
    }
    setButtonsPosition(w, h);
}
Esempio n. 3
0
void CharCreateDialog::setAttributes(const StringVect &labels,
                                     int available, int min, int max)
{
    mMaxPoints = available;

    for (unsigned i = 0; i < mAttributeLabel.size(); i++)
    {
        remove(mAttributeLabel[i]);
        delete mAttributeLabel[i];
        mAttributeLabel[i] = nullptr;
        remove(mAttributeSlider[i]);
        delete mAttributeSlider[i];
        mAttributeSlider[i] = nullptr;
        remove(mAttributeValue[i]);
        delete mAttributeValue[i];
        mAttributeValue[i] = nullptr;
    }

    mAttributeLabel.resize(labels.size());
    mAttributeSlider.resize(labels.size());
    mAttributeValue.resize(labels.size());

    int w = 480;
    int h = 350;

    for (unsigned i = 0; i < labels.size(); i++)
    {
        mAttributeLabel[i] = new Label(labels[i]);
        mAttributeLabel[i]->setWidth(70);
        mAttributeLabel[i]->setPosition(5, 145 + i * 24);
        mAttributeLabel[i]->adjustSize();
        add(mAttributeLabel[i]);

        mAttributeSlider[i] = new Slider(min, max);
        mAttributeSlider[i]->setDimension(gcn::Rectangle(140, 145 + i * 24,
                                                         150, 12));
        mAttributeSlider[i]->setActionEventId("statslider");
        mAttributeSlider[i]->addActionListener(this);
        add(mAttributeSlider[i]);

        mAttributeValue[i] = new Label(toString(min));
        mAttributeValue[i]->setPosition(295, 145 + i * 24);
        add(mAttributeValue[i]);
    }

    mAttributesLeft->setPosition(15, 300);
    updateSliders();

    mCancelButton->setPosition(
            w / 2,
            h - 5 - mCancelButton->getHeight());
    mCreateButton->setPosition(
            mCancelButton->getX() - 5 - mCreateButton->getWidth(),
            h - 5 - mCancelButton->getHeight());
}
Esempio n. 4
0
void InputManager::retrieve()
{
    for (int i = 0; i < InputAction::TOTAL; i++)
    {
#ifdef USE_SDL2
        const std::string cf = std::string("sdl2")
            + inputActionData[i].configField;
#else
        const std::string cf = inputActionData[i].configField;
#endif
        if (!cf.empty())
        {
            mNameMap[cf] = i;
            InputFunction &kf = mKey[i];
            const std::string keyStr = config.getValue(cf, "");
            const size_t keyStrSize = keyStr.size();
            if (keyStr.empty())
                continue;

            StringVect keys;
            splitToStringVector(keys, keyStr, ',');
            unsigned int i2 = 0;
            for (StringVectCIter it = keys.begin(), it_end = keys.end();
                 it != it_end && i2 < inputFunctionSize; ++ it)
            {
                std::string keyStr2 = *it;
                if (keyStrSize < 2)
                    continue;
                int type = InputType::KEYBOARD;
                if ((keyStr2[0] < '0' || keyStr2[0] > '9')
                    && keyStr2[0] != '-')
                {
                    switch (keyStr2[0])
                    {
                        case 'm':
                            type = InputType::MOUSE;
                            break;
                        case 'j':
                            type = InputType::JOYSTICK;
                            break;
                        default:
                            break;
                    }
                    keyStr2 = keyStr2.substr(1);
                }
                const int key = atoi(keyStr2.c_str());
                if (key >= -255 && key < SDLK_LAST)
                {
                    kf.values[i2] = InputItem(type, key);
                    i2 ++;
                }
            }
        }
    }
}
// ----------------------------------------------------------------------------
int read_n_lines(std::fstream & fs, int N, StringVect & lines) {
    lines.clear();
    int K = 0;
    while (!fs.eof() && K < N) {
        std::string line;
        std::getline(fs, line);
        lines.push_back(line);
        ++K;
    }
    return K;
}
Esempio n. 6
0
void ModeListModel::addCustomMode(std::string mode)
{
    StringVectCIter it = mVideoModes.begin();
    StringVectCIter it_end = mVideoModes.end();
    while (it != it_end)
    {
        if (*it == mode)
            return;
        ++ it;
    }
    mVideoModes.push_back(mode);
}
// ----------------------------------------------------------------------------
int main(int argc, char * argv[]) {

    std::fstream fs;

    fs.open("Project2Data.txt");

    ProdInfo pi;    // The current product info that is being dealt with.
    while (!fs.eof()) {
        StringVect lines;
        pi.Reset();

        // Read the head lines.
        if (read_n_lines(fs, HEAD_LINES, lines) != HEAD_LINES) {
            // We run out of lines. Just break.
            std::cerr << "Not enough head lines." << std::endl;
            break;
        }

        // Parse the lines.
        StringPair sp;
        split_to_pair(rm_carriage(lines[0]), sp);
        pi.id = trim(sp.second);
        split_to_pair(rm_carriage(lines[1]), sp);
        pi.asin = trim(sp.second);
        split_to_pair(rm_carriage(lines[2]), sp);
        pi.title = trim(sp.second);
        split_to_pair(rm_carriage(lines[3]), sp);
        pi.group = trim(sp.second);

        // Read the categories.
        split_to_pair(lines[4], sp);
        int category_count = str_to_int(trim(sp.second));
        if (read_n_lines(fs, category_count, lines) != category_count) {
            // We run out of lines. Just break.
            std::cerr << "Not enough category lines." << std::endl;
            break;
        }
        for (size_t i = 0; i < lines.size(); ++i) {
            pi.categories.push_back(trim(rm_carriage(lines[i])));
        }

        // Write the product info into a SQL statement.
        std::cout << toSQL(pi) << std::endl;

        // Skip the blank lines.
        read_n_lines(fs, SEP_LINES, lines);
    }

    fs.close();

    return 0;
}
Esempio n. 8
0
void Guild::getNames(StringVect &names) const
{
    names.clear();
    MemberList::const_iterator it = mMembers.begin();
    const MemberList::const_iterator it_end = mMembers.end();

    while (it != it_end)
    {
        if (*it)
            names.push_back((*it)->getName());
        ++it;
    }
}
Esempio n. 9
0
void Party::getNames(StringVect &names) const
{
    names.clear();
    MemberList::const_iterator it = mMembers.begin();
    const MemberList::const_iterator it_end = mMembers.end();
    while (it != it_end)
    {
        const PartyMember *const m = *it;
        if (m)
            names.push_back(m->getName());
        ++it;
    }
}
Esempio n. 10
0
std::string Wallpaper::getWallpaper(const int width, const int height)
{
    WallpaperData wp;

    // Wallpaper filename container
    StringVect wallPaperVector;

    FOR_EACH (std::vector<WallpaperData>::const_iterator, iter, wallpaperData)
    {
        wp = *iter;
        if (wp.width <= width && wp.height <= height)
            wallPaperVector.push_back(wp.filename);
    }
Esempio n. 11
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(helpPath.append(file).append(".txt"),
        translator, lines);

    for (size_t i = 0, sz = lines.size(); i < sz; ++i)
        mBrowserBox->addRow(lines[i]);
}
Esempio n. 12
0
/*----------------------------------------------------------------------------------------------------------------------
|	Returns simulated data stored in `sim_pattern_map' as a string in the form of a two-column table. The first column
|	is labeled "Count" and the second is labeled "Pattern". The Count column shows the number of times its associated 
|	pattern was inserted using the insertPattern function. The Pattern column shows a representation of the pattern 
|	itself, using symbols for states provided in the `state_symbols' argument. The `state_symbols' argument should be 
|	a vector of single-character strings supplying a symbol to represent each state that might show up in any pattern.
|	Assumes that no state in any pattern stored in `sim_pattern_map' is greater than or equal to the length of the 
|	`state_symbols' vector (because states are used as indices into `state_symbols').
*/
std::string SimData::patternTable(
  const StringVect & state_symbols) /**< is a vector of strings representing states (e.g. {"A", "C", "G", "T"}). Note that each state symbol should be a string of length 1 (i.e. a single character) */	
	{
	PHYCAS_ASSERT(state_symbols.size() > 0);

	outstr.clear();

	if (sim_pattern_map.empty())
		{
		outstr = "Sorry, no patterns are stored";
		}
	else
		{
		outstr = "     Count  Pattern";

		for (pattern_map_t::iterator it = sim_pattern_map.begin(); it != sim_pattern_map.end(); ++it)
			{
			// Output the count first
			outstr << str(boost::format("\n%10.1f") % it->second) << "  ";

			// Now output the pattern
			std::transform(it->first.begin(), it->first.end(), std::back_inserter(outstr), LookupStateSymbol(state_symbols));
			}
		}
	return outstr;
	}
Esempio n. 13
0
bool SDL::getAllVideoModes(StringVect &modeList)
{
    std::set<std::string> modes;

    for (int display = 0; display < 100; display ++)
    {
        const int numModes = SDL_GetNumDisplayModes(display);
        if (numModes > 0)
        {
            logger->log("Modes for display %d", display);
            for (int f = 0; f < numModes; f ++)
            {
                SDL_DisplayMode mode;
                SDL_GetDisplayMode(display, f, &mode);
                const int w = mode.w;
                const int h = mode.h;
                logger->log("%dx%dx%d", w, h, mode.refresh_rate);
                modes.insert(strprintf("%dx%d", w, h));
            }
        }
    }
    FOR_EACH (std::set<std::string>::const_iterator, it, modes)
        modeList.push_back(*it);
    return true;
}
Esempio n. 14
0
void InputManager::retrieve()
{
    for (int i = 0; i < Input::KEY_TOTAL; i++)
    {
        if (*keyData[i].configField)
        {
            KeyFunction &kf = mKey[i];
            std::string keyStr = config.getValue(keyData[i].configField, "");
            if (keyStr.empty())
                continue;

            StringVect keys;
            splitToStringVector(keys, keyStr, ',');
            int i2 = 0;
            for (StringVectCIter it = keys.begin(), it_end = keys.end();
                 it != it_end && i2 < KeyFunctionSize; ++ it)
            {
                std::string keyStr2 = *it;
                if (keyStr.size() < 2)
                    continue;
                int type = INPUT_KEYBOARD;
                if ((keyStr2[0] < '0' || keyStr2[0] > '9')
                    && keyStr2[0] != '-')
                {
                    switch (keyStr2[0])
                    {
                        case 'm':
                            type = INPUT_MOUSE;
                            break;
                        case 'j':
                            type = INPUT_JOYSTICK;
                            break;
                        default:
                            break;
                    }
                    keyStr2 = keyStr2.substr(1);
                }
                int key = atoi(keyStr2.c_str());
                if (key >= -255 && key < SDLK_LAST)
                {
                    kf.values[i2] = KeyItem(type, key);
                    i2 ++;
                }
            }
        }
    }
}
Esempio n. 15
0
void GuildChatTab::getAutoCompleteList(StringVect &names) const
{
    if (!guildManager)
        return;

    guildManager->getNames(names);
    names.push_back("/notice ");
}
Esempio n. 16
0
 void Reset() {
     id.clear();
     asin.clear();
     title.clear();
     group.clear();
     categories.clear();
     description.clear();
 }
Esempio n. 17
0
void CharServerHandler::setCharCreateDialog(CharCreateDialog *window)
{
    mCharCreateDialog = window;

    if (!mCharCreateDialog)
        return;

    StringVect attributes;
    attributes.push_back(_("Strength:"));
    attributes.push_back(_("Agility:"));
    attributes.push_back(_("Vitality:"));
    attributes.push_back(_("Intelligence:"));
    attributes.push_back(_("Dexterity:"));
    attributes.push_back(_("Luck:"));

    const Token &token =
        static_cast<LoginHandler*>(Net::getLoginHandler())->getToken();

    int minStat = CharDB::getMinStat();
    if (!minStat)
        minStat = 1;
    int maxStat = CharDB::getMaxStat();
    if (!maxStat)
        maxStat = 9;
    int sumStat = CharDB::getSumStat();
    if (!sumStat)
        sumStat = 30;

    mCharCreateDialog->setAttributes(attributes, sumStat, minStat, maxStat);
    mCharCreateDialog->setFixedGender(true, token.sex);
}
Esempio n. 18
0
bool TranslationManager::translateFile(const std::string &fileName,
                                       PoDict *const dict,
                                       StringVect &lines)
{
    if (!dict || fileName.empty())
        return false;

    int contentsLength;
    const ResourceManager *const resman = ResourceManager::getInstance();
    char *fileContents = static_cast<char*>(
                             resman->loadFile(fileName, contentsLength));

    if (!fileContents)
    {
        logger->log("Couldn't load file: %s", fileName.c_str());
        return false;
    }
    std::string str = std::string(fileContents, contentsLength);

    size_t oldPos1 = std::string::npos;
    size_t pos1;

    while ((pos1 = str.find("<<")) != std::string::npos)
    {
        if (pos1 == oldPos1)
            break;  // detected infinite loop
        const size_t pos2 = str.find(">>", pos1 + 2);
        if (pos2 == std::string::npos)
            break;
        const std::string key = str.substr(pos1 + 2, pos2 - pos1 - 2);
        const std::string key2 = "<<" + str.substr(
                                     pos1 + 2, pos2 - pos1 - 2) + ">>";
        const std::string val = dict->getStr(key);

//        logger->log("key:" + key);
        replaceAll(str, key2, val);

        oldPos1 = pos1;
    }

    std::istringstream iss(str);
    std::string line;

    while (getline(iss, line))
        lines.push_back(line);

    free(fileContents);
    return true;
}
Esempio n. 19
0
void Gui::postInit(Graphics *const graphics)
{
    logger->log1("Initializing GUI...");
    // Set graphics
    setGraphics(graphics);

    // Set input
    guiInput = new SDLInput;
    setInput(guiInput);

    // Set focus handler
    delete mFocusHandler;
    mFocusHandler = new FocusHandler;

    // Initialize top GUI widget
    WindowContainer *const guiTop = new WindowContainer(nullptr);
    guiTop->setFocusable(true);
    guiTop->setSize(graphics->mWidth, graphics->mHeight);
    guiTop->setOpaque(false);
    Window::setWindowContainer(guiTop);
    setTop(guiTop);

    const StringVect langs = getLang();
    const bool isJapan = (!langs.empty() && langs[0].size() > 3
        && langs[0].substr(0, 3) == "ja_");
    const bool isChinese = (!langs.empty() && langs[0].size() > 3
        && langs[0].substr(0, 3) == "zh_");

    // Set global font
    const int fontSize = config.getIntValue("fontSize");
    std::string fontFile = config.getValue("font", "");
    if (isJapan)
    {
        fontFile = config.getValue("japanFont", "");
        if (fontFile.empty())
            fontFile = branding.getStringValue("japanFont");
    }
    else if (isChinese)
    {
        fontFile = config.getValue("chinaFont", "");
        if (fontFile.empty())
            fontFile = branding.getStringValue("chinaFont");
    }
    if (fontFile.empty())
        fontFile = branding.getStringValue("font");

    mGuiFont = new Font(fontFile, fontSize);

    // Set particle font
    fontFile = config.getValue("particleFont", "");
    if (isJapan)
    {
        fontFile = config.getValue("japanFont", "");
        if (fontFile.empty())
            fontFile = branding.getStringValue("japanFont");
    }
    else if (isChinese)
    {
        fontFile = config.getValue("chinaFont", "");
        if (fontFile.empty())
            fontFile = branding.getStringValue("chinaFont");
    }
    if (fontFile.empty())
        fontFile = branding.getStringValue("particleFont");

    mInfoParticleFont = new Font(fontFile, fontSize, TTF_STYLE_BOLD);

    // Set bold font
    fontFile = config.getValue("boldFont", "");
    if (fontFile.empty())
        fontFile = branding.getStringValue("boldFont");

    boldFont = new Font(fontFile, fontSize);

    // Set help font
    fontFile = config.getValue("helpFont", "");
    if (fontFile.empty())
        fontFile = branding.getStringValue("helpFont");

    mHelpFont = new Font(fontFile, fontSize);

    // Set secure font
    fontFile = config.getValue("secureFont", "");
    if (fontFile.empty())
        fontFile = branding.getStringValue("secureFont");

    mSecureFont = new Font(fontFile, fontSize);

    // Set npc font
    const int npcFontSize = config.getIntValue("npcfontSize");
    fontFile = config.getValue("npcFont", "");
    if (isJapan)
    {
        fontFile = config.getValue("japanFont", "");
        if (fontFile.empty())
            fontFile = branding.getStringValue("japanFont");
    }
    else if (isChinese)
    {
        fontFile = config.getValue("chinaFont", "");
        if (fontFile.empty())
            fontFile = branding.getStringValue("chinaFont");
    }
    if (fontFile.empty())
        fontFile = branding.getStringValue("npcFont");

    mNpcFont = new Font(fontFile, npcFontSize);

    Widget::setGlobalFont(mGuiFont);

    // Initialize mouse cursor and listen for changes to the option
    setUseCustomCursor(config.getBoolValue("customcursor"));
    setDoubleClick(config.getBoolValue("doubleClick"));
    config.addListener("customcursor", mConfigListener);
    config.addListener("doubleClick", mConfigListener);
}
Esempio n. 20
0
/*----------------------------------------------------------------------------------------------------------------------
|	Saves simulated data stored in `sim_pattern_map' to a file named `filename'. If the file already exists, it will be
|	overwritten without warning. If the file does not yet exist, it will be created. The file written will be a valid
|	NEXUS data file suitable for executing in phylogenetic analysis software that reads the NEXUS file format. The
|	supplied `taxon_names' will be used in the matrix command of the NEXUS file to specify the names of the taxa. 
|	Assumes that the number of elements in `taxon_names' equals `pattern_length'. The `datatype' argument should be the
|	correct NEXUS datatype (e.g. "dna", "standard") for the data simulated. The symbols used for the states are 
|	supplied in the `state_symbols' vector. Each element of this vector should be a single-character string. Assumes
|	that no state in any pattern stored in `sim_pattern_map' is greater than or equal to the length of the 
|	`state_symbols' vector (because states are used as indices into `state_symbols').
*/
void SimData::saveToNexusFile(
  const std::string filename,			/**< is the name of the file to create containing the simulated data stored in this object */
  const StringVect & taxon_names,		/**< is a vector containing the taxon names to use in the saved file */
  const std::string datatype,			/**< is a string to be used as the NEXUS datatype (e.g. "dna" or "standard") */	
  const StringVect & state_symbols)		/**< is a vector of strings representing states (e.g. {"A", "C", "G", "T"}). Note that each state symbol should be a string of length 1 (i.e. a single character) */	
	{
	std::cerr << "taxon_names size = " << taxon_names.size() << std::endl;
	std::cerr << "pattern_length   = " << pattern_length << std::endl;
	std::cerr << "taxon_names: |";
	std::copy(taxon_names.begin(), taxon_names.end(), std::ostream_iterator<std::string>(std::cerr, "|"));
	
	PHYCAS_ASSERT(state_symbols.size() > 0);
	PHYCAS_ASSERT(taxon_names.size() == pattern_length);

	// Find length of longest string in taxon_names vector; this is used later for formatting purposes
	// The 2 is included in case apostrophes are needed when taxon names are output in the matrix command
	unsigned length_of_longest_name = 2 + (unsigned)std::max_element(taxon_names.begin(), taxon_names.end(), StringLengthLess())->length();
	
	std::ofstream outf(filename.c_str());

	outf << "#nexus" << "\n\n";
	outf << "begin data;" << "\n";
	outf << str(boost::format("  dimensions ntax=%d nchar=%d;") % pattern_length % (unsigned)total_count) << "\n";
	outf << "  format datatype=" << datatype << ";" << "\n";
	outf << "  matrix" << "\n";

	// Create a format string to use with boost::format that left-justifies (the "-" flag) the 
	// taxon names in a field of width length_of_longest_name 
	std::string fmtstr = str(boost::format("    %%-%ds") % length_of_longest_name);

	for (unsigned i = 0; i < pattern_length; ++i)
		{
		if (taxon_names[i].find(' ') != std::string::npos)
			{
			std::string s = "'";
			s += taxon_names[i];
			s += "'";
			outf << str(boost::format(fmtstr) % s) << "  ";
			}
		else
			{
			outf << str(boost::format(fmtstr) % taxon_names[i]) << "  ";
			}

#if 1
        // Spit out characters in the order in which they were simulated. While this is a nice feature, 
        // it currently requires storing the data twice (patternVect and sim_pattern_map)
        unsigned nchar = (unsigned)patternVect.size();
        for (unsigned k = 0; k < nchar; ++k)
            {
            unsigned j = (unsigned)patternVect[k][i];
            char s = state_symbols[j][0];
            outf << s;
            }
#else
		for (pattern_map_t::iterator it = sim_pattern_map.begin(); it != sim_pattern_map.end(); ++it)
			{
			// The first member of it is the state, which must be converted from its coded form
			// to the standard symbol for this data type (e.g. A, C, G or T for DNA characters)
			int8_t j = (*it).first[i];

			PHYCAS_ASSERT(j < (int8_t)state_symbols.size());
			char s = state_symbols[j][0];	// use the first (and hopefully only) character in the string at position j

			// The second member of it is the pattern count
			unsigned n = (unsigned)it->second;	//@POL assuming counts not fractional
			for (unsigned k = 0; k < n; ++k)
				{
				outf << s;
				}
			}
#endif
		outf << "\n";
		}

	outf << "  ;" << "\n";
	outf << "end;" << "\n";

	outf.close();
	}
Esempio n. 21
0
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, "", 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)
    {
        setCaption(gettext(inventory->getName().c_str()));
        setWindowName(inventory->getName());
        switch (inventory->getType())
        {
            case InventoryType::Inventory:
            case InventoryType::Trade:
            case InventoryType::Npc:
#ifdef EATHENA_SUPPORT
            case InventoryType::Vending:
            case InventoryType::Mail:
            case InventoryType::Craft:
#endif
            case InventoryType::TypeEnd:
            default:
                mSortDropDown->setSelected(config.getIntValue(
                    "inventorySortOrder"));
                break;
            case InventoryType::Storage:
                mSortDropDown->setSelected(config.getIntValue(
                    "storageSortOrder"));
                break;
#ifdef EATHENA_SUPPORT
            case InventoryType::Cart:
                mSortDropDown->setSelected(config.getIntValue(
                    "cartSortOrder"));
                break;
#endif
        };
    }
    else
    {
        // TRANSLATORS: inventory window name
        setCaption(_("Inventory"));
        setWindowName("Inventory");
        mSortDropDown->setSelected(0);
    }

    if (setupWindow &&
        inventory &&
        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);

    ScrollArea *const invenScroll = new ScrollArea(this, mItems,
        getOptionBool("showbackground"), "inventory_background.xml");
    invenScroll->setHorizontalScrollPolicy(ScrollArea::SHOW_NEVER);

    const int size = config.getIntValue("fontSize");
    mFilter = new TabStrip(this, "filter_" + getWindowName(), size + 16);
    mFilter->addActionListener(this);
    mFilter->setActionEventId("tag_");

    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)
    {
        invInstances.push_back(this);
        return;
    }

    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;
        }

#ifdef EATHENA_SUPPORT
        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;
        }
#endif

        default:
        case InventoryType::Trade:
        case InventoryType::Npc:
#ifdef EATHENA_SUPPORT
        case InventoryType::Vending:
        case InventoryType::Mail:
        case InventoryType::Craft:
#endif
        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);
}
Esempio n. 22
0
void WhisperTab::getAutoCompleteList(StringVect &names) const
{
    names.push_back(mNick);
}
Esempio n. 23
0
int main(int argc, char * argv[]) {
    bool pass = true;

    {
        StringVect perms = permutation_str_no_dup("");
        pass = pass && perms.empty();
    }

    {
        StringVect perms = permutation_str_no_dup("a");
        pass = pass
            && (perms.size() == 1)
            && (std::find(perms.begin(), perms.end(), "a") != perms.end())
            ;
    }

    {
        StringVect perms = permutation_str_no_dup("ab");
        pass = pass
            && (perms.size() == 2)
            && (std::find(perms.begin(), perms.end(), "ab") != perms.end())
            && (std::find(perms.begin(), perms.end(), "ba") != perms.end())
            ;
    }

    {
        StringVect perms = permutation_str_no_dup("abc");
        pass = pass
            && (perms.size() == 6)
            && (std::find(perms.begin(), perms.end(), "abc") != perms.end())
            && (std::find(perms.begin(), perms.end(), "acb") != perms.end())
            && (std::find(perms.begin(), perms.end(), "bac") != perms.end())
            && (std::find(perms.begin(), perms.end(), "bca") != perms.end())
            && (std::find(perms.begin(), perms.end(), "cab") != perms.end())
            && (std::find(perms.begin(), perms.end(), "cba") != perms.end())
            ;
    }

    return (pass ? 0 : -1);
}
void GraphicsManager::setVideoMode()
{
    const int bpp = 0;
    const bool fullscreen = config.getBoolValue("screen");
    const bool hwaccel = config.getBoolValue("hwaccel");
    const bool enableResize = config.getBoolValue("enableresize");
    const bool noFrame = config.getBoolValue("noframe");

#ifdef ANDROID
//    int width = config.getValue("screenwidth", 0);
//    int height = config.getValue("screenheight", 0);
    StringVect videoModes;
    SDL::getAllVideoModes(videoModes);
    if (videoModes.empty())
        logger->error("no video modes detected");
    std::vector<int> res;
    splitToIntVector(res, videoModes[0], 'x');
    if (res.size() != 2)
        logger->error("no video modes detected");

    int width = res[0];
    int height = res[1];
#elif defined __native_client__
#ifdef USE_SDL2
    // not implimented
#else
    const SDL_VideoInfo* info = SDL_GetVideoInfo();
    int width = info->current_w;
    int height = info->current_h;
#endif
#else
    int width = config.getIntValue("screenwidth");
    int height = config.getIntValue("screenheight");
#endif

    // Try to set the desired video mode
    if (!mainGraphics->setVideoMode(width, height, bpp,
        fullscreen, hwaccel, enableResize, noFrame))
    {
        logger->log(strprintf("Couldn't set %dx%dx%d video mode: %s",
            width, height, bpp, SDL_GetError()));

        const int oldWidth = config.getValueInt("oldscreenwidth", -1);
        const int oldHeight = config.getValueInt("oldscreenheight", -1);
        const int oldFullscreen = config.getValueInt("oldscreen", -1);
        if (oldWidth != -1 && oldHeight != -1 && oldFullscreen != -1)
        {
            config.deleteKey("oldscreenwidth");
            config.deleteKey("oldscreenheight");
            config.deleteKey("oldscreen");

            config.setValueInt("screenwidth", oldWidth);
            config.setValueInt("screenheight", oldHeight);
            config.setValue("screen", oldFullscreen == 1);
            if (!mainGraphics->setVideoMode(oldWidth, oldHeight, bpp,
                oldFullscreen, hwaccel, enableResize, noFrame))
            {
                logger->safeError(strprintf("Couldn't restore %dx%dx%d "
                    "video mode: %s", oldWidth, oldHeight, bpp,
                    SDL_GetError()));
            }
        }
    }
}
Esempio n. 25
0
void SpriteDef::loadAnimation(XmlNodePtr animationNode,
                              Action *action, ImageSet *imageSet,
                              int variant_offset)
{
    if (!action || !imageSet)
        return;

    const std::string directionName =
        XML::getProperty(animationNode, "direction", "");
    const SpriteDirection directionType = makeSpriteDirection(directionName);

    if (directionType == DIRECTION_INVALID)
    {
        logger->log("Warning: Unknown direction \"%s\" used in %s",
                directionName.c_str(), getIdPath().c_str());
        return;
    }

    Animation *animation = new Animation;
    action->setAnimation(directionType, animation);

    // Get animation frames
    for_each_xml_child_node(frameNode, animationNode)
    {
        const int delay = XML::getIntProperty(
            frameNode, "delay", 0, 0, 100000);
        int offsetX = XML::getProperty(frameNode, "offsetX", 0) +
            imageSet->getOffsetX();
        int offsetY = XML::getProperty(frameNode, "offsetY", 0) +
            imageSet->getOffsetY();
        int rand = XML::getIntProperty(frameNode, "rand", 100, 0, 100);

        offsetY -= imageSet->getHeight() - 32;
        offsetX -= imageSet->getWidth() / 2 - 16;

        if (xmlNameEqual(frameNode, "frame"))
        {
            const int index = XML::getProperty(frameNode, "index", -1);

            if (index < 0)
            {
                logger->log1("No valid value for 'index'");
                continue;
            }

            Image *img = imageSet->get(index + variant_offset);

            if (!img)
            {
                logger->log("No image at index %d", index + variant_offset);
                continue;
            }

            animation->addFrame(img, delay, offsetX, offsetY, rand);
        }
        else if (xmlNameEqual(frameNode, "sequence"))
        {
            const int start = XML::getProperty(frameNode, "start", -1);
            const int end = XML::getProperty(frameNode, "end", -1);
            const std::string value = XML::getProperty(frameNode, "value", "");
            int repeat = XML::getIntProperty(frameNode, "repeat", 1, 0, 100);

            if (repeat < 1)
            {
                logger->log1("No valid value for 'repeat'");
                continue;
            }

            if (value.empty())
            {
                if (addSequence(start, end, delay, offsetX, offsetY,
                    variant_offset, repeat, rand, imageSet, animation))
                {
                    continue;
                }

            }
            else
            {
                StringVect vals;
                splitToStringVector(vals, value, ',');
                for (StringVectCIter it = vals.begin(), it_end = vals.end();
                     it != it_end; ++ it)
                {
                    std::string str = *it;
                    size_t idx = str.find("-");
                    if (str == "p")
                    {
                        animation->addPause(delay, rand);
                    }
                    else if (idx != std::string::npos)
                    {
                        int v1 = atoi(str.substr(0, idx).c_str());
                        int v2 = atoi(str.substr(idx + 1).c_str());
                        addSequence(v1, v2, delay, offsetX, offsetY,
                            variant_offset, repeat, rand, imageSet, animation);
                    }
                    else
                    {
                        Image *img = imageSet->get(atoi(
                            str.c_str()) + variant_offset);
                        if (img)
                        {
                            animation->addFrame(img, delay,
                                offsetX, offsetY, rand);
                        }
                    }
                }
            }
        }
        else if (xmlNameEqual(frameNode, "pause"))
        {
            animation->addPause(delay, rand);
        }
        else if (xmlNameEqual(frameNode, "end"))
        {
            animation->addTerminator(rand);
        }
        else if (xmlNameEqual(frameNode, "jump"))
        {
            animation->addJump(XML::getProperty(
                frameNode, "action", ""), rand);
        }
        else if (xmlNameEqual(frameNode, "label"))
        {
            std::string name = XML::getProperty(frameNode, "name", "");
            if (!name.empty())
                animation->addLabel(name);
        }
        else if (xmlNameEqual(frameNode, "goto"))
        {
            std::string name = XML::getProperty(frameNode, "label", "");
            if (!name.empty())
                animation->addGoto(name, rand);
        }
    } // for frameNode
}
Esempio n. 26
0
Setup_Perfomance::Setup_Perfomance(const Widget2 *const widget) :
    SetupTabScroll(widget),
#ifdef USE_SDL2
    mSdlDriversList(new NamesModel),
#endif  // USE_SDL2
    mTexturesList(new NamesModel)
{
    // TRANSLATORS: settings tab name
    setName(_("Performance"));

    // Do the layout
    LayoutHelper h(this);
    ContainerPlacer place = h.getPlacer(0, 0);
    place(0, 0, mScroll, 10, 10);

#ifdef USE_SDL2
    StringVect sdlDriversList;
    SDL::getRenderers(sdlDriversList,
        config.getStringValue("sdlDriver"));
    sdlDriversList.insert(sdlDriversList.begin(),
        // TRANSLATORS: sdl driver name
        N_("default"));
#endif  // USE_SDL2

    // TRANSLATORS: settings option
    new SetupItemLabel(_("Better performance (enable for better performance)"),
        "", this,
        Separator_true);

    // TRANSLATORS: settings option
    new SetupItemCheckBox(_("Auto adjust performance"), "",
        "adjustPerfomance", this, "adjustPerfomanceEvent",
        MainConfig_true);

    // TRANSLATORS: settings option
    new SetupItemCheckBox(_("Hw acceleration"), "",
        "hwaccel", this, "hwaccelEvent",
        MainConfig_true);

    // TRANSLATORS: settings option
    new SetupItemCheckBox(_("Enable opacity cache (Software, can "
        "use much memory)"), "", "alphaCache", this, "alphaCacheEvent",
        MainConfig_true);

#ifndef USE_SDL2
    // TRANSLATORS: settings option
    new SetupItemCheckBox(_("Enable map reduce (Software)"), "",
        "enableMapReduce", this, "enableMapReduceEvent",
        MainConfig_true);
#endif  // USE_SDL2

    // TRANSLATORS: settings option
    new SetupItemCheckBox(_("Enable compound sprite delay (Software)"), "",
        "enableCompoundSpriteDelay", this, "enableCompoundSpriteDelayEvent",
        MainConfig_true);

    // TRANSLATORS: settings option
    new SetupItemCheckBox(_("Enable delayed images load (OpenGL)"), "",
        "enableDelayedAnimations", this, "enableDelayedAnimationsEvent",
        MainConfig_true);

    // TRANSLATORS: settings option
    new SetupItemCheckBox(_("Enable texture sampler (OpenGL)"), "",
        "useTextureSampler", this, "useTextureSamplerEvent",
        MainConfig_true);

    // TRANSLATORS: settings option
    new SetupItemCheckBox(_("Enable OpenGL context creation"),
        "", "openglContext", this, "openglContextEvent",
        MainConfig_true);

    // TRANSLATORS: settings option
    new SetupItemCheckBox(_("Enable OpenGL direct state access"),
        "", "enableDSA", this, "enableDSAEvent",
        MainConfig_true);


    // TRANSLATORS: settings option
    new SetupItemLabel(_("Better quality (disable for better performance)"),
        "", this,
        Separator_true);

    // TRANSLATORS: settings option
    new SetupItemCheckBox(_("Enable alpha channel fix (Software, can "
        "be very slow)"), "Can slow down drawing", "enableAlphaFix",
        this, "enableAlphaFixEvent",
        MainConfig_true);

    // TRANSLATORS: settings option
    new SetupItemCheckBox(_("Show beings transparency"), "",
        "beingopacity", this, "beingopacityEvent",
        MainConfig_true);

    // TRANSLATORS: settings option
    new SetupItemCheckBox(_("Enable reorder sprites (need for mods support)."),
        "", "enableReorderSprites", this, "enableReorderSpritesEvent",
        MainConfig_true);


#ifndef USE_SDL2
    // TRANSLATORS: settings option
    new SetupItemLabel(_("Small memory (enable for lower memory usage)"),
         "", this,
        Separator_true);

    // TRANSLATORS: settings option
    new SetupItemCheckBox(_("Disable advanced beings caching (Software)"), "",
        "disableAdvBeingCaching", this, "disableAdvBeingCachingEvent",
        MainConfig_true);

    // TRANSLATORS: settings option
    new SetupItemCheckBox(_("Disable beings caching (Software)"), "",
        "disableBeingCaching", this, "disableBeingCachingEvent",
        MainConfig_true);
#endif  // USE_SDL2


    // TRANSLATORS: settings group
    new SetupItemLabel(_("Different options (enable or disable can "
        "improve performance)"), "", this,
        Separator_true);

#ifdef USE_SDL2
    mSdlDriversList->fillFromVector(sdlDriversList);
    new SetupItemDropDownStr(
        // TRANSLATORS: settings option
        _("Try first sdl driver (only for SDL2 default mode)"),
        "", "sdlDriver", this, "sdlDriverEvent", mSdlDriversList, 100,
        MainConfig_true);
#endif  // USE_SDL2

    mTexturesList->fillFromArray(&texturesList[0], texturesListSize);
    // TRANSLATORS: settings option
    new SetupItemDropDown(_("Enable texture compression (OpenGL)"), "",
        "compresstextures", this, "compresstexturesEvent", mTexturesList, 100,
        MainConfig_true);

    // TRANSLATORS: settings option
    new SetupItemCheckBox(_("Enable rectangular texture extension (OpenGL)"),
        "", "rectangulartextures", this, "rectangulartexturesEvent",
        MainConfig_true);

    // TRANSLATORS: settings option
    new SetupItemCheckBox(_("Use new texture internal format (OpenGL)"),
        "", "newtextures", this, "newtexturesEvent",
        MainConfig_true);

    // TRANSLATORS: settings option
    new SetupItemCheckBox(_("Enable texture atlases (OpenGL)"), "",
        "useAtlases", this, "useAtlasesEvent",
        MainConfig_true);

    // TRANSLATORS: settings option
    new SetupItemCheckBox(_("Cache all sprites per map (can use "
        "additional memory)"), "", "uselonglivesprites", this,
        "uselonglivespritesEvent",
        MainConfig_true);

    // TRANSLATORS: settings option
    new SetupItemCheckBox(_("Cache all sounds (can use additional memory)"),
        "", "uselonglivesounds", this,
        "uselonglivesoundsEvent",
        MainConfig_true);

    // TRANSLATORS: settings group
    new SetupItemLabel(_("Critical options (DO NOT change if you don't "
        "know what you're doing)"), "", this,
        Separator_true);

    // TRANSLATORS: settings option
    new SetupItemCheckBox(_("Disable logging in game (do not enable)"),
        "", "disableLoggingInGame", this, "disableLoggingInGameEvent",
        MainConfig_true);

    setDimension(Rect(0, 0, 550, 350));
}
Esempio n. 27
0
InventoryWindow::InventoryWindow(Inventory *const inventory):
    Window("Inventory", false, nullptr, "inventory.xml"),
    gcn::ActionListener(),
    gcn::KeyListener(),
    gcn::SelectionListener(),
    InventoryListener(),
    mInventory(inventory),
    mItems(new ItemContainer(this, mInventory)),
    mWeight(),
    mSlots(),
    mUseButton(nullptr),
    mDropButton(nullptr),
    mSplitButton(nullptr),
    mOutfitButton(nullptr),
    mShopButton(nullptr),
    mEquipmentButton(nullptr),
    mStoreButton(nullptr),
    mRetrieveButton(nullptr),
    mInvCloseButton(nullptr),
    mWeightBar(nullptr),
    mSlotsBar(new ProgressBar(this, 0.0f, 100, 0, Theme::PROG_INVY_SLOTS)),
    mFilter(nullptr),
    mSortModel(new SortListModelInv),
    mSortDropDown(new DropDown(this, mSortModel, false, false, this, "sort")),
    mNameFilter(new TextField(this, "", true, this, "namefilter", true)),
    mSortDropDownCell(nullptr),
    mNameFilterCell(nullptr),
    mFilterCell(nullptr),
    mSlotsBarCell(nullptr),
    mSplit(false),
    mCompactMode(false)
{
    if (inventory)
    {
        setCaption(gettext(inventory->getName().c_str()));
        setWindowName(inventory->getName());
    }
    else
    {
        // TRANSLATORS: inventory window name
        setCaption(_("Inventory"));
        setWindowName("Inventory");
    }

    listen(CHANNEL_ATTRIBUTES);

    if (setupWindow)
        setupWindow->registerWindowForReset(this);

    setResizable(true);
    setCloseButton(true);
    setSaveVisible(true);
    setStickyButtonLock(true);

    setDefaultSize(387, 307, ImageRect::CENTER);
    setMinWidth(310);
    setMinHeight(179);
    addKeyListener(this);

    mItems->addSelectionListener(this);

    gcn::ScrollArea *const invenScroll = new ScrollArea(
        mItems, getOptionBool("showbackground"), "inventory_background.xml");
    invenScroll->setHorizontalScrollPolicy(gcn::ScrollArea::SHOW_NEVER);

    const int size = config.getIntValue("fontSize");
    mFilter = new TabStrip(this, "filter_" + getWindowName(), size + 16);
    mFilter->addActionListener(this);
    mFilter->setActionEventId("tag_");

    mSortDropDown->setSelected(0);

    StringVect tags = ItemDB::getTags();
    for (unsigned f = 0; f < tags.size(); f ++)
        mFilter->addButton(tags[f]);

    if (isMainInventory())
    {
        // 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 button
        mSplitButton = new Button(this, _("Split"), "split", this);
        // TRANSLATORS: inventory button
        mOutfitButton = new Button(this, _("Outfits"), "outfit", this);
        // TRANSLATORS: inventory button
        mShopButton = new Button(this, _("Shop"), "shop", this);
        // TRANSLATORS: inventory button
        mEquipmentButton = new Button(this, _("Equipment"), "equipment", this);
        mWeightBar = new ProgressBar(this, 0.0f, 100, 0, Theme::PROG_WEIGHT);

        place(0, 0, mWeightBar, 4);
        mSlotsBarCell = &place(4, 0, mSlotsBar, 5);
        mSortDropDownCell = &place(9, 0, mSortDropDown, 2);

        mFilterCell = &place(0, 1, mFilter, 10).setPadding(3);
        mNameFilterCell = &place(9, 1, mNameFilter, 2);

        place(0, 2, invenScroll, 11).setPadding(3);
        place(0, 3, mUseButton);
        place(1, 3, mDropButton);
        place(8, 2, mSplitButton);
        place(8, 3, mShopButton);
        place(9, 3, mOutfitButton);
        place(10, 3, mEquipmentButton);

        updateWeight();
    }
    else
    {
        // 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);
    }

    Layout &layout = getLayout();
    layout.setRowHeight(2, Layout::AUTO_SET);

    mInventory->addInventoyListener(this);

    invInstances.push_back(this);

    if (inventory && inventory->isMainInventory())
    {
        updateDropButton();
    }
    else
    {
        if (!invInstances.empty())
            invInstances.front()->updateDropButton();
    }

    loadWindowState();
    enableVisibleSound(true);
    slotsChanged(mInventory);

    widgetResized(gcn::Event(nullptr));
    if (!isMainInventory())
        setVisible(true);
}