コード例 #1
0
ファイル: dialog_score.cpp プロジェクト: sundoom/sunstudio
// ---------------------------------------------------------------------
// create all the text to go in each text box
// ---------------------------------------------------------------------
void t_score_dialog::create_text()
{
	std::string text;
	t_screen_point        point(0,0);
	t_screen_rect         rect;

//			std::string hero_list = format_hero_list( *m_armies[k_side_attacker] );
//			text = replace_keywords( k_player_surrenders, "%hero_list", hero_list, "%town_name", m_dest_town_name );

	add_text( k_town_title, "town_title", 1, false );
	add_text( k_hero_title, "hero_title", 1, false );
	add_text( k_exploration_title, "exploration_title", 1, false );
	add_text( k_artifacts_title, "artifacts_title", 1, false );
	add_text( k_quests_title, "quests_title", 1, false );
	add_text( k_wealth_title, "wealth_title", 1, false );
	add_text( k_army_size_title, "army_size_title", 1, false );
	add_text( k_battles_won_title, "battles_won_title", 1, false );
	add_text( k_time_title, "time_title", 1, false );
	add_text( k_map_difficulty_title, "map_difficulty_title", 1, false );
	add_text( k_player_difficulty_title, "player_difficulty_title", 1, false );

	//
	// calculate and post all the score values
	//

	t_map_size		map_size = m_map.get_map_size_type();
	t_difficulty	map_difficulty = m_map.get_map_difficulty();
	t_difficulty	player_difficulty = m_map.get_player_difficulty();

	// player difficulty points
	text = format_string( "%s\n%i%%", k_difficulty_text[player_difficulty].c_str(), 
						  m_scores.player_difficulty_percentage );
	add_text( text, "player_difficulty_text", 2, false );

	// map difficulty
	text = format_string( "%s\n%i%%", k_difficulty_text[map_difficulty].c_str(), 
						  m_scores.map_difficulty_percentage );
	add_text( text, "map_difficulty_text", 2, false );

	// time points
	text = format_string( "%s %i\n%i", k_week.c_str(), ( m_map.get_day() / k_days_per_week ) + 1,
						  m_scores.time_points );
	add_text( text, "time_text", 2, false );

	// battles won points
	text = format_string( "%s %i\n%i", k_battles_won.c_str(), m_scores.battles_won, 
						  m_scores.battles_won_points );
	add_text( text, "battles_won_text", 2, false );

	// army size points
	text = format_string( "%s %i\n%i", k_army_value.c_str(), m_scores.total_creature_gold_value,
						  m_scores.army_size_points );
	add_text( text, "army_size_text", 2, false );

	// wealth points
	text = format_string( "%s %i\n%i", k_gold_value.c_str(), m_scores.resource_value, 
						  m_scores.wealth_points );
	add_text( text, "wealth_text", 2, false );

	// quests points
	text = format_string( "%s %i\n%i", k_quests_completed.c_str(), m_scores.quests_completed, 
						  m_scores.quest_points );
	add_text( text, "quests_text", 2, false );

	// artifacts points
	text = format_string( "%s %i\n%i", k_artifacts_collected.c_str(), m_scores.artifacts_collected, 
						  m_scores.artifact_points );
	add_text( text, "artifacts_text", 2, false );

	// exploration points
	int explored = (int)(m_scores.percent_explored * 100);
	text = format_string( "%i %s\n%i", explored, k_explored.c_str(), 
						  m_scores.exploration_points );
	add_text( text, "exploration_text", 2, false );

	// best hero points
	text = format_string( "%s\n%i", m_scores.hero_name.c_str(), m_scores.main_hero_points );
	add_text( text, "hero_text", 2, false );

	// towns owned
	text = format_string( "%s %i\n%i", k_towns_owned.c_str(), m_scores.town_count, m_scores.town_points );
	add_text( text, "town_text", 2, false );

	// total score
	text = format_string( "%s: %i", k_total.c_str(), m_scores.final_score );
	add_text( text, "score", 1, false, false );

	// rank
	m_scores.rank_name = get_creature_name( m_scores.creature_index, 1, false, true );
	text = format_string( "%s: %s", k_rank.c_str(), m_scores.rank_name.c_str() );
	add_text( text, "rank", 1, false, false );

	// player name
	text = format_string( "%s:", k_name.c_str() );
	add_text( text, "name", 1, false, false );

	if( m_map.is_cheater() )
	{
		text = format_string( "%s", k_cheater.c_str() );
		add_text( text, "player", 1, false, false );
	} else
	{
		// create edit box
		t_text_edit_handler handler;

		rect = m_layout->find( "player" )->get_rect();
		// determine row, column where edit box will be placed
		point.x = 0;
		point.y = 0;
		if( text.size() > 0 )
			point.x = m_layout->find( "name" )->get_rect().left + get_font( rect.height() )->get_width( text.c_str() );
		rect.left = point.x;
		m_edit_box = new t_text_edit_window( get_font( rect.height() ), rect, this,
											 m_scores.human_player->get_name(), t_pixel_24(0,0,0) );
		m_edit_box->set_drop_shadow( true, t_pixel_24(200,200,200));
		handler = bound_handler( *this, &t_score_dialog::name_change );
		m_edit_box->set_change_handler( handler );
		handler = bound_handler( *this, &t_score_dialog::name_finished );
		m_edit_box->set_end_edit_handler( handler );
	}
}
コード例 #2
0
ファイル: Forge.cpp プロジェクト: justinabrahms/avendar
void Forge::CompleteWeapon(CHAR_DATA & ch, ForgeContext & context)
{
    // Determine the number of bonus points to spend
    bool forgeMaster(false);
    int bonusPoints(ch.level / 2);
    if (number_percent() <= get_skill(&ch, gsn_forgemaster)) 
    {
        check_improve(&ch, NULL, gsn_forgemaster, true, 4);
        forgeMaster = true; 
        bonusPoints += 10;
    }
    else
        check_improve(&ch, NULL, gsn_forgemaster, false, 4);

    if (ch.in_room != NULL && room_is_affected(ch.in_room, gsn_lavaforge)) bonusPoints += 20;
    if (context.named) bonusPoints += 60;
    bonusPoints -= context.flaws * 20;

    switch (Luck::Check(ch))
    {
        case Luck::Lucky: bonusPoints += 5; break;
        case Luck::Unlucky: bonusPoints -= 5; break;
        default: break;
    }

    bonusPoints = UMAX(0, bonusPoints);

    // Build the special odds ranges from the weapon and base objects
    std::vector<std::pair<unsigned int, const SpecialInfo *> > specials;
    unsigned int nextIndex(0);
    for (SpecialMap::const_iterator iter(Specials().begin()); iter != Specials().end(); ++iter)
    {
        // Make sure there are sufficient points for at least 1 level of this special
        if (bonusPoints < iter->second.cost)
            continue;

        // Calculate odds
        unsigned int oddsRange(CalculateOddsRange(iter->second, context.weaponInfo->weapon, context.materials));
        if (oddsRange == 0)
            continue;
        
        // Add in the range
        specials.push_back(std::make_pair(nextIndex, &iter->second));
        nextIndex += oddsRange;
    }

    // Now choose the special types, up to three
    std::vector<const SpecialInfo *> chosenSpecials;
    if (nextIndex > 0)
    {
        for (size_t i(0); i < 3; ++i)
        {
            // Choose an index at random and find the associated special
            unsigned int index(number_range(0, nextIndex - 1));
            for (size_t j(0); j + 1 < specials.size(); ++j)
            {
                if (specials[j].first <= index && specials[j + 1].first > index)
                {
                    // Found the matching special, now verify that it is acceptable in the face of other chosen ones
                    const SpecialInfo * chosenSpecial(specials[j].second);
                    for (size_t k(0); k < chosenSpecials.size(); ++k)
                    {
                        // No duplicates and no more than one uniqueclass
                        if (chosenSpecials[k] == chosenSpecial || (chosenSpecials[k]->uniqueClass && chosenSpecial->uniqueClass))
                        {
                            chosenSpecial = NULL;
                            break;
                        }
                    }

                    if (chosenSpecial != NULL)
                        chosenSpecials.push_back(chosenSpecial);

                    break;
                }
            }
        }
    }

    // Create the base object
    OBJ_DATA * obj(create_object(get_obj_index(OBJ_VNUM_FORGEWEAPON), 0));
    if (obj == NULL)
    {
        bug("Forge weapon failed due to bad obj creation", 0);
        send_to_char("An error has occurred, please contact the gods.\n", &ch);
        return;
    }

    // Fill out the basic info; use the first material as the object's material
    obj->level = ch.level;
    obj->weight = number_range(context.weaponInfo->minWeight, (context.weaponInfo->minWeight * 23) / 20);
    obj->weight = UMIN(obj->weight, context.weight);
    obj->size = context.weaponInfo->objSize;
    obj->cost = ((bonusPoints * bonusPoints) / 2) + number_range(0, 300);
    if (!context.materials.empty()) obj->material = context.materials[0];
    if (!context.weaponInfo->damverbs.empty()) 
        copy_string(obj->obj_str, context.weaponInfo->damverbs[number_range(0, context.weaponInfo->damverbs.size() - 1)].c_str());

    obj->value[0] = context.weaponInfo->type;
    obj->value[1] = 10 + (ch.level / 10) + context.weaponInfo->dammod + (context.named ? 1 : 0);
    obj->value[2] = 2;
    obj->value[3] = context.weaponInfo->damtype;
    if (context.weaponInfo->twohanded) SET_BIT(obj->value[4], WEAPON_TWO_HANDS);

    // Now choose from the selected specials at random until out of points or possible specials
    while (bonusPoints > 0 && !chosenSpecials.empty())
    {
        // Choose a special and add it in
        size_t index(number_range(0, chosenSpecials.size() - 1));
        chosenSpecials[index]->callback(*obj);
        bonusPoints -= UMAX(1, chosenSpecials[index]->cost);

        // Remove the special if too costly for the remaining points or only one allowed
        if (bonusPoints < chosenSpecials[index]->cost || !chosenSpecials[index]->multipleAllowed)
        {
            chosenSpecials[index] = chosenSpecials[chosenSpecials.size() - 1];
            chosenSpecials.pop_back();
        }
    }

    // Compensate for bad luck with increased damage
    if (context.named && bonusPoints >= 10)
        ++obj->value[1];

    // Choose an adjective from the set of common adjectives plus the weapon-specific adjectives
    WordList adjectives(Adjectives());
    for (size_t i(0); i < context.weaponInfo->adjectives.size(); ++i)
        adjectives.push_back(context.weaponInfo->adjectives[i]);

    std::string adjective;
    if (!adjectives.empty()) 
        adjective = adjectives[number_range(0, adjectives.size() - 1)];

    // Break down the material set to only unique materials
    std::set<int> materials;
    for (size_t i(0); i < context.materials.size(); ++i)
        materials.insert(context.materials[i]);

    std::string materialAdjective;
    switch (materials.size())
    {
        case 0: break;
        case 1: materialAdjective = material_table[context.materials[0]].name; break;
        case 2: 
        {
            std::set<int>::iterator iter(materials.begin());
            materialAdjective = material_table[*iter].name;
            materialAdjective += '-';
            ++iter;
            materialAdjective += material_table[*iter].name;
            break;
        }
        default:
            materialAdjective = material_table[context.materials[0]].name;
            materialAdjective += "-alloyed";
            break;
    }

    // Build the short desc
    std::ostringstream shortDesc;
    if (!adjective.empty()) shortDesc << adjective << ' ';
    if (!materialAdjective.empty()) shortDesc << materialAdjective << ' ';
    shortDesc << context.weaponInfo->name;

    std::string weaponShort(shortDesc.str());
    if (!weaponShort.empty())
        weaponShort = std::string(indefiniteArticleFor(weaponShort[0])) + ' ' + weaponShort;

    SetBasicDescs(*obj, weaponShort.c_str(), false);

    // Set up the exdesc
    std::ostringstream exdesc;
    switch (number_range(0, 2))
    {
        case 0: exdesc << "Forged"; break;
        case 1: exdesc << "Formed"; break;
        default: exdesc << "Wrought"; break;
    }
    exdesc << " from ";

    switch (materials.size())
    {
        case 0: exdesc << " pure metal"; break;
        case 1: exdesc << " pure " << material_table[context.materials[0]].name; break;
        case 2:
        {
            std::set<int>::iterator iter(materials.begin());
            exdesc << "an alloy of " << material_table[*iter].name << " and ";
            ++iter;
            exdesc << material_table[*iter].name;
            break;
        }
        default: exdesc << " a metal alloy"; break;
    }
    exdesc << ", this ";
    if (!adjective.empty()) exdesc << adjective << ' ';
    exdesc << context.weaponInfo->name;

    if (IS_OBJ_STAT(obj, ITEM_GLOW)) exdesc << " gleams brightly.";
    else if (IS_OBJ_STAT(obj, ITEM_DARK)) exdesc << " seems to drink the light into its dark surface.";
    else if (IS_OBJ_STAT(obj, ITEM_HUM)) exdesc << " hums faintly.";
    else if (IS_OBJ_STAT(obj, ITEM_NODESTROY)) exdesc << " seems nearly indestructible.";
    else if (context.named) exdesc << " radiates an aura of power.";
    else if (forgeMaster) exdesc << " has been masterfully crafted.";
    else exdesc << " has been well-crafted.";

    exdesc << ' ';
    switch (number_range(0, 5))
    {
        case 0: exdesc << "The bands of metal which comprise it have been folded over and over to toughen the final product."; break;
        case 1: exdesc << "Bands of metal flash-forged together serve to harden the weapon against wear."; break;
        case 2: exdesc << "Carved into the weapon's length are small straight-lined runes, etched with obvious care."; break;
        case 3: exdesc << "Folds of the metal have been beaten into the weapon's surface, reinforcing the craftsmanship."; break;
        case 4: exdesc << "Ornate filigree runs the length of the weapon, decorating it in gleaming metal."; break;
        default: exdesc << "The lines of the weapon are simple and unadorned, lending it a certain grim elegance."; break;
    }

    if (!context.weaponInfo->sentences.empty() && number_bits(1) == 0)
        exdesc << ' ' << context.weaponInfo->sentences[number_range(0, context.weaponInfo->sentences.size() - 1)];

    if (TraitCount(*obj, Trait_Parry) > 0)
        exdesc << " Forged with unusual precision, the balance of this piece lends itself well to parrying blows.";

    if (TraitCount(*obj, Trait_Casting) > 0)
        exdesc << " A sense of focus permeates this piece, as though it has been well-prepared for the channeling of mystical energies.";

    switch (context.flaws)
    {
        case 0: 
            switch (number_range(0, 3))
            {
                case 0: exdesc << " The work is flawless, bearing no sign of weakness."; break;
                case 1: exdesc << " Clearly well-fashioned, this " << context.weaponInfo->name << " has been made to stand the test of time."; break;
                case 2: exdesc << " No trace of imperfection mars the surface of this beautiful " << context.weaponInfo->name << '.'; break;
                default: exdesc << " There is no sign of seam or solder, as though the weapon was cast as a single, perfect unit."; break;
            }
            break;

        case 1:
            switch (number_range(0, 2))
            {
                case 0: exdesc << " A few minor imperfections mar the otherwise smooth surface of the " << context.weaponInfo->name << '.'; break;
                case 1: exdesc << " Though not immediately-visible, a couple of minor flaws are evident upon closer inspection."; break;
                default: exdesc << " Some dents remain from the original crafting, slightly weakening the metalwork."; break;
            }
            break;

        default:
            switch (number_range(0, 2))
            {
                case 0: exdesc << " Significant flaws are evident along the " << context.weaponInfo->name << "'s length."; break;
                default: exdesc << " Several seams show clearly on the weapon's surface, evidence of clumsy forgework."; break;
            }
            break;
    }

    // Apply the desc
    exdesc << '\n';
    EXTRA_DESCR_DATA * extraDesc(new_extra_descr());
    copy_string(extraDesc->keyword, obj->name);
    copy_string(extraDesc->description, exdesc.str().c_str());
    extraDesc->description = format_string(extraDesc->description);
    extraDesc->next     = obj->extra_descr;
    obj->extra_descr    = extraDesc;

    // Give the object to the char
    obj_to_char(obj, &ch);

    // Echoes (and charge max mana for the naming, if present)
    act("You quench the metalwork, now shaped into $p.", &ch, obj, NULL, TO_CHAR);
    act("$n quenches the metalwork, now shaped into $p.", &ch, obj, NULL, TO_ROOM);
    if (context.named)
    {
        act("You can feel the air about it charged with power drained from your very being, as the newly-forged weapon lies waiting to receive its true Name.", &ch, obj, NULL, TO_CHAR);
        ch.max_mana = UMAX(0, ch.max_mana - NamingManaCost);
        if (!IS_NPC(&ch))
            ch.pcdata->perm_mana = UMAX(0, ch.pcdata->perm_mana - NamingManaCost);

        ch.mana = UMIN(ch.mana, ch.max_mana);

        // Add an effect to the char to indicate he can name the object
        AFFECT_DATA af = {0};
        af.where    = TO_AFFECTS;
        af.type     = gsn_forgeweapon;
        af.location = APPLY_HIDE;
        af.duration = -1;
        af.point    = obj;
        af.level    = ch.level;
        affect_to_char(&ch, &af);
    }
}
コード例 #3
0
ファイル: sprintf.c プロジェクト: BruceYi/okl4
int
vsprintf(char *s, const char *format, va_list arg)
{
    return format_string(s, NULL, 0, -1, format, arg);
}
コード例 #4
0
ファイル: text_input.c プロジェクト: 1337Noob1337/OpenRCT2
void window_text_input_open(rct_window* call_w, int call_widget, rct_string_id title, rct_string_id description, rct_string_id existing_text, uint32 existing_args, int maxLength)
{
	_maxInputLength = maxLength;

	window_close_by_class(WC_TEXTINPUT);

	// Clear the text input buffer
	memset(text_input, 0, maxLength);

	// Enter in the the text input buffer any existing
	// text.
	if (existing_text != STR_NONE)
		format_string(text_input, existing_text, &existing_args);

	// In order to prevent strings that exceed the maxLength
	// from crashing the game.
	text_input[maxLength - 1] = '\0';

	utf8_remove_format_codes(text_input, false);

	// This is the text displayed above the input box
	input_text_description = description;

	// Work out the existing size of the window
	char wrapped_string[512];
	safe_strcpy(wrapped_string, text_input, 512);

	int no_lines = 0, font_height = 0;

	// String length needs to add 12 either side of box
	// +13 for cursor when max length.
	gfx_wrap_string(wrapped_string, WW - (24 + 13), &no_lines, &font_height);

	int height = no_lines * 10 + WH;

	// Window will be in the center of the screen
	rct_window* w = window_create_centred(
		WW,
		height,
		&window_text_input_events,
		WC_TEXTINPUT,
		WF_STICK_TO_FRONT
	);

	w->widgets = window_text_input_widgets;
	w->enabled_widgets = (1 << WIDX_CLOSE) | (1<<WIDX_CANCEL) | (1<<WIDX_OKAY);

	window_text_input_widgets[WIDX_TITLE].image = title;

	// Save calling window details so that the information
	// can be passed back to the correct window & widget
	calling_class = call_w->classification;
	calling_number = call_w->number;
	calling_widget = call_widget;

	platform_start_text_input(text_input, maxLength);

	window_init_scroll_widgets(w);
	w->colours[0] = call_w->colours[0];
	w->colours[1] = call_w->colours[1];
	w->colours[2] = call_w->colours[2];
}
コード例 #5
0
ファイル: expand.cpp プロジェクト: frogshead/fish-shell
static int find_process(const wchar_t *proc,
                        expand_flags_t flags,
                        std::vector<completion_t> &out)
{
    int found = 0;

    if (!(flags & EXPAND_SKIP_JOBS))
    {
        ASSERT_IS_MAIN_THREAD();
        const job_t *j;

        if (iswnumeric(proc) || (wcslen(proc)==0))
        {
            /*
              This is a numeric job string, like '%2'
            */

            if (flags & ACCEPT_INCOMPLETE)
            {
                job_iterator_t jobs;
                while ((j = jobs.next()))
                {
                    wchar_t jid[16];
                    if (j->command_is_empty())
                        continue;

                    swprintf(jid, 16, L"%d", j->job_id);

                    if (wcsncmp(proc, jid, wcslen(proc))==0)
                    {
                        wcstring desc_buff = format_string(COMPLETE_JOB_DESC_VAL, j->command_wcstr());
                        append_completion(out,
                                          jid+wcslen(proc),
                                          desc_buff,
                                          0);
                    }
                }

            }
            else
            {

                int jid;
                wchar_t *end;

                errno = 0;
                jid = fish_wcstoi(proc, &end, 10);
                if (jid > 0 && !errno && !*end)
                {
                    j = job_get(jid);
                    if ((j != 0) && (j->command_wcstr() != 0))
                    {
                        {
                            append_completion(out, to_string<long>(j->pgid));
                            found = 1;
                        }
                    }
                }
            }
        }
        if (found)
            return 1;

        job_iterator_t jobs;
        while ((j = jobs.next()))
        {

            if (j->command_is_empty())
                continue;

            size_t offset;
            if (match_pid(j->command(), proc, flags, &offset))
            {
                if (flags & ACCEPT_INCOMPLETE)
                {
                    append_completion(out,
                                      j->command_wcstr() + offset + wcslen(proc),
                                      COMPLETE_JOB_DESC,
                                      0);
                }
                else
                {
                    append_completion(out, to_string<long>(j->pgid));
                    found = 1;
                }
            }
        }

        if (found)
        {
            return 1;
        }

        jobs.reset();
        while ((j = jobs.next()))
        {
            process_t *p;
            if (j->command_is_empty())
                continue;
            for (p=j->first_process; p; p=p->next)
            {
                if (p->actual_cmd.empty())
                    continue;

                size_t offset;
                if (match_pid(p->actual_cmd, proc, flags, &offset))
                {
                    if (flags & ACCEPT_INCOMPLETE)
                    {
                        append_completion(out,
                                          wcstring(p->actual_cmd, offset + wcslen(proc)),
                                          COMPLETE_CHILD_PROCESS_DESC,
                                          0);
                    }
                    else
                    {
                        append_completion(out,
                                          to_string<long>(p->pid),
                                          L"",
                                          0);
                        found = 1;
                    }
                }
            }
        }

        if (found)
        {
            return 1;
        }
    }

    /* Iterate over all processes */
    wcstring process_name;
    pid_t process_pid;
    process_iterator_t iterator;
    while (iterator.next_process(&process_name, &process_pid))
    {
        size_t offset;
        if (match_pid(process_name, proc, flags, &offset))
        {
            if (flags & ACCEPT_INCOMPLETE)
            {
                append_completion(out,
                                  process_name.c_str() + offset + wcslen(proc),
                                  COMPLETE_PROCESS_DESC,
                                  0);
            }
            else
            {
                append_completion(out, to_string<long>(process_pid));
            }
        }
    }

    return 1;
}
コード例 #6
0
ファイル: fish_pager.cpp プロジェクト: anbotero/fish-shell
static int completion_try_print( int cols,
				 wchar_t *prefix,
				 int is_quoted,
				 std::vector<comp_t *> &lst )
{
	/*
	  The calculated preferred width of each column
	*/
	int pref_width[PAGER_MAX_COLS];
	/*
	  The calculated minimum width of each column
	*/
	int min_width[PAGER_MAX_COLS];
	/*
	  If the list can be printed with this width, width will contain the width of each column
	*/
	int *width=pref_width;
	/*
	  Set to one if the list should be printed at this width
	*/
	int print=0;
	
	long i, j;
	
	int rows = (int)((lst.size()-1)/cols+1);
	
	int pref_tot_width=0;
	int min_tot_width = 0;
	int res=PAGER_RETRY;
	/*
	  Skip completions on tiny terminals
	*/
	
	if( termsize.ws_col < PAGER_MIN_WIDTH )
		return PAGER_DONE;
	
	memset( pref_width, 0, sizeof(pref_width) );
	memset( min_width, 0, sizeof(min_width) );
	
	/* Calculate how wide the list would be */
	for( j = 0; j < cols; j++ )
	{
		for( i = 0; i<rows; i++ )
		{
			int pref,min;
			comp_t *c;
			if( lst.size() <= j*rows + i )
				continue;

			c = lst.at(j*rows + i );
			pref = c->pref_width;
			min = c->min_width;
			
			if( j != cols-1 )
			{
				pref += 2;
				min += 2;
			}
			min_width[j] = maxi( min_width[j],
					     min );
			pref_width[j] = maxi( pref_width[j],
					      pref );
		}
		min_tot_width += min_width[j];
		pref_tot_width += pref_width[j];
	}
	/*
	  Force fit if one column
	*/
	if( cols == 1)
	{
		if( pref_tot_width > termsize.ws_col )
		{
			pref_width[0] = termsize.ws_col;
		}
		width = pref_width;
		print=1;
	}
	else if( pref_tot_width <= termsize.ws_col )
	{
		/* Terminal is wide enough. Print the list! */
		width = pref_width;
		print=1;
	}
	else
	{
		long next_rows = (lst.size()-1)/(cols-1)+1;
/*		fwprintf( stderr,
  L"cols %d, min_tot %d, term %d, rows=%d, nextrows %d, termrows %d, diff %d\n",
  cols,
  min_tot_width, termsize.ws_col,
  rows, next_rows, termsize.ws_row,
  pref_tot_width-termsize.ws_col );
*/
		if( min_tot_width < termsize.ws_col &&
		    ( ( (rows < termsize.ws_row) && (next_rows >= termsize.ws_row ) ) ||
		      ( pref_tot_width-termsize.ws_col< 4 && cols < 3 ) ) )
		{
			/*
			  Terminal almost wide enough, or squeezing makes the
			  whole list fit on-screen.

			  This part of the code is really important. People hate
			  having to scroll through the completion list. In cases
			  where there are a huge number of completions, it can't
			  be helped, but it is not uncommon for the completions to
			  _almost_ fit on one screen. In those cases, it is almost
			  always desirable to 'squeeze' the completions into a
			  single page. 

			  If we are using N columns and can get everything to
			  fit using squeezing, but everything would also fit
			  using N-1 columns, don't try.
			*/

			int tot_width = min_tot_width;
			width = min_width;

			while( tot_width < termsize.ws_col )
			{
				for( i=0; (i<cols) && ( tot_width < termsize.ws_col ); i++ )
				{
					if( width[i] < pref_width[i] )
					{
						width[i]++;
						tot_width++;
					}
				}
			}
			print=1;
		}
	}

	if( print )
	{
		res=PAGER_DONE;
		if( rows < termsize.ws_row )
		{
			/* List fits on screen. Print it and leave */
			if( is_ca_mode )
			{
				is_ca_mode = 0;
				writembs(exit_ca_mode);
			}
			
			completion_print( cols, width, 0, rows, prefix, is_quoted, lst);
			pager_flush();
		}
		else
		{
			int npos, pos = 0;
			int do_loop = 1;

			/*
			  Enter ca_mode, which means that the terminal
			  content will be restored to the current
			  state on exit.
			*/
			if( enter_ca_mode && exit_ca_mode )
			{
				is_ca_mode=1;
				writembs(enter_ca_mode);
			}
			

			completion_print( cols,
					  width,
					  0,
					  termsize.ws_row-1,
					  prefix,
					  is_quoted,
					  lst);
			/*
			  List does not fit on screen. Print one screenfull and
			  leave a scrollable interface
			*/
			while(do_loop)
			{
				set_color( rgb_color_t::black(), get_color(HIGHLIGHT_PAGER_PROGRESS) );
                wcstring msg = format_string(_(L" %d to %d of %d"), pos, pos+termsize.ws_row-1, rows );
				msg.append(L"   \r" );
								
				writestr(msg.c_str());
				set_color( rgb_color_t::normal(), rgb_color_t::normal() );
				pager_flush();
				int c = readch();

				switch( c )
				{
					case LINE_UP:
					{
						if( pos > 0 )
						{
							pos--;
							writembs(tparm( cursor_address, 0, 0));
							writembs(scroll_reverse);
							completion_print( cols,
									  width,
									  pos,
									  pos+1,
									  prefix,
									  is_quoted,
									  lst );
							writembs( tparm( cursor_address,
									 termsize.ws_row-1, 0) );
							writembs(clr_eol );

						}

						break;
					}

					case LINE_DOWN:
					{
						if( pos <= (rows - termsize.ws_row ) )
						{
							pos++;
							completion_print( cols,
									  width,
									  pos+termsize.ws_row-2,
									  pos+termsize.ws_row-1,
									  prefix,
									  is_quoted,
									  lst );
						}
						break;
					}

					case PAGE_DOWN:
					{

						npos = mini( (int)(rows - termsize.ws_row+1), (int)(pos + termsize.ws_row-1) );
						if( npos != pos )
						{
							pos = npos;
							completion_print( cols,
									  width,
									  pos,
									  pos+termsize.ws_row-1,
									  prefix,
									  is_quoted,
									  lst );
						}
						else
						{
							if( flash_screen )
								writembs( flash_screen );
						}

						break;
					}

					case PAGE_UP:
					{
						npos = maxi( 0,
							     pos - termsize.ws_row+1 );

						if( npos != pos )
						{
							pos = npos;
							completion_print( cols,
									  width,
									  pos,
									  pos+termsize.ws_row-1,
									  prefix,
									  is_quoted,
									  lst );
						}
						else
						{
							if( flash_screen )
								writembs( flash_screen );
						}
						break;
					}

					case R_NULL:
					{
						do_loop=0;
						res=PAGER_RESIZE;
						break;
						
					}
					
					default:
					{
						out_buff.push_back( c );
						do_loop = 0;
						break;
					}					
				}
			}
			writembs(clr_eol);
		}
	}
	return res;
}
コード例 #7
0
ファイル: combat_ai.cpp プロジェクト: sundoom/sunstudio
// -----------------------------------------------------
// determine if AI should retreat
// -----------------------------------------------------
bool ai_check_retreat( t_battlefield& battlefield )
{
	bool side = battlefield.get_acting_side();

	if (battlefield.get_retreat_checked( side ))
		return false;
	if (!should_retreat( battlefield, side ))
		return false;
	battlefield.set_retreat_checked( side );

	t_player*			player = battlefield.get_player( side );
	t_combat_window*	combat_window = battlefield.get_combat_window();

	if (!player->is_computer())
		return suggest_retreat( battlefield, side );

	if (battlefield.can_surrender( side ))
	{
		int			cost = battlefield.calculate_surrender_cost( side );
		std::string	cost_text = format_string( "%i", cost );
		std::string	text;
		bool		enemy_towns;
		bool		blocked_towns;
		t_town*		town = combat_window->find_nearest_town( side, enemy_towns, blocked_towns );
		t_hero const*	enemy_hero;
		t_hero const*	hero;
		t_skill			skill;
		t_skill			enemy_skill;
		t_hero_keyword_replacer replacer;

		hero = get_charm( battlefield, side, skill );
		enemy_hero = get_charm( battlefield, !side, enemy_skill );
		replacer.add_keyword( "%surrender_cost", cost_text );
		replacer.add_keyword( "%town_name", town->get_name() );

		if (enemy_skill.level < skill.level)
		{
			replacer.add_hero( hero );
			replacer.add_skill( skill );
			text = replacer( k_text_force_surrender );
			ok_dialog( text );
			battlefield.surrender();
			return true;
		}

		text = replacer( k_text_request_surrender );
		if (yes_no_dialog( text, true ))
		{
			battlefield.surrender();
			return true;
		}
	}

	if (!battlefield.can_retreat( side ))
		return false;
	if (side)
		combat_window->force_combat_termination(k_result_defender_retreated);
	else
		combat_window->force_combat_termination(k_result_attacker_retreated);
	return true;
}
コード例 #8
0
/*
    Conditions:
      22
    Exit points:
      0
    M = 22 - 0 + 2 = 25
    Cyclomatic complexity
      25
  */
void fp_test(void)
{
  uint32_t retCode = 0;
  GUI_Button_t  fp_start,
                fp_refresh,
                fp_close,
                fp_continue;
  TS_StateTypeDef ts;
  uint32_t action = 0, id = 0;

  gui_button_init(&fp_start);
  fp_start.XPosition   = 20;
  fp_start.YPosition   = 50;
  fp_start.Height      = 50;
  fp_start.Width       = 200;
  fp_start.BorderWidth = 2;
  fp_start.BorderColor = LCD_COLOR_BLACK;
  fp_start.FillColor   = LCD_COLOR_WHITE;
  fp_start.TextColor   = LCD_COLOR_BLACK;
  fp_start.Text = (uint8_t*)"Start";

  gui_button_init(&fp_refresh);
  fp_refresh.XPosition   = 20;
  fp_refresh.YPosition   = 125;
  fp_refresh.Height      = 50;
  fp_refresh.Width       = 200;
  fp_refresh.BorderWidth = 2;
  fp_refresh.BorderColor = LCD_COLOR_BLACK;
  fp_refresh.FillColor   = LCD_COLOR_WHITE;
  fp_refresh.TextColor   = LCD_COLOR_BLACK;
  fp_refresh.Text = (uint8_t*)"Refresh";

  gui_button_init(&fp_close);
  fp_close.XPosition   = 20;
  fp_close.YPosition   = 200;
  fp_close.Height      = 50;
  fp_close.Width       = 200;
  fp_close.BorderWidth = 2;
  fp_close.BorderColor = LCD_COLOR_BLACK;
  fp_close.FillColor   = LCD_COLOR_WHITE;
  fp_close.TextColor   = LCD_COLOR_BLACK;
  fp_close.Text = (uint8_t*)"Close";

  gui_button_init(&fp_continue);
  fp_continue.XPosition   = 20;
  fp_continue.YPosition   = 250;
  fp_continue.Height      = 50;
  fp_continue.Width       = 200;
  fp_continue.BorderWidth = 2;
  fp_continue.BorderColor = LCD_COLOR_BLACK;
  fp_continue.FillColor   = LCD_COLOR_WHITE;
  fp_continue.TextColor   = LCD_COLOR_BLACK;
  fp_continue.Text = (uint8_t*)"Continue";

  while (1)
  {
    BSP_LCD_Clear(LCD_COLOR_WHITE);

    gui_button_draw(&fp_start);
    gui_button_draw(&fp_refresh);
    gui_button_draw(&fp_close);

    action = 0;

    while (action == 0)
    {
      BSP_TS_GetState(&ts);

      if (gui_button_check_touch(&fp_start, &ts) == GUI_Button_Error_Yes)
      {
        action = 1;
      }
      else if (gui_button_check_touch(&fp_refresh, &ts) == GUI_Button_Error_Yes)
      {
        action = 2;
      }
      else if (gui_button_check_touch(&fp_close, &ts) == GUI_Button_Error_Yes)
      {
        action = 3;
      }
      else
      {
        vTaskDelay(5);
      }
    }

    switch (action)
    {
      case 1:
        id = fp_session_start();
        BSP_LCD_Clear(LCD_COLOR_WHITE);
        BSP_LCD_DisplayStringAtLine(1, (uint8_t*)"Session start");
        if (id < 20)
          BSP_LCD_DisplayStringAtLine(2, format_string("ID: %d", id));
        else
          BSP_LCD_DisplayStringAtLine(2, format_string("Error code: %x", id));

        gui_button_draw(&fp_continue);

        while (1)
        {
          BSP_TS_GetState(&ts);

          if (gui_button_check_touch(&fp_continue, &ts) == GUI_Button_Error_Yes)
            break;

          vTaskDelay(5);
        }
        break;

      case 2:
        retCode = fp_session_refresh(id);
        BSP_LCD_Clear(LCD_COLOR_WHITE);
        BSP_LCD_DisplayStringAtLine(1, (uint8_t*)"Session refresh");
        if (retCode < 20)
          BSP_LCD_DisplayStringAtLine(2, format_string("ID: %d", id));
        else
          BSP_LCD_DisplayStringAtLine(2, format_string("Error code: %x", retCode));

        gui_button_draw(&fp_continue);

        while (1)
        {
          BSP_TS_GetState(&ts);

          if (gui_button_check_touch(&fp_continue, &ts) == GUI_Button_Error_Yes)
            break;

          vTaskDelay(5);
        }
        break;

      case 3:
        retCode = fp_session_close(id);
        BSP_LCD_Clear(LCD_COLOR_WHITE);
        BSP_LCD_DisplayStringAtLine(1, (uint8_t*)"Session close");
        if (retCode < 20)
          BSP_LCD_DisplayStringAtLine(2, format_string("ID: %d", id));
        else
          BSP_LCD_DisplayStringAtLine(2, format_string("Error code: %x", retCode));

        gui_button_draw(&fp_continue);

        while (1)
        {
          BSP_TS_GetState(&ts);

          if (gui_button_check_touch(&fp_continue, &ts) == GUI_Button_Error_Yes)
            break;

          vTaskDelay(5);
        }
        break;

      default:
        id = fp_error_session_not_started;
        break;
    }
  }
}
コード例 #9
0
bool
RPG_Net_Server_Common_Tools::getNextLogFilename (const std::string& directory_in,
                                                 std::string& FQLogFilename_out)
{
  RPG_TRACE (ACE_TEXT ("RPG_Net_Server_Common_Tools::getNextLogFilename"));

  // initialize return value(s)
  FQLogFilename_out.resize (0);

  // sanity check(s): log directory exists ?
  // No ? --> try to create it then !
  if (!Common_File_Tools::isDirectory (directory_in))
  {
    if (!Common_File_Tools::createDirectory (directory_in))
    {
      ACE_DEBUG ((LM_ERROR,
                  ACE_TEXT ("failed to Common_File_Tools::createDirectory(\"%s\"), aborting\n"),
                  ACE_TEXT (directory_in.c_str ())));
      return false;
    } // end IF
    ACE_DEBUG ((LM_DEBUG,
               ACE_TEXT ("created directory: \"%s\"...\n"),
               ACE_TEXT (directory_in.c_str ())));
  } // end IF

  // construct correct logfilename...
  FQLogFilename_out = directory_in;
  FQLogFilename_out += ACE_DIRECTORY_SEPARATOR_CHAR_A;
  std::string logFileName = ACE_TEXT_ALWAYS_CHAR (RPG_NET_SERVER_LOG_FILENAME_PREFIX);
  logFileName += ACE_TEXT_ALWAYS_CHAR (COMMON_LOG_FILENAME_SUFFIX);
  FQLogFilename_out += logFileName;

  // retrieve all existing logs and sort them alphabetically...
  ACE_Dirent_Selector entries;
  int result = entries.open (directory_in.c_str (),
                             &RPG_Net_Server_Common_Tools::selector,
                             &RPG_Net_Server_Common_Tools::comparator);
  if (result == -1)
  {
    ACE_DEBUG ((LM_ERROR,
                ACE_TEXT ("failed to ACE_Dirent_Selector::open(\"%s\"): \"%s\", aborting\n"),
                ACE_TEXT (directory_in.c_str ()),
                ACE_TEXT (ACE_OS::strerror (ACE_OS::last_error()))));
    return false;
  } // end IF

//   ACE_DEBUG ((LM_DEBUG,
//               ACE_TEXT ("found %d logfiles...\n"),
//               entries.length ()));

  // OK: iterate over the entries and perform some magic...
  // *NOTE*: entries have been sorted alphabetically:
  //         1 current 2 4 3 --> current 1 2 3 4
  // *TODO*: some malicious user could inject "fake" logfiles which can
  //         "confuse" this algorithm...
  // skip handling of "<PREFIX><SUFFIX>" (if found)...
  // *NOTE*: <PREFIX><SUFFIX> will become <PREFIX>_1<SUFFIX>...
  bool found_current = false;
  // sscanf settings
  int number = 0;
  int return_val = -1;
  std::string format_string ("%d");
  format_string += ACE_TEXT_ALWAYS_CHAR (COMMON_LOG_FILENAME_SUFFIX);
  std::stringstream converter;
  for (int i = entries.length () - 1, index = RPG_Net_Server_Common_Tools::maxNumberOfLogFiles_ - 1;
       i >= 0;
       i--)
  {
    // perform "special treatment" if "<PREFIX><SUFFIX>" found...
    // *TODO*: do this in C++...
    if (ACE_OS::strcmp (entries[i]->d_name,
                        logFileName.c_str ()) == 0)
    {
      found_current = true;

      // skip this one for now
      continue;
    } // end IF

    // scan number...
    try
    {
      // *TODO*: do this in C++...
      return_val = ::sscanf (entries[i]->d_name +
                             // skip some characters...
                             (ACE_OS::strlen (ACE_TEXT_ALWAYS_CHAR (RPG_NET_SERVER_LOG_FILENAME_PREFIX)) + 1),
                             format_string.c_str (),
                             &number);
      if (return_val != 1)
      {
        if (return_val != 0)
        {
          ACE_DEBUG ((LM_ERROR,
                      ACE_TEXT ("::sscanf() failed for \"%s\": \"%s\", continuing\n"),
                      entries[i]->d_name,
                      ACE_TEXT (ACE_OS::strerror (ACE_OS::last_error ()))));
        } // end IF

        continue;
      } // end IF
    }
    catch (...)
    {
      ACE_DEBUG ((LM_ERROR,
                  ACE_TEXT ("caught exception in ::sscanf() for \"%s\": \"%s\", continuing\n"),
                  entries[i]->d_name,
                  ACE_TEXT (ACE_OS::strerror (ACE_OS::last_error ()))));

      continue;
    }

    // adjust the index, if the number is smaller than max
    if (number < index)
      index = number + 1;

    // if the number is bigger than the max AND we have more than enough logs --> delete it !
    if ((static_cast<unsigned long> (number) >= (RPG_Net_Server_Common_Tools::maxNumberOfLogFiles_ - 1)) &&
        (static_cast<unsigned long> (entries.length()) >= RPG_Net_Server_Common_Tools::maxNumberOfLogFiles_))
    {
      ACE_DEBUG ((LM_DEBUG,
                  ACE_TEXT ("removing surplus logfile \"%s\"...\n"),
                  entries[i]->d_name));

      // clean up
      std::string FQfilename = directory_in;
      FQfilename += ACE_DIRECTORY_SEPARATOR_CHAR_A;
      FQfilename += entries[i]->d_name;
      Common_File_Tools::deleteFile (FQfilename);

      continue;
    } // end IF

    // logrotate file...
    std::string oldFQfilename = directory_in;
    oldFQfilename += ACE_DIRECTORY_SEPARATOR_CHAR_A;
    oldFQfilename += entries[i]->d_name;

    std::string newFQfilename = directory_in;
    newFQfilename += ACE_DIRECTORY_SEPARATOR_CHAR_A;
    newFQfilename += ACE_TEXT_ALWAYS_CHAR (RPG_NET_SERVER_LOG_FILENAME_PREFIX);
    newFQfilename += ACE_TEXT_ALWAYS_CHAR ("_");

    converter.clear ();
    converter.str (ACE_TEXT_ALWAYS_CHAR (""));
    converter << index;

    newFQfilename += converter.str ();
    newFQfilename += ACE_TEXT_ALWAYS_CHAR (COMMON_LOG_FILENAME_SUFFIX);
    // *IMPORTANT NOTE*: last parameter affects Win32 behaviour only,
    // see "ace/OS_NS_stdio.inl" !
    if (ACE_OS::rename (oldFQfilename.c_str (),
                        newFQfilename.c_str (),
                        -1))
    {
      ACE_DEBUG ((LM_ERROR,
                  ACE_TEXT ("failed to ACE_OS::rename() \"%s\" to \"%s\": \"%s\", aborting\n"),
                  ACE_TEXT (oldFQfilename.c_str ()),
                  ACE_TEXT (newFQfilename.c_str ()),
                  ACE_TEXT (ACE_OS::strerror (ACE_OS::last_error ()))));
      return false;
    } // end IF
    ACE_DEBUG ((LM_DEBUG,
                ACE_TEXT ("renamed file \"%s\" to \"%s\"...\n"),
                ACE_TEXT (oldFQfilename.c_str ()),
                ACE_TEXT (newFQfilename.c_str ())));

    index--;
  } // end FOR

  if (found_current)
  {
    std::string newFQfilename = directory_in;
    newFQfilename += ACE_DIRECTORY_SEPARATOR_CHAR_A;
    newFQfilename += ACE_TEXT_ALWAYS_CHAR (RPG_NET_SERVER_LOG_FILENAME_PREFIX);
    newFQfilename += ACE_TEXT_ALWAYS_CHAR ("_1");
    newFQfilename += ACE_TEXT_ALWAYS_CHAR (COMMON_LOG_FILENAME_SUFFIX);

    // *TODO*: last parameter affects Win32 behaviour only, see "ace/OS_NS_stdio.inl" !
    if (ACE_OS::rename (FQLogFilename_out.c_str (),
                        newFQfilename.c_str (),
                        -1))
    {
      ACE_DEBUG ((LM_ERROR,
                  ACE_TEXT ("failed to ACE_OS::rename() \"%s\" to \"%s\": \"%m\", aborting\n"),
                  ACE_TEXT (FQLogFilename_out.c_str ()),
                  ACE_TEXT (newFQfilename.c_str ())));
      return false;
    } // end IF
    ACE_DEBUG ((LM_DEBUG,
                ACE_TEXT ("renamed file \"%s\" to \"%s\"...\n"),
                ACE_TEXT (FQLogFilename_out.c_str ()),
                ACE_TEXT (newFQfilename.c_str ())));
  } // end IF

  return true;
}
コード例 #10
0
static int icq_snac_extension_userfound_common(session_t *s, unsigned char *buf, int len, int islast) {
	char *nickname = NULL;
	char *first_name = NULL;
	char *last_name = NULL;
	char *email = NULL;
	char *full_name;
	char *temp;
	const char *__age = NULL;
	const char *__gender = "";
	char *__active;

	uint32_t uin;
	uint16_t len2;
	uint16_t status, age;
	uint8_t auth, gender;

	/* XXX, sprawdzic czy mamy cookie. */

	if (!ICQ_UNPACK(&buf, "w", &len2))
		return -1;

	if (len < len2)
		return -1;

	if (!ICQ_UNPACK(&buf, "i", &uin))
		return -1;

	if (!ICQ_UNPACK(&buf, "S", &temp)) goto cleanup;
	nickname = xstrdup(temp);

	if (!ICQ_UNPACK(&buf, "S", &temp)) goto cleanup;
	first_name = xstrdup(temp);

	if (!ICQ_UNPACK(&buf, "S", &temp)) goto cleanup;
	last_name = xstrdup(temp);

	if (!ICQ_UNPACK(&buf, "S", &temp)) goto cleanup;
	email = xstrdup(temp);

	if (first_name[0] && last_name[0])
		full_name = saprintf("%s %s", first_name, last_name);
	else
		full_name = xstrdup(first_name[0] ? first_name : last_name);

	if (ICQ_UNPACK(&buf, "cwcw", &auth, &status, &gender, &age)) {
		if (age)
			__age = itoa(age);		// XXX calculate birthyear?
		if (gender)
			__gender = (gender==2) ? "m" : "f";
	} else {
		debug_error("icq_snac_extension_userfound_common() broken\n");
		auth = status = gender = age = 0;
	}

	/* XXX, "search_results_multi", "search_results_single" */
	/* XXX, instead of email we had city */
	/* XXX, some time ago i was thinking to of function which
	 * 	if data was truncated [because of width in format]
	 * 	it'd take another line to complete..
	 *
	 * 	i don't like truncation of data for instance:
	 * 	 08:17:12  97320776 | darkjames    | Jakub Zawadz | -    | darkjames@po
	 *
	 * 	i was thinking about:
	 * 	           97320776 | darkjames    | Jakub Zawwdz | -    | darkjames@po
	 * 	                                     ki                    czta.onet.pl
	 *
	 * 	of course we can do more magic, and wrap...
	 * 					     Jakub
	 * 					     Zawadzki
	 *
	 * 	or maybe let's  align to center? :)
	 * 						 Jakub
	 * 					       Zawadzki
	 */

	{
		const char *fvalue;
		/* XXX ?wo? new formats for icq status
		 * status (0 - offline, 1 - online, 2 - non_webaware)
		 */
		switch (status) {
			case 0:
				fvalue = format_find("search_results_multi_notavail");
				break;
			case 1:
				fvalue = format_find("search_results_multi_avail");
				break;
			default:
				fvalue = format_find("search_results_multi_unknown");
				break;
		}
		temp = format_string(fvalue);
		/* XXX ?wo? add format for "auth" */
		__active = saprintf("%s %s", temp, auth ? " " : "A");
		xfree(temp);
	}
	print_info(NULL, s, "search_results_multi", itoa(uin), full_name, nickname, email,
			__age ? __age : ("-"), __gender, __active);

	xfree(__active);
	xfree(full_name);

	if (islast && len>=4) {
		uint32_t omit;
		ICQ_UNPACK(&buf, "I", &omit);
		debug_warn("icq_snac_extension_userfound_last() Bulshit warning!\n");
		debug_white("icq_snac_extension_userfound_last() %d search results omitted\n", omit);
	}

	icq_hexdump(DEBUG_WHITE, buf, len);

	xfree(nickname); xfree(first_name); xfree(last_name); xfree(email);
	return 0;

cleanup:
	xfree(nickname); xfree(first_name); xfree(last_name); xfree(email);
	return -1;
}
コード例 #11
0
ファイル: number_format.cpp プロジェクト: tfussell/xlnt
number_format::number_format(const std::string &format, std::size_t id)
{
    format_string(format, id);
}
コード例 #12
0
ファイル: capture.c プロジェクト: AmesianX/RosWine
static BOOL WINAPI dscenum_callback(LPGUID lpGuid, LPCSTR lpcstrDescription,
				    LPCSTR lpcstrModule, LPVOID lpContext)
{
    HRESULT rc;
    LPDIRECTSOUNDCAPTURE dsco=NULL;
    LPDIRECTSOUNDCAPTUREBUFFER dscbo=NULL;
    DSCBUFFERDESC bufdesc;
    WAVEFORMATEX wfx;
    DSCCAPS dsccaps;
    DWORD f;
    int ref;

    /* Private dsound.dll: Error: Invalid interface buffer */
    trace("*** Testing %s - %s ***\n",lpcstrDescription,lpcstrModule);
    rc=pDirectSoundCaptureCreate(lpGuid,NULL,NULL);
    ok(rc==DSERR_INVALIDPARAM,"DirectSoundCaptureCreate() should have "
       "returned DSERR_INVALIDPARAM, returned: %08x\n",rc);

    rc=pDirectSoundCaptureCreate(lpGuid,&dsco,NULL);
    ok((rc==DS_OK)||(rc==DSERR_NODRIVER)||(rc==E_FAIL)||(rc==DSERR_ALLOCATED),
       "DirectSoundCaptureCreate() failed: %08x\n",rc);
    if (rc!=DS_OK) {
        if (rc==DSERR_NODRIVER)
            trace("  No Driver\n");
        else if (rc==E_FAIL)
            trace("  No Device\n");
        else if (rc==DSERR_ALLOCATED)
            trace("  Already In Use\n");
	goto EXIT;
    }

    /* Private dsound.dll: Error: Invalid caps buffer */
    rc=IDirectSoundCapture_GetCaps(dsco,NULL);
    ok(rc==DSERR_INVALIDPARAM,"IDirectSoundCapture_GetCaps() should have "
       "returned DSERR_INVALIDPARAM, returned: %08x\n",rc);

    /* Private dsound.dll: Error: Invalid caps buffer */
    dsccaps.dwSize=0;
    rc=IDirectSoundCapture_GetCaps(dsco,&dsccaps);
    ok(rc==DSERR_INVALIDPARAM,"IDirectSoundCapture_GetCaps() should have "
       "returned DSERR_INVALIDPARAM, returned: %08x\n",rc);

    dsccaps.dwSize=sizeof(dsccaps);
    rc=IDirectSoundCapture_GetCaps(dsco,&dsccaps);
    ok(rc==DS_OK,"IDirectSoundCapture_GetCaps() failed: %08x\n", rc);
    if (rc==DS_OK && winetest_debug > 1) {
	trace("  Caps: size=%d flags=0x%08x formats=%05x channels=%d\n",
	      dsccaps.dwSize,dsccaps.dwFlags,dsccaps.dwFormats,
              dsccaps.dwChannels);
    }

    /* Private dsound.dll: Error: Invalid size */
    /* Private dsound.dll: Error: Invalid capture buffer description */
    ZeroMemory(&bufdesc, sizeof(bufdesc));
    bufdesc.dwSize=0;
    bufdesc.dwFlags=0;
    bufdesc.dwBufferBytes=0;
    bufdesc.dwReserved=0;
    bufdesc.lpwfxFormat=NULL;
    rc=IDirectSoundCapture_CreateCaptureBuffer(dsco,&bufdesc,&dscbo,NULL);
    ok(rc==DSERR_INVALIDPARAM,"IDirectSoundCapture_CreateCaptureBuffer() "
       "should have returned DSERR_INVALIDPARAM, returned: %08x\n", rc);
    if (rc==DS_OK) {
	ref=IDirectSoundCaptureBuffer_Release(dscbo);
	ok(ref==0,"IDirectSoundCaptureBuffer_Release() has %d references, "
           "should have 0\n",ref);
    }

    /* Private dsound.dll: Error: Invalid buffer size */
    /* Private dsound.dll: Error: Invalid capture buffer description */
    ZeroMemory(&bufdesc, sizeof(bufdesc));
    bufdesc.dwSize=sizeof(bufdesc);
    bufdesc.dwFlags=0;
    bufdesc.dwBufferBytes=0;
    bufdesc.dwReserved=0;
    bufdesc.lpwfxFormat=NULL;
    rc=IDirectSoundCapture_CreateCaptureBuffer(dsco,&bufdesc,&dscbo,NULL);
    ok(rc==DSERR_INVALIDPARAM,"IDirectSoundCapture_CreateCaptureBuffer() "
       "should have returned DSERR_INVALIDPARAM, returned %08x\n", rc);
    if (rc==DS_OK) {
	ref=IDirectSoundCaptureBuffer_Release(dscbo);
	ok(ref==0,"IDirectSoundCaptureBuffer_Release() has %d references, "
           "should have 0\n",ref);
    }

    /* Private dsound.dll: Error: Invalid buffer size */
    /* Private dsound.dll: Error: Invalid capture buffer description */
    ZeroMemory(&bufdesc, sizeof(bufdesc));
    ZeroMemory(&wfx, sizeof(wfx));
    bufdesc.dwSize=sizeof(bufdesc);
    bufdesc.dwFlags=0;
    bufdesc.dwBufferBytes=0;
    bufdesc.dwReserved=0;
    bufdesc.lpwfxFormat=&wfx;
    rc=IDirectSoundCapture_CreateCaptureBuffer(dsco,&bufdesc,&dscbo,NULL);
    ok(rc==DSERR_INVALIDPARAM,"IDirectSoundCapture_CreateCaptureBuffer() "
       "should have returned DSERR_INVALIDPARAM, returned: %08x\n", rc);
    if (rc==DS_OK) {
	ref=IDirectSoundCaptureBuffer_Release(dscbo);
	ok(ref==0,"IDirectSoundCaptureBuffer_Release() has %d references, "
           "should have 0\n",ref);
    }

    /* Private dsound.dll: Error: Invalid buffer size */
    /* Private dsound.dll: Error: Invalid capture buffer description */
    init_format(&wfx,WAVE_FORMAT_PCM,11025,8,1);
    ZeroMemory(&bufdesc, sizeof(bufdesc));
    bufdesc.dwSize=sizeof(bufdesc);
    bufdesc.dwFlags=0;
    bufdesc.dwBufferBytes=0;
    bufdesc.dwReserved=0;
    bufdesc.lpwfxFormat=&wfx;
    rc=IDirectSoundCapture_CreateCaptureBuffer(dsco,&bufdesc,&dscbo,NULL);
    ok(rc==DSERR_INVALIDPARAM,"IDirectSoundCapture_CreateCaptureBuffer() "
       "should have returned DSERR_INVALIDPARAM, returned: %08x\n", rc);
    if (rc==DS_OK) {
	ref=IDirectSoundCaptureBuffer_Release(dscbo);
	ok(ref==0,"IDirectSoundCaptureBuffer_Release() has %d references, "
           "should have 0\n",ref);
    }

    for (f=0;f<NB_FORMATS;f++) {
	dscbo=NULL;
	init_format(&wfx,WAVE_FORMAT_PCM,formats[f][0],formats[f][1],
                    formats[f][2]);
	ZeroMemory(&bufdesc, sizeof(bufdesc));
	bufdesc.dwSize=sizeof(bufdesc);
	bufdesc.dwFlags=0;
	bufdesc.dwBufferBytes=wfx.nAvgBytesPerSec;
	bufdesc.dwReserved=0;
	bufdesc.lpwfxFormat=&wfx;
        if (winetest_interactive)
	    trace("  Testing the capture buffer at %s\n", format_string(&wfx));
	rc=IDirectSoundCapture_CreateCaptureBuffer(dsco,&bufdesc,&dscbo,NULL);
	ok(((rc==DS_OK)&&(dscbo!=NULL))
           || rc==DSERR_BADFORMAT || rc==DSERR_INVALIDCALL || rc==DSERR_NODRIVER
           || rc==DSERR_ALLOCATED || rc==E_INVALIDARG || rc==E_FAIL,
           "IDirectSoundCapture_CreateCaptureBuffer() failed to create a "
           "%s capture buffer: %08x\n",format_string(&wfx),rc);
	if (rc==DS_OK) {
	    test_capture_buffer(dsco, dscbo, winetest_interactive);
	    ref=IDirectSoundCaptureBuffer_Release(dscbo);
	    ok(ref==0,"IDirectSoundCaptureBuffer_Release() has %d references, "
               "should have 0\n",ref);
	} else if (rc==DSERR_BADFORMAT) {
            ok(!(dsccaps.dwFormats & formats[f][3]),
               "IDirectSoundCapture_CreateCaptureBuffer() failed to create a "
               "capture buffer: format listed as supported but using it failed\n");
            if (!(dsccaps.dwFormats & formats[f][3]))
                trace("  Format not supported: %s\n", format_string(&wfx));
        } else if (rc==DSERR_NODRIVER) {
            trace("  No Driver\n");
        } else if (rc==DSERR_ALLOCATED) {
            trace("  Already In Use\n");
        } else if (rc==E_INVALIDARG) { /* try the old version struct */
            DSCBUFFERDESC1 bufdesc1;
	    ZeroMemory(&bufdesc1, sizeof(bufdesc1));
	    bufdesc1.dwSize=sizeof(bufdesc1);
	    bufdesc1.dwFlags=0;
	    bufdesc1.dwBufferBytes=wfx.nAvgBytesPerSec;
	    bufdesc1.dwReserved=0;
	    bufdesc1.lpwfxFormat=&wfx;
	    rc=IDirectSoundCapture_CreateCaptureBuffer(dsco,
                (DSCBUFFERDESC*)&bufdesc1,&dscbo,NULL);
            ok(rc==DS_OK || broken(rc==DSERR_INVALIDPARAM),
               "IDirectSoundCapture_CreateCaptureBuffer() failed to create a "
               "%s capture buffer: %08x\n",format_string(&wfx), rc);
            if (rc==DSERR_INVALIDPARAM) {
                skip("broken driver\n");
                goto EXIT;
            }
            if (rc==DS_OK) {
	        test_capture_buffer(dsco, dscbo, winetest_interactive);
	        ref=IDirectSoundCaptureBuffer_Release(dscbo);
	        ok(ref==0,"IDirectSoundCaptureBuffer_Release() has %d "
                   "references, should have 0\n",ref);
            }
        } else if (rc==E_FAIL) {
            /* WAVE_FORMAT_PCM only allows 8 and 16 bits per sample, so only
             * report a failure if the bits per sample is 8 or 16
             */
            if (wfx.wBitsPerSample == 8 || wfx.wBitsPerSample == 16)
                ok(FALSE,"Should not fail for 8 or 16 bits per sample\n");
        }
    }

    /* try a non PCM format */
    if (0)
    {
    /* FIXME: Why is this commented out? */
    init_format(&wfx,WAVE_FORMAT_MULAW,8000,8,1);
    ZeroMemory(&bufdesc, sizeof(bufdesc));
    bufdesc.dwSize=sizeof(bufdesc);
    bufdesc.dwFlags=DSCBCAPS_WAVEMAPPED;
    bufdesc.dwBufferBytes=wfx.nAvgBytesPerSec;
    bufdesc.dwReserved=0;
    bufdesc.lpwfxFormat=&wfx;
    if (winetest_interactive)
        trace("  Testing the capture buffer at %s\n", format_string(&wfx));
    rc=IDirectSoundCapture_CreateCaptureBuffer(dsco,&bufdesc,&dscbo,NULL);
    ok((rc==DS_OK)&&(dscbo!=NULL),"IDirectSoundCapture_CreateCaptureBuffer() "
       "failed to create a capture buffer: %08x\n",rc);
    if ((rc==DS_OK)&&(dscbo!=NULL)) {
	test_capture_buffer(dsco, dscbo, winetest_interactive);
	ref=IDirectSoundCaptureBuffer_Release(dscbo);
	ok(ref==0,"IDirectSoundCaptureBuffer_Release() has %d references, "
           "should have 0\n",ref);
    }
    }

    /* Try an invalid format to test error handling */
    if (0)
    {
    /* FIXME: Remove this test altogether? */
    init_format(&wfx,WAVE_FORMAT_PCM,2000000,16,2);
    ZeroMemory(&bufdesc, sizeof(bufdesc));
    bufdesc.dwSize=sizeof(bufdesc);
    bufdesc.dwFlags=DSCBCAPS_WAVEMAPPED;
    bufdesc.dwBufferBytes=wfx.nAvgBytesPerSec;
    bufdesc.dwReserved=0;
    bufdesc.lpwfxFormat=&wfx;
    if (winetest_interactive)
        trace("  Testing the capture buffer at %s\n", format_string(&wfx));
    rc=IDirectSoundCapture_CreateCaptureBuffer(dsco,&bufdesc,&dscbo,NULL);
    ok(rc!=DS_OK,"IDirectSoundCapture_CreateCaptureBuffer() should have failed "
       "at 2 MHz %08x\n",rc);
    }

EXIT:
    if (dsco!=NULL) {
	ref=IDirectSoundCapture_Release(dsco);
	ok(ref==0,"IDirectSoundCapture_Release() has %d references, should "
           "have 0\n",ref);
    }

    return TRUE;
}
コード例 #13
0
ファイル: JsonPrettify.cpp プロジェクト: DelBero/FBX-glTF
void JsonPrettify::formatPair (utility::string_t &key, web::json::value &val, utility::ostream_t &stream) {
	indent (stream) ;
	format_string (key, stream) ;
	stream << U(": ") ;
	formatValue (val, stream) ;
}
コード例 #14
0
/// Try to print the list of completions l with the prefix prefix using cols as the number of
/// columns. Return true if the completion list was printed, false if the terminal is to narrow for
/// the specified number of columns. Always succeeds if cols is 1.
bool pager_t::completion_try_print(size_t cols, const wcstring &prefix, const comp_info_list_t &lst,
                                   page_rendering_t *rendering, size_t suggested_start_row) const {
    // The calculated preferred width of each column.
    int pref_width[PAGER_MAX_COLS] = {0};
    // The calculated minimum width of each column.
    int min_width[PAGER_MAX_COLS] = {0};
    // If the list can be printed with this width, width will contain the width of each column.
    int *width = pref_width;

    // Set to one if the list should be printed at this width.
    bool print = false;

    // Compute the effective term width and term height, accounting for disclosure.
    size_t term_width = this->available_term_width;
    size_t term_height =
        this->available_term_height - 1 -
        (search_field_shown ? 1 : 0);  // we always subtract 1 to make room for a comment row
    if (!this->fully_disclosed) {
        term_height = mini(term_height, (size_t)PAGER_UNDISCLOSED_MAX_ROWS);
    }

    size_t row_count = divide_round_up(lst.size(), cols);

    // We have more to disclose if we are not fully disclosed and there's more rows than we have in
    // our term height.
    if (!this->fully_disclosed && row_count > term_height) {
        rendering->remaining_to_disclose = row_count - term_height;
    } else {
        rendering->remaining_to_disclose = 0;
    }

    // If we have only one row remaining to disclose, then squelch the comment row. This prevents us
    // from consuming a line to show "...and 1 more row".
    if (!this->fully_disclosed && rendering->remaining_to_disclose == 1) {
        term_height += 1;
        rendering->remaining_to_disclose = 0;
    }

    size_t pref_tot_width = 0;
    size_t min_tot_width = 0;

    // Skip completions on tiny terminals.
    if (term_width < PAGER_MIN_WIDTH) return true;

    // Calculate how wide the list would be.
    for (size_t col = 0; col < cols; col++) {
        for (size_t row = 0; row < row_count; row++) {
            int pref, min;
            const comp_t *c;
            if (lst.size() <= col * row_count + row) continue;

            c = &lst.at(col * row_count + row);
            pref = c->pref_width;
            min = c->min_width;

            if (col != cols - 1) {
                pref += 2;
                min += 2;
            }
            min_width[col] = maxi(min_width[col], min);
            pref_width[col] = maxi(pref_width[col], pref);
        }
        min_tot_width += min_width[col];
        pref_tot_width += pref_width[col];
    }

    // Force fit if one column.
    if (cols == 1) {
        if (pref_tot_width > term_width) {
            pref_width[0] = term_width;
        }
        width = pref_width;
        print = true;
    } else if (pref_tot_width <= term_width) {
        // Terminal is wide enough. Print the list!
        width = pref_width;
        print = true;
    }

    if (print) {
        // Determine the starting and stop row.
        size_t start_row = 0, stop_row = 0;
        if (row_count <= term_height) {
            // Easy, we can show everything.
            start_row = 0;
            stop_row = row_count;
        } else {
            // We can only show part of the full list. Determine which part based on the
            // suggested_start_row.
            assert(row_count > term_height);
            size_t last_starting_row = row_count - term_height;
            start_row = mini(suggested_start_row, last_starting_row);
            stop_row = start_row + term_height;
            assert(start_row >= 0 && start_row <= last_starting_row);
        }

        assert(stop_row >= start_row);
        assert(stop_row <= row_count);
        assert(stop_row - start_row <= term_height);
        completion_print(cols, width, start_row, stop_row, prefix, lst, rendering);

        // Ellipsis helper string. Either empty or containing the ellipsis char.
        const wchar_t ellipsis_string[] = {ellipsis_char == L'\x2026' ? L'\x2026' : L'\0', L'\0'};

        // Add the progress line. It's a "more to disclose" line if necessary, or a row listing if
        // it's scrollable; otherwise ignore it.
        wcstring progress_text;
        if (rendering->remaining_to_disclose == 1) {
            // I don't expect this case to ever happen.
            progress_text = format_string(_(L"%lsand 1 more row"), ellipsis_string);
        } else if (rendering->remaining_to_disclose > 1) {
            progress_text = format_string(_(L"%lsand %lu more rows"), ellipsis_string,
                                          (unsigned long)rendering->remaining_to_disclose);
        } else if (start_row > 0 || stop_row < row_count) {
            // We have a scrollable interface. The +1 here is because we are zero indexed, but want
            // to present things as 1-indexed. We do not add 1 to stop_row or row_count because
            // these are the "past the last value".
            progress_text =
                format_string(_(L"rows %lu to %lu of %lu"), start_row + 1, stop_row, row_count);
        } else if (completion_infos.empty() && !unfiltered_completion_infos.empty()) {
            // Everything is filtered.
            progress_text = _(L"(no matches)");
        }

        if (!progress_text.empty()) {
            line_t &line = rendering->screen_data.add_line();
            print_max(progress_text, highlight_spec_pager_progress |
                                         highlight_make_background(highlight_spec_pager_progress),
                      term_width, true /* has_more */, &line);
        }

        if (search_field_shown) {
            // Add the search field.
            wcstring search_field_text = search_field_line.text;
            // Append spaces to make it at least the required width.
            if (search_field_text.size() < PAGER_SEARCH_FIELD_WIDTH) {
                search_field_text.append(PAGER_SEARCH_FIELD_WIDTH - search_field_text.size(), L' ');
            }
            line_t *search_field = &rendering->screen_data.insert_line_at_index(0);

            // We limit the width to term_width - 1.
            int search_field_written = print_max(SEARCH_FIELD_PROMPT, highlight_spec_normal,
                                                 term_width - 1, false, search_field);
            print_max(search_field_text, highlight_modifier_force_underline,
                      term_width - search_field_written - 1, false, search_field);
        }
    }
    return print;
}
コード例 #15
0
ファイル: git-access.c プロジェクト: ngdmcc/subsurface
/*
 * If it's not a git repo, return NULL. Be very conservative.
 */
struct git_repository *is_git_repository(const char *filename, const char **branchp, const char **remote)
{
	int flen, blen, ret;
	int offset = 1;
	struct stat st;
	git_repository *repo;
	char *loc, *branch;

	flen = strlen(filename);
	if (!flen || filename[--flen] != ']')
		return NULL;

	/* Find the matching '[' */
	blen = 0;
	while (flen && filename[--flen] != '[')
		blen++;

	/* Ignore slashes at the end of the repo name */
	while (flen && filename[flen-1] == '/') {
		flen--;
		offset++;
	}

	if (!flen)
		return NULL;

	/*
	 * This is the "point of no return": the name matches
	 * the git repository name rules, and we will no longer
	 * return NULL.
	 *
	 * We will either return "dummy_git_repository" and the
	 * branch pointer will have the _whole_ filename in it,
	 * or we will return a real git repository with the
	 * branch pointer being filled in with just the branch
	 * name.
	 *
	 * The actual git reading/writing routines can use this
	 * to generate proper error messages.
	 */
	*branchp = filename;
	loc = format_string("%.*s", flen, filename);
	if (!loc)
		return dummy_git_repository;

	branch = format_string("%.*s", blen, filename + flen + offset);
	if (!branch) {
		free(loc);
		return dummy_git_repository;
	}

	repo = is_remote_git_repository(loc, branch);
	if (repo) {
		if (remote)
			*remote = loc;
		else
			free(loc);
		*branchp = branch;
		return repo;
	}

	if (stat(loc, &st) < 0 || !S_ISDIR(st.st_mode)) {
		free(loc);
		free(branch);
		return dummy_git_repository;
	}

	ret = git_repository_open(&repo, loc);
	free(loc);
	if (ret < 0) {
		free(branch);
		return dummy_git_repository;
	}
	if (remote)
		*remote = NULL;
	*branchp = branch;
	return repo;
}
コード例 #16
0
ファイル: dsound8.c プロジェクト: reactos/reactos
/*
 * Test the primary buffer at different formats while keeping the
 * secondary buffer at a constant format.
 */
static HRESULT test_primary_secondary8(LPGUID lpGuid)
{
    HRESULT rc;
    LPDIRECTSOUND8 dso=NULL;
    LPDIRECTSOUNDBUFFER primary=NULL,secondary=NULL;
    DSBUFFERDESC bufdesc;
    DSCAPS dscaps;
    WAVEFORMATEX wfx, wfx2;
    int ref;
    unsigned int f, tag;

    /* Create the DirectSound object */
    rc=pDirectSoundCreate8(lpGuid,&dso,NULL);
    ok(rc==DS_OK||rc==DSERR_NODRIVER||rc==DSERR_ALLOCATED,
       "DirectSoundCreate8() failed: %08x\n",rc);
    if (rc!=DS_OK)
        return rc;

    /* Get the device capabilities */
    ZeroMemory(&dscaps, sizeof(dscaps));
    dscaps.dwSize=sizeof(dscaps);
    rc=IDirectSound8_GetCaps(dso,&dscaps);
    ok(rc==DS_OK,"IDirectSound8_GetCaps() failed: %08x\n",rc);
    if (rc!=DS_OK)
        goto EXIT;

    /* We must call SetCooperativeLevel before creating primary buffer */
    /* DSOUND: Setting DirectSound cooperative level to DSSCL_PRIORITY */
    rc=IDirectSound8_SetCooperativeLevel(dso,get_hwnd(),DSSCL_PRIORITY);
    ok(rc==DS_OK,"IDirectSound8_SetCooperativeLevel() failed: %08x\n", rc);
    if (rc!=DS_OK)
        goto EXIT;

    ZeroMemory(&bufdesc, sizeof(bufdesc));
    bufdesc.dwSize=sizeof(bufdesc);
    bufdesc.dwFlags=DSBCAPS_PRIMARYBUFFER;
    rc=IDirectSound8_CreateSoundBuffer(dso,&bufdesc,&primary,NULL);
    ok(rc==DS_OK && primary!=NULL,
       "IDirectSound8_CreateSoundBuffer() failed to create a primary buffer "
       "%08x\n",rc);

    if (rc==DS_OK && primary!=NULL) {
        for (f=0;f<NB_FORMATS;f++) {
          for (tag=0;tag<NB_TAGS;tag++) {
            /* if float, we only want to test 32-bit */
            if ((format_tags[tag] == WAVE_FORMAT_IEEE_FLOAT) && (formats[f][1] != 32))
                continue;

            /* We must call SetCooperativeLevel to be allowed to call
             * SetFormat */
            /* DSOUND: Setting DirectSound cooperative level to
             * DSSCL_PRIORITY */
            rc=IDirectSound8_SetCooperativeLevel(dso,get_hwnd(),DSSCL_PRIORITY);
            ok(rc==DS_OK,"IDirectSound8_SetCooperativeLevel() failed: %08x\n", rc);
            if (rc!=DS_OK)
                goto EXIT;

            init_format(&wfx,format_tags[tag],formats[f][0],formats[f][1],
                        formats[f][2]);
            wfx2=wfx;
            rc=IDirectSoundBuffer_SetFormat(primary,&wfx);
            ok(rc==DS_OK
               || rc==DSERR_INVALIDPARAM, /* 2003 */
               "IDirectSoundBuffer_SetFormat(%s) failed: %08x\n",
               format_string(&wfx), rc);

            /* There is no guarantee that SetFormat will actually change the
             * format to what we asked for. It depends on what the soundcard
             * supports. So we must re-query the format.
             */
            rc=IDirectSoundBuffer_GetFormat(primary,&wfx,sizeof(wfx),NULL);
            ok(rc==DS_OK,"IDirectSoundBuffer_GetFormat() failed: %08x\n", rc);
            if (rc==DS_OK &&
                (wfx.wFormatTag!=wfx2.wFormatTag ||
                 wfx.nSamplesPerSec!=wfx2.nSamplesPerSec ||
                 wfx.wBitsPerSample!=wfx2.wBitsPerSample ||
                 wfx.nChannels!=wfx2.nChannels)) {
                trace("Requested primary format tag=0x%04x %dx%dx%d "
                      "avg.B/s=%d align=%d\n",
                      wfx2.wFormatTag,wfx2.nSamplesPerSec,wfx2.wBitsPerSample,
                      wfx2.nChannels,wfx2.nAvgBytesPerSec,wfx2.nBlockAlign);
                trace("Got tag=0x%04x %dx%dx%d avg.B/s=%d align=%d\n",
                      wfx.wFormatTag,wfx.nSamplesPerSec,wfx.wBitsPerSample,
                      wfx.nChannels,wfx.nAvgBytesPerSec,wfx.nBlockAlign);
            }

            /* Set the CooperativeLevel back to normal */
            /* DSOUND: Setting DirectSound cooperative level to DSSCL_NORMAL */
            rc=IDirectSound8_SetCooperativeLevel(dso,get_hwnd(),DSSCL_NORMAL);
            ok(rc==DS_OK,"IDirectSound8_SetCooperativeLevel() failed: %08x\n", rc);

            init_format(&wfx2,WAVE_FORMAT_PCM,11025,16,2);

            secondary=NULL;
            ZeroMemory(&bufdesc, sizeof(bufdesc));
            bufdesc.dwSize=sizeof(bufdesc);
            bufdesc.dwFlags=DSBCAPS_GETCURRENTPOSITION2;
            bufdesc.dwBufferBytes=align(wfx.nAvgBytesPerSec*BUFFER_LEN/1000,
                                        wfx.nBlockAlign);
            bufdesc.lpwfxFormat=&wfx2;
            if (winetest_interactive) {
                trace("  Testing a primary buffer at %dx%dx%d (fmt=%d) with a "
                      "secondary buffer at %dx%dx%d\n",
                      wfx.nSamplesPerSec,wfx.wBitsPerSample,wfx.nChannels,format_tags[tag],
                      wfx2.nSamplesPerSec,wfx2.wBitsPerSample,wfx2.nChannels);
            }
            rc=IDirectSound_CreateSoundBuffer(dso,&bufdesc,&secondary,NULL);
            ok(rc==DS_OK && secondary!=NULL,
               "IDirectSound_CreateSoundBuffer() failed to create a secondary "
               "buffer %08x\n",rc);

            if (rc==DS_OK && secondary!=NULL) {
                test_buffer8(dso,&secondary,0,FALSE,0,FALSE,0,
                             winetest_interactive,1.0,0,NULL,0,0);

                ref=IDirectSoundBuffer_Release(secondary);
                ok(ref==0,"IDirectSoundBuffer_Release() has %d references, "
                   "should have 0\n",ref);
            }
          }
        }

        ref=IDirectSoundBuffer_Release(primary);
        ok(ref==0,"IDirectSoundBuffer_Release() primary has %d references, "
           "should have 0\n",ref);
    }

    /* Set the CooperativeLevel back to normal */
    /* DSOUND: Setting DirectSound cooperative level to DSSCL_NORMAL */
    rc=IDirectSound8_SetCooperativeLevel(dso,get_hwnd(),DSSCL_NORMAL);
    ok(rc==DS_OK,"IDirectSound8_SetCooperativeLevel() failed: %08x\n", rc);

EXIT:
    ref=IDirectSound8_Release(dso);
    ok(ref==0,"IDirectSound8_Release() has %d references, should have 0\n",ref);
    if (ref!=0)
        return DSERR_GENERIC;

    return rc;
}
コード例 #17
0
ファイル: env.cpp プロジェクト: GarethLewin/fish-shell
env_var_t env_get_string(const wcstring &key)
{
    /* Big hack...we only allow getting the history on the main thread. Note that history_t may ask for an environment variable, so don't take the lock here (we don't need it) */
    const bool is_main = is_main_thread();
    if (key == L"history" && is_main)
    {
        env_var_t result;

        history_t *history = reader_get_history();
        if (! history)
        {
            history = &history_t::history_with_name(L"fish");
        }
        if (history)
            history->get_string_representation(result, ARRAY_SEP_STR);
        return result;
    }
    else if (key == L"COLUMNS")
    {
        return to_string(common_get_width());
    }
    else if (key == L"LINES")
    {
        return to_string(common_get_height());
    }
    else if (key == L"status")
    {
        return to_string(proc_get_last_status());
    }
    else if (key == L"umask")
    {
        return format_string(L"0%0.3o", get_umask());
    }
    else
    {
        {
            /* Lock around a local region */
            scoped_lock lock(env_lock);

            env_node_t *env = top;
            wcstring result;

            while (env != NULL)
            {
                const var_entry_t *entry = env->find_entry(key);
                if (entry != NULL)
                {
                    if (entry->val == ENV_NULL)
                    {
                        return env_var_t::missing_var();
                    }
                    else
                    {
                        return entry->val;
                    }
                }

                env = env->next_scope_to_search();
            }
        }

        /* Another big hack - only do a universal barrier on the main thread (since it can change variable values)
           Make sure we do this outside the env_lock because it may itself call env_get_string */
        if (is_main && ! get_proc_had_barrier())
        {
            set_proc_had_barrier(true);
            env_universal_barrier();
        }

        const wchar_t *item = env_universal_get(key);

        if (!item || (wcscmp(item, ENV_NULL)==0))
        {
            return env_var_t::missing_var();
        }
        else
        {
            return item;
        }
    }
}
コード例 #18
0
ファイル: proc.cpp プロジェクト: Sam0523/fish-shell
static int process_clean_after_marking(bool allow_interactive) {
    ASSERT_IS_MAIN_THREAD();
    job_t *jnext;
    int found = 0;

    // this function may fire an event handler, we do not want to call ourselves recursively (to avoid
    // infinite recursion).
    static bool locked = false;
    if (locked) {
        return 0;
    }
    locked = true;

    // this may be invoked in an exit handler, after the TERM has been torn down
    // don't try to print in that case (#3222)
    const bool interactive = allow_interactive && cur_term != NULL;


    job_iterator_t jobs;
    const size_t job_count = jobs.count();
    jnext = jobs.next();
    while (jnext) {
        job_t *j = jnext;
        jnext = jobs.next();

        // If we are reaping only jobs who do not need status messages sent to the console, do not
        // consider reaping jobs that need status messages.
        if ((!j->get_flag(JOB_SKIP_NOTIFICATION)) && (!interactive) &&
            (!j->get_flag(JOB_FOREGROUND))) {
            continue;
        }

        for (const process_ptr_t &p : j->processes) {
            int s;
            if (!p->completed) continue;

            if (!p->pid) continue;

            s = p->status;

            // TODO: The generic process-exit event is useless and unused.
            // Remove this in future.
            proc_fire_event(L"PROCESS_EXIT", EVENT_EXIT, p->pid,
                            (WIFSIGNALED(s) ? -1 : WEXITSTATUS(s)));

            // Ignore signal SIGPIPE.We issue it ourselves to the pipe writer when the pipe reader
            // dies.
            if (!WIFSIGNALED(s) || WTERMSIG(s) == SIGPIPE) {
                continue;
            }

            // Handle signals other than SIGPIPE.
            int proc_is_job = (p->is_first_in_job && p->is_last_in_job);
            if (proc_is_job) j->set_flag(JOB_NOTIFIED, true);
            if (j->get_flag(JOB_SKIP_NOTIFICATION)) {
                continue;
            }

            // Print nothing if we get SIGINT in the foreground process group, to avoid spamming
            // obvious stuff on the console (#1119). If we get SIGINT for the foreground
            // process, assume the user typed ^C and can see it working. It's possible they
            // didn't, and the signal was delivered via pkill, etc., but the SIGINT/SIGTERM
            // distinction is precisely to allow INT to be from a UI
            // and TERM to be programmatic, so this assumption is keeping with the design of
            // signals. If echoctl is on, then the terminal will have written ^C to the console.
            // If off, it won't have. We don't echo ^C either way, so as to respect the user's
            // preference.
            if (WTERMSIG(p->status) != SIGINT || !j->get_flag(JOB_FOREGROUND)) {
                if (proc_is_job) {
                    // We want to report the job number, unless it's the only job, in which case
                    // we don't need to.
                    const wcstring job_number_desc =
                        (job_count == 1) ? wcstring() : format_string(_(L"Job %d, "), j->job_id);
                    fwprintf(stdout, _(L"%ls: %ls\'%ls\' terminated by signal %ls (%ls)"),
                             program_name, job_number_desc.c_str(),
                             truncate_command(j->command()).c_str(), sig2wcs(WTERMSIG(p->status)),
                             signal_get_desc(WTERMSIG(p->status)));
                } else {
                    const wcstring job_number_desc =
                        (job_count == 1) ? wcstring() : format_string(L"from job %d, ", j->job_id);
                    const wchar_t *fmt =
                        _(L"%ls: Process %d, \'%ls\' %ls\'%ls\' terminated by signal %ls (%ls)");
                    fwprintf(stdout, fmt, program_name, p->pid, p->argv0(), job_number_desc.c_str(),
                             truncate_command(j->command()).c_str(), sig2wcs(WTERMSIG(p->status)),
                             signal_get_desc(WTERMSIG(p->status)));
                }

                if (cur_term != NULL) {
                    tputs(clr_eol, 1, &writeb);
                } else {
                    fwprintf(stdout, L"\e[K");  // no term set up - do clr_eol manually
                }
                fwprintf(stdout, L"\n");
            }
            found = 1;
            p->status = 0;  // clear status so it is not reported more than once
        }

        // If all processes have completed, tell the user the job has completed and delete it from
        // the active job list.
        if (job_is_completed(j)) {
            if (!j->get_flag(JOB_FOREGROUND) && !j->get_flag(JOB_NOTIFIED) &&
                !j->get_flag(JOB_SKIP_NOTIFICATION)) {
                format_job_info(j, JOB_ENDED);
                found = 1;
            }
            // TODO: The generic process-exit event is useless and unused.
            // Remove this in future.
            // Don't fire the exit-event for jobs with pgid -2.
            // That's our "sentinel" pgid, for jobs that don't (yet) have a pgid,
            // or jobs that consist entirely of builtins (and hence don't have a process).
            // This causes issues if fish is PID 2, which is quite common on WSL. See #4582.
            if (j->pgid != -2) {
                proc_fire_event(L"JOB_EXIT", EVENT_EXIT, -j->pgid, 0);
            }
            proc_fire_event(L"JOB_EXIT", EVENT_JOB_ID, j->job_id, 0);

            job_remove(j);
        } else if (job_is_stopped(j) && !j->get_flag(JOB_NOTIFIED)) {
            // Notify the user about newly stopped jobs.
            if (!j->get_flag(JOB_SKIP_NOTIFICATION)) {
                format_job_info(j, JOB_STOPPED);
                found = 1;
            }
            j->set_flag(JOB_NOTIFIED, true);
        }
    }

    if (found) fflush(stdout);

    locked = false;

    return found;
}
コード例 #19
0
// -------------------------------------------------------------------
// dialog for purchasing buildings in town
// create buttons for purchasing buildings.
// -------------------------------------------------------------------
void t_buy_building_window::create_buttons( t_window* background )
{
	t_button_info button_info[k_max_buttons];
	t_town_type   town_type = m_town->get_type();
	t_help_block const& help = get_help_block( "town_hall" );

	int i;

	for (i = 0; i < k_max_buttons; i++)
	{
		button_info[i].id = -1;
		button_info[i].state = k_button_hidden;
	}

	set_button_state( button_info, m_town, k_common_buttons, ELEMENTS_OF( k_common_buttons ));
	set_button_state( button_info, m_town, k_button_maps[town_type].map, 
	                  k_button_maps[town_type].count );

	t_bitmap_layer const* layer;
	t_button*			  button;
	t_bitmap_layer const* frame = m_interface->find( "frame" );
	t_screen_point        frame_origin = frame->get_rect().top_left();
	t_bitmap_layer const* thumbnail = m_interface->find( "thumbnail" );
	t_screen_point        thumbnail_origin = thumbnail->get_rect().top_left() - frame_origin;
	t_bitmap_layer const* x_mark = m_interface->find( "cannot build" );
	t_bitmap_layer const* bars[6];
	t_window*             frame_window;
	t_window*             window;
	t_town_building       building;

	m_thumbnails = g_building_thumbnails[town_type]->get();

	bars[k_button_disabled - 1]		 = m_interface->find( "gray bar" );
	bars[k_button_built - 1]		 = m_interface->find( "gold bar" );
	bars[k_button_cannot_build - 1]	 = m_interface->find( "red bar" );
	bars[k_button_cannot_afford - 1] = bars[k_button_cannot_build - 1];
	bars[k_button_not_owner - 1]     = bars[k_button_cannot_build - 1];
	bars[k_button_ok - 1]			 = m_interface->find( "green bar" );

	// find row rectangles
	t_bitmap_layer const* rows[5];
	int                   row_counts[5];
	int                   row_spacing[5];
	int                   row_start[5];

	for (i = 0; i < 5; i++)
	{
		row_counts[i] = 0;
		rows[i] = m_interface->find( format_string( "row %i", i + 1 ) );
	}

	// count # of buttons in each row
	for (i = 0; i < 20; i++)
		if (button_info[i].state != k_button_hidden)
			row_counts[i / 4]++;

	// compute row spacing
    int             width_diff;
	for (i = 0; i < 5; i++)
	{
        // Diff. between row frame and sum of individual building frames.
        width_diff = (rows[i]->get_width() - k_building_columns * frame->get_width());

		row_spacing[i] = width_diff / (k_building_columns - 1) + frame->get_width();
		row_start[i] =  (rows[i]->get_width() - frame->get_width() 
			             - row_spacing[i] * (row_counts[i] - 1)) / 2;
	}             

	// create the buttons
	t_screen_point  point;
	int             row;
	t_window*       bar;
	t_text_window*  text_window;
	t_screen_rect   rect;
	t_screen_rect   text_rect = m_interface->find("building_text")->get_rect();

	//t_screen_point  thumbnail_offset;

	for (i = 0; i < k_max_buttons; i++)
	{
		if (button_info[i].state == k_button_hidden)
			continue;

		building = t_town_building( button_info[i].id  );

		t_building_traits const& traits = get_traits( town_type, building );

		row = i / k_building_columns;
		point = rows[row]->get_rect().top_left();
		point.x += row_start[row] + (i % k_building_columns ) * row_spacing[row];
		button = new t_button( point, background );
		
        rect = frame->get_rect() - frame->get_rect().top_left();
	    frame_window = new t_window ( rect, k_completely_transparent, button );
		window = new t_bitmap_layer_window( frame, -frame->get_rect().top_left(), frame_window );

		// add thumbnail
		layer = m_thumbnails->find( traits.keyword );
		window = new t_bitmap_layer_window( layer, thumbnail_origin, frame_window );

		// if cannot build, add X mark
		switch (button_info[i].state)
		{
			case k_button_disabled:
			case k_button_cannot_build:
			case k_button_cannot_afford:
				window = new t_bitmap_layer_window( x_mark, -frame_origin, frame_window );
				break;
		}
		
		// add appropriate bar
		t_bitmap_layer const* bar_layer = bars[button_info[i].state - 1];
		bar = new t_bitmap_layer_window( bar_layer, -frame_origin, frame_window );
		
		// add name to bar
		text_window = new t_text_window( get_font( text_rect.height() / 2 ), text_rect - bar_layer->get_rect().top_left(),
			                             bar, traits.name, t_pixel_24(0, 0, 0) );
		text_window->set_center_horizontal();
		text_window->set_center_vertical();
		//text_window->set_drop_shadow( true );

		switch (button_info[i].state)
		{
            case k_button_built:
	            set_help( button, help, "gold_bar" );
                break;

			case k_button_disabled:
	            set_help( button, help, "gray_bar" );
                break;

			case k_button_cannot_build:
	            set_help( button, help, "red_bar_x" );
                break;

			case k_button_cannot_afford:
	            set_help( button, help, "red_bar_$" );
				break;

			case k_button_not_owner:
				set_help( button, help, "red_bar_owner" );
				break;

            default :
	            set_help( button, help, "green_bar" );
				break;
		}
		
		// set image and handler
	    frame_window->set_size_from_children();
		button->set_released_image( frame_window );
		if (button_info[i].state == k_button_disabled)
        {
		    button->set_click_handler( add_2nd_argument(
			    bound_handler( *this, &t_buy_building_window::disabled_building_click ), button_info[i].id ));
        }
        else
        {
		    button->set_click_handler( add_2nd_argument(
			    bound_handler( *this, &t_buy_building_window::building_click ), button_info[i].id ));
        }
		button->set_right_click_handler( add_2nd_argument(
			bound_handler( *this, &t_buy_building_window::describe_building ), button_info[i].id ));
	}
}
コード例 #20
0
ファイル: git-access.c プロジェクト: dirkhh/subsurface
/*
 * If it's not a git repo, return NULL. Be very conservative.
 */
struct git_repository *is_git_repository(const char *filename, const char **branchp, const char **remote, bool dry_run)
{
	int flen, blen, ret;
	int offset = 1;
	struct stat st;
	git_repository *repo;
	char *loc, *branch;

	flen = strlen(filename);
	if (!flen || filename[--flen] != ']')
		return NULL;

	/*
	 * Special-case "file://", and treat it as a local
	 * repository since libgit2 is insanely slow for that.
	 */
	if (!strncmp(filename, "file://", 7)) {
		filename += 7;
		flen -= 7;
	}

	/* Find the matching '[' */
	blen = 0;
	while (flen && filename[--flen] != '[')
		blen++;

	/* Ignore slashes at the end of the repo name */
	while (flen && filename[flen-1] == '/') {
		flen--;
		offset++;
	}

	if (!flen)
		return NULL;

	/*
	 * This is the "point of no return": the name matches
	 * the git repository name rules, and we will no longer
	 * return NULL.
	 *
	 * We will either return "dummy_git_repository" and the
	 * branch pointer will have the _whole_ filename in it,
	 * or we will return a real git repository with the
	 * branch pointer being filled in with just the branch
	 * name.
	 *
	 * The actual git reading/writing routines can use this
	 * to generate proper error messages.
	 */
	*branchp = filename;
	loc = format_string("%.*s", flen, filename);
	if (!loc)
		return dummy_git_repository;

	branch = format_string("%.*s", blen, filename + flen + offset);
	if (!branch) {
		free(loc);
		return dummy_git_repository;
	}

	if (dry_run) {
		*branchp = branch;
		*remote = loc;
		return dummy_git_repository;
	}
	repo = is_remote_git_repository(loc, branch);
	if (repo) {
		if (remote)
			*remote = loc;
		else
			free(loc);
		*branchp = branch;
		return repo;
	}

	if (subsurface_stat(loc, &st) < 0 || !S_ISDIR(st.st_mode)) {
		if (verbose)
			fprintf(stderr, "loc %s wasn't found or is not a directory\n", loc);
		free(loc);
		free(branch);
		return dummy_git_repository;
	}

	ret = git_repository_open(&repo, loc);
	free(loc);
	if (ret < 0) {
		free(branch);
		return dummy_git_repository;
	}
	if (remote)
		*remote = NULL;
	*branchp = branch;
	return repo;
}
コード例 #21
0
ファイル: env.cpp プロジェクト: lnsoso/fish-shell
env_var_t env_get_string(const wcstring &key, env_mode_flags_t mode)
{
    const bool has_scope = mode & (ENV_LOCAL | ENV_GLOBAL | ENV_UNIVERSAL);
    const bool search_local = !has_scope || (mode & ENV_LOCAL);
    const bool search_global = !has_scope || (mode & ENV_GLOBAL);
    const bool search_universal = !has_scope || (mode & ENV_UNIVERSAL);

    const bool search_exported = (mode & ENV_EXPORT) || !(mode & ENV_UNEXPORT);
    const bool search_unexported = (mode & ENV_UNEXPORT) || !(mode & ENV_EXPORT);

    /* Make the assumption that electric keys can't be shadowed elsewhere, since we currently block that in env_set() */
    if (is_electric(key))
    {
        if (!search_global) return env_var_t::missing_var();
        /* Big hack...we only allow getting the history on the main thread. Note that history_t may ask for an environment variable, so don't take the lock here (we don't need it) */
        if (key == L"history" && is_main_thread())
        {
            env_var_t result;

            history_t *history = reader_get_history();
            if (! history)
            {
                history = &history_t::history_with_name(L"fish");
            }
            if (history)
                history->get_string_representation(&result, ARRAY_SEP_STR);
            return result;
        }
        else if (key == L"COLUMNS")
        {
            return to_string(common_get_width());
        }
        else if (key == L"LINES")
        {
            return to_string(common_get_height());
        }
        else if (key == L"status")
        {
            return to_string(proc_get_last_status());
        }
        else if (key == L"umask")
        {
            return format_string(L"0%0.3o", get_umask());
        }
        // we should never get here unless the electric var list is out of sync
    }

    if (search_local || search_global) {
        /* Lock around a local region */
        scoped_lock lock(env_lock);

        env_node_t *env = search_local ? top : global_env;

        while (env != NULL)
        {
            const var_entry_t *entry = env->find_entry(key);
            if (entry != NULL && (entry->exportv ? search_exported : search_unexported))
            {
                if (entry->val == ENV_NULL)
                {
                    return env_var_t::missing_var();
                }
                else
                {
                    return entry->val;
                }
            }

            if (has_scope)
            {
                if (!search_global || env == global_env) break;
                env = global_env;
            }
            else
            {
                env = env->next_scope_to_search();
            }
        }
    }

    if (!search_universal) return env_var_t::missing_var();

    /* Another big hack - only do a universal barrier on the main thread (since it can change variable values)
        Make sure we do this outside the env_lock because it may itself call env_get_string */
    if (is_main_thread() && ! get_proc_had_barrier())
    {
        set_proc_had_barrier(true);
        env_universal_barrier();
    }

    if (uvars())
    {
        env_var_t env_var = uvars()->get(key);
        if (env_var == ENV_NULL || !(uvars()->get_export(key) ? search_exported : search_unexported))
        {
            env_var = env_var_t::missing_var();
        }
        return env_var;
    }
    return env_var_t::missing_var();
}
コード例 #22
0
ファイル: object_list.c プロジェクト: kevinburke/OpenRCT2
/**
 * 
 *  rct2: 0x006A8B40
 */
void object_list_load()
{
	HANDLE hFindFile;
	WIN32_FIND_DATAA findFileData;
	int totalFiles = 0, totalFileSize = 0, fileDateModifiedChecksum = 0;

	char pluginPath[MAX_PATH];
	get_plugin_path(pluginPath);

	// Enumerate through each object in the directory
	hFindFile = FindFirstFile(RCT2_ADDRESS(RCT2_ADDRESS_OBJECT_DATA_PATH, char), &findFileData);
	if (hFindFile != INVALID_HANDLE_VALUE) {
		do {
			totalFiles++;
			totalFileSize += findFileData.nFileSizeLow;
			fileDateModifiedChecksum ^=
				findFileData.ftLastWriteTime.dwLowDateTime ^
				findFileData.ftLastWriteTime.dwHighDateTime;
			fileDateModifiedChecksum = ror32(fileDateModifiedChecksum, 5);
		} while (FindNextFile(hFindFile, &findFileData));
		FindClose(hFindFile);
	}

	totalFiles = ror32(totalFiles, 24);
	totalFiles = (totalFiles & ~0xFF) | 1;
	totalFiles = rol32(totalFiles, 24);

	// Read plugin header
	rct_plugin_header pluginHeader;

	FILE *file = fopen(pluginPath, "rb");
	if (file != NULL) {
		if (fread(&pluginHeader, sizeof(pluginHeader), 1, file) == 1) {
			// Check if object repository has changed in anyway
			if (
				totalFiles == pluginHeader.total_files &&
				totalFileSize == pluginHeader.total_file_size &&
				fileDateModifiedChecksum == pluginHeader.date_modified_checksum
			) {
				// Dispose installed object list
				if (RCT2_GLOBAL(RCT2_ADDRESS_INSTALLED_OBJECT_LIST, sint32) != -1) {
					rct2_free(RCT2_GLOBAL(RCT2_ADDRESS_INSTALLED_OBJECT_LIST, void*));
					RCT2_GLOBAL(RCT2_ADDRESS_INSTALLED_OBJECT_LIST, sint32) = -1;
				}

				// Read installed object list
				RCT2_GLOBAL(RCT2_ADDRESS_INSTALLED_OBJECT_LIST, void*) = rct2_malloc(pluginHeader.object_list_size);
				if (fread(RCT2_GLOBAL(RCT2_ADDRESS_INSTALLED_OBJECT_LIST, void*), pluginHeader.object_list_size, 1, file) == 1) {
					RCT2_GLOBAL(RCT2_ADDRESS_OBJECT_LIST_NO_ITEMS, uint32) = pluginHeader.object_list_no_items;

					fclose(file);
					sub_6A9FC0();
					object_list_examine();
					return;
				}
			}
		}
		fclose(file);
	}

	// Reload object list
	RCT2_GLOBAL(0x00F42B94, uint32) = totalFiles;
	RCT2_GLOBAL(0x00F42B98, uint32) = totalFileSize;
	RCT2_GLOBAL(0x00F42B9C, uint32) = fileDateModifiedChecksum;
	//RCT2_CALLPROC_EBPSAFE(0x006A8D8F);

	int eax = 3161;
	if (RCT2_GLOBAL(0x9AA00D, uint8) != 0){
		eax = 3160;
		RCT2_GLOBAL(0x9AA00D, uint8) = 0;
	}
	// File count removed and replaced by variable
	// RCT2_GLOBAL(0xF42BA8, uint32) = 0;
	uint32 file_count = 0;

	// Progress bar related.
	RCT2_GLOBAL(0xF42BD8, uint8) = 0;

	sub_6A9FC0();

	// Dispose installed object list
	if (RCT2_GLOBAL(RCT2_ADDRESS_INSTALLED_OBJECT_LIST, sint32) != -1) {
		rct2_free(RCT2_GLOBAL(RCT2_ADDRESS_INSTALLED_OBJECT_LIST, void*));
		RCT2_GLOBAL(RCT2_ADDRESS_INSTALLED_OBJECT_LIST, sint32) = -1;
	}

	RCT2_GLOBAL(RCT2_ADDRESS_OBJECT_LIST_NO_ITEMS, uint32) = 0;
	RCT2_GLOBAL(RCT2_ADDRESS_INSTALLED_OBJECT_LIST, void*) = rct2_malloc(4096);
	if (RCT2_GLOBAL(RCT2_ADDRESS_INSTALLED_OBJECT_LIST, int) == -1){
		RCT2_CALLPROC_X(0x006E3838, 0x343, 0xC5A, 0, 0, 0, 0, 0);
		return;
	}

	uint32 installed_buffer_size = 0x1000;
	uint32 current_item_offset = 0;

	hFindFile = FindFirstFile(RCT2_ADDRESS(RCT2_ADDRESS_OBJECT_DATA_PATH, char), &findFileData);
	if (hFindFile == INVALID_HANDLE_VALUE){
		//6a92ea This hasn't been implemented but there isn't much point.
		// It would make a empty object file if no files found.
		return;
	}

	for (uint8 first_time = 1; first_time || FindNextFile(hFindFile, &findFileData);){
		first_time = 0;

		RCT2_GLOBAL(0x9ABD98, HANDLE) = hFindFile;
		
		file_count++;
		// update progress bar. 
		eax = (file_count << 8) / ((RCT2_GLOBAL(0xF42B94, uint32) & 0xFFFFFF) + 1);



		if ((eax & 0xFF) != RCT2_GLOBAL(0xF42BD8, uint8)){
			RCT2_GLOBAL(0xF42BD8, uint8) = eax & 0xFF;
			// update progress bar
		}

		if ((installed_buffer_size - current_item_offset) <= 2842){
			installed_buffer_size += 0x1000;
			RCT2_GLOBAL(RCT2_ADDRESS_INSTALLED_OBJECT_LIST, void*) = rct2_realloc(RCT2_GLOBAL(RCT2_ADDRESS_INSTALLED_OBJECT_LIST, void*), installed_buffer_size);
			if (RCT2_GLOBAL(RCT2_ADDRESS_INSTALLED_OBJECT_LIST, int) == -1){
				RCT2_CALLPROC_X(0x006E3838, 0x343, 0xC5A, 0, 0, 0, 0, 0);
				return;
			}
		}

		char path[260];
		subsitute_path(path, RCT2_ADDRESS(RCT2_ADDRESS_OBJECT_DATA_PATH, char), findFileData.cFileName);

		FILE *obj_file = fopen(path, "rb");
		if (obj_file == NULL){
			continue;
		}

		rct_object_entry* entry = RCT2_ADDRESS(0xF42B74, rct_object_entry);
		if (fread(entry, sizeof(rct_object_entry), 1, obj_file) != 1){
			fclose(obj_file);
			continue;
		}
		fclose(obj_file);

		RCT2_GLOBAL(0xF42BC4, uint32) = current_item_offset;

		uint8* installed_entry_pointer = RCT2_GLOBAL(RCT2_ADDRESS_INSTALLED_OBJECT_LIST, uint8*) + current_item_offset;

		memcpy(installed_entry_pointer, entry, sizeof(rct_object_entry));
		installed_entry_pointer += sizeof(rct_object_entry);

		strcpy(installed_entry_pointer, findFileData.cFileName);
		while (*installed_entry_pointer++);

		*((sint32*)installed_entry_pointer) = -1;
		*(installed_entry_pointer + 4) = 0;
		*((sint32*)(installed_entry_pointer + 5)) = 0;
		*((uint16*)(installed_entry_pointer + 9)) = 0;
		*((uint32*)(installed_entry_pointer + 11)) = 0;

		RCT2_GLOBAL(0x9ADAF0, uint32) = 0xF26E;

		RCT2_GLOBAL(RCT2_ADDRESS_OBJECT_LIST_NO_ITEMS, uint32)++;

		// This is a variable used by object_load to decide if it should
		// use object_paint on the entry.
		RCT2_GLOBAL(0x9ADAFD, uint8) = 1;

		// Probably used by object paint.
		RCT2_GLOBAL(0x9ADAF4, uint32) = 0xF42BDB;

		int chunk_size;
		if (!object_load(-1, entry, &chunk_size)){
			RCT2_GLOBAL(0x9ADAF4, sint32) = -1;
			RCT2_GLOBAL(0x9ADAFD, uint8) = 0;
			RCT2_GLOBAL(RCT2_ADDRESS_OBJECT_LIST_NO_ITEMS, uint32)--;
			continue;
		}
		// See above note
		RCT2_GLOBAL(0x9ADAF4, sint32) = -1;
		RCT2_GLOBAL(0x9ADAFD, uint8) = 0;

		if ((entry->flags & 0xF0) == 0x80){
			RCT2_GLOBAL(0xF42B70, uint32)++;
			if (RCT2_GLOBAL(0xF42B70, uint32) > 772){
				RCT2_GLOBAL(0xF42B70, uint32)--;
				RCT2_GLOBAL(RCT2_ADDRESS_OBJECT_LIST_NO_ITEMS, uint32)--;
				continue;
			}
		}
		*((sint32*)installed_entry_pointer) = chunk_size;
		installed_entry_pointer += 4;

		uint8* chunk = RCT2_GLOBAL(RCT2_ADDRESS_CURR_OBJECT_CHUNK_POINTER, uint8*); // Loaded in object_load

		// When made of two parts i.e Wooden Roller Coaster (Dream Woodie Cars);
		if ((entry->flags & 0xF) == 0 && !(*((uint32*)(chunk + 8)) & 0x1000)){
			rct_string_id obj_string = chunk[12];
			if (obj_string == 0xFF){
				obj_string = chunk[13];
				if (obj_string == 0xFF){
					obj_string = chunk[14];
				}
			}

			obj_string += 2;
			format_string(installed_entry_pointer, obj_string, 0);
			strcat(installed_entry_pointer, "\t (");
			strcat(installed_entry_pointer, language_get_string(RCT2_GLOBAL(0xF42BBC, uint32)));
			strcat(installed_entry_pointer, ")");
			while (*installed_entry_pointer++);
		}
		else{
			strcpy(installed_entry_pointer, language_get_string(RCT2_GLOBAL(0xF42BBC, uint32)));
			while (*installed_entry_pointer++);
		}
		*((uint32*)installed_entry_pointer) = RCT2_GLOBAL(0x9ADAF0, uint32) - 0xF26E;
		installed_entry_pointer += 4;

		uint8* esi = RCT2_ADDRESS(0xF42BDB, uint8);
		int cl = *esi++;
		*installed_entry_pointer++ = cl;
		if (cl){
			memcpy(installed_entry_pointer, esi, cl*sizeof(rct_object_entry));
			installed_entry_pointer += cl*sizeof(rct_object_entry);
		}

		cl = *esi++;
		*installed_entry_pointer++ = cl;
		if (cl){
			memcpy(installed_entry_pointer, esi, cl*sizeof(rct_object_entry));
			installed_entry_pointer += cl*sizeof(rct_object_entry);
		}

		*((uint32*)installed_entry_pointer) = RCT2_GLOBAL(0xF433DD, uint32);
		installed_entry_pointer += 4;

		int size_of_object = installed_entry_pointer - RCT2_GLOBAL(RCT2_ADDRESS_INSTALLED_OBJECT_LIST, uint8*) - current_item_offset;

		object_unload(entry->flags & 0xF, (rct_object_entry_extended*)entry);

		// Return pointer to start of entry
		installed_entry_pointer -= size_of_object;

		uint8* copied_entry = RCT2_ADDRESS(0x140E9AC, uint8);

		size_of_object = object_copy(copied_entry, installed_entry_pointer);

		RCT2_GLOBAL(RCT2_ADDRESS_OBJECT_LIST_NO_ITEMS, uint32)--;
		copied_entry += sizeof(rct_object_entry);
		// Skip filename
		while (*copied_entry++);

		// Skip 
		copied_entry += 4;

		installed_entry_pointer = RCT2_GLOBAL(RCT2_ADDRESS_INSTALLED_OBJECT_LIST, uint8*);

		for (uint32 i = 0; i < RCT2_GLOBAL(RCT2_ADDRESS_OBJECT_LIST_NO_ITEMS, uint32); ++i){

			uint8* temp_installed_entry = installed_entry_pointer;
			temp_installed_entry += sizeof(rct_object_entry);

			// Skip filename
			while (*temp_installed_entry++);

			// Skip 
			temp_installed_entry += 4;

			if (strcmp(temp_installed_entry, copied_entry) <= 0)break;

			installed_entry_pointer = (uint8*)(object_get_next((rct_object_entry*)installed_entry_pointer));
		}

		// Difference to new location
		int no_bytes_to_move = RCT2_GLOBAL(RCT2_ADDRESS_INSTALLED_OBJECT_LIST, uint8*) + current_item_offset - installed_entry_pointer;

		uint8* curr_location = installed_entry_pointer;
		uint8* move_location = installed_entry_pointer + size_of_object;

		if (no_bytes_to_move){
			memmove(move_location, curr_location, no_bytes_to_move);
		}

		copied_entry = RCT2_ADDRESS(0x140E9AC, uint8);
		memcpy(installed_entry_pointer, copied_entry, size_of_object);
		current_item_offset += size_of_object;
		RCT2_GLOBAL(RCT2_ADDRESS_OBJECT_LIST_NO_ITEMS, uint32)++;
	}
コード例 #23
0
ファイル: Park.cpp プロジェクト: Gymnasiast/OpenRCT2
/**
 *
 *  rct2: 0x00667132
 */
void park_init()
{
    sint32 i;

    gUnk13CA740 = 0;
    gParkName = STR_UNNAMED_PARK;
    gStaffHandymanColour = COLOUR_BRIGHT_RED;
    gStaffMechanicColour = COLOUR_LIGHT_BLUE;
    gStaffSecurityColour = COLOUR_YELLOW;
    gNumGuestsInPark = 0;
    gNumGuestsInParkLastWeek = 0;
    gNumGuestsHeadingForPark = 0;
    gGuestChangeModifier = 0;
    gParkRating = 0;
    _guestGenerationProbability = 0;
    gTotalRideValueForMoney = 0;
    gResearchLastItem.rawValue = RESEARCHED_ITEMS_SEPARATOR;

    for (i = 0; i < 20; i++)
        gMarketingCampaignDaysLeft[i] = 0;

    research_reset_items();
    finance_init();

    set_every_ride_type_not_invented();

    set_all_scenery_items_invented();

    gParkEntranceFee = MONEY(10, 00);

    for (auto &peepSpawn : gPeepSpawns)
    {
        peepSpawn.x = PEEP_SPAWN_UNDEFINED;
    }

    gResearchPriorities =
        (1 << RESEARCH_CATEGORY_TRANSPORT) |
        (1 << RESEARCH_CATEGORY_GENTLE) |
        (1 << RESEARCH_CATEGORY_ROLLERCOASTER) |
        (1 << RESEARCH_CATEGORY_THRILL) |
        (1 << RESEARCH_CATEGORY_WATER) |
        (1 << RESEARCH_CATEGORY_SHOP) |
        (1 << RESEARCH_CATEGORY_SCENERY_GROUP);
    gResearchFundingLevel = RESEARCH_FUNDING_NORMAL;

    gGuestInitialCash = MONEY(50,00); // Cash per guest (average)
    gGuestInitialHappiness = calculate_guest_initial_happiness(50); // 50%
    gGuestInitialHunger = 200;
    gGuestInitialThirst = 200;
    gScenarioObjectiveType = OBJECTIVE_GUESTS_BY;
    gScenarioObjectiveYear = 4;
    gScenarioObjectiveNumGuests = 1000;
    gLandPrice = MONEY(90, 00);
    gConstructionRightsPrice = MONEY(40,00);
    gParkFlags = PARK_FLAGS_NO_MONEY | PARK_FLAGS_SHOW_REAL_GUEST_NAMES;
    park_reset_history();
    finance_reset_history();
    award_reset();

    gS6Info.name[0] = '\0';
    format_string(gS6Info.details, 256, STR_NO_DETAILS_YET, nullptr);
}
コード例 #24
0
ファイル: window_impl_x.cpp プロジェクト: 4og/schism
window::window_impl::window_impl(const display_cptr&      in_display,
                                 const ::Window           in_parent,
                                 const std::string&       in_title,
                                 const math::vec2i&       in_position,
                                 const math::vec2ui&      in_size,
                                 const format_desc&       in_sf)
  : surface::surface_impl(),
    _display(in_display->_impl->_display),
    _glx_extensions(in_display->_impl->_glx_extensions)
{
    try {
        if (channel_count(in_sf._color_format) < 3) {
            std::ostringstream s;
            s << "window::window_impl::window_impl() <xlib>: "
              << "window pixel format must contain RGB or RGBA color format "
              << "(requested: " << format_string(in_sf._color_format) << ").";
            //err() << log::fatal << s.str() << log::end;
            throw(std::runtime_error(s.str()));
        }

        std::stringstream fbc_err;
        _fb_config = util::framebuffer_config_selector::choose(in_display->_impl->_display, in_sf,
                                                               util::framebuffer_config_selector::window_surface,
                                                               _glx_extensions, fbc_err);
        if (0 == _fb_config) {
            std::ostringstream s;
            s << "window::window_impl::window_impl() <xlib>: "
              << "unable to select framebuffer config: "
              << fbc_err.str();
            //err() << log::fatal << s.str() << log::end;
            throw(std::runtime_error(s.str()));
        }

        XVisualInfo* fb_visual = glXGetVisualFromFBConfig(in_display->_impl->_display, _fb_config);
        if (!fb_visual) {
            std::ostringstream s;
            s << "window::window_impl::window_impl() <xlib>: "
              << "unable to retrieve visual for framebuffer config " << _fb_config;
            //err() << log::fatal << s.str() << log::end;
            throw(std::runtime_error(s.str()));
        }

        XSetWindowAttributes wnd_attribs;
        Colormap             wnd_color_map = XCreateColormap(in_display->_impl->_display, RootWindow(in_display->_impl->_display, fb_visual->screen), fb_visual->visual, AllocNone);

        wnd_attribs.colormap          = wnd_color_map;
        wnd_attribs.background_pixmap = None;
        wnd_attribs.border_pixel      = 0;
        wnd_attribs.event_mask        = StructureNotifyMask;

        ::Window parent_wnd = RootWindow(in_display->_impl->_display, fb_visual->screen);
        if (0 != in_parent) {
            parent_wnd = in_parent;
        }

        _window_handle = ::XCreateWindow(in_display->_impl->_display, parent_wnd,
                                         in_position.x, in_position.y, in_size.x, in_size.y, 0,
                                         fb_visual->depth, InputOutput, fb_visual->visual,
                                         CWColormap, &wnd_attribs);
        if (!_window_handle) {
            std::ostringstream s;
            s << "window::window_impl::window_impl() <xlib>: "
              << "failed to create window.";
            //err() << log::fatal << s.str() << log::end;
            throw(std::runtime_error(s.str()));
        }

        _glx_window_handle = ::glXCreateWindow(in_display->_impl->_display, _fb_config, _window_handle, 0);

        if (!_glx_window_handle) {
            std::ostringstream s;
            s << "window::window_impl::window_impl() <xlib>: "
              << "failed to create glx window handle.";
            //err() << log::fatal << s.str() << log::end;
            throw(std::runtime_error(s.str()));
        }

        // set the drawable of the surface
        _drawable = _glx_window_handle;

        XFree(fb_visual);

        XStoreName(in_display->_impl->_display, _window_handle, in_title.c_str());
    }
    catch (...) {
        cleanup();
        throw;
    }
}
コード例 #25
0
ファイル: event.cpp プロジェクト: Aulos/fish-shell
/*
    Give a more condensed description of \c event compared to \c event_get_desc.
    It includes what function will fire if the \c event is an event handler.
 */
static wcstring event_desc_compact(const event_t &event)
{
    wcstring res;
    wchar_t const *temp;
    int sig;
    switch (event.type)
    {
        case EVENT_ANY:
            res = L"EVENT_ANY";
            break;
        case EVENT_VARIABLE:
            if (event.str_param1.c_str())
            {
                res = format_string(L"EVENT_VARIABLE($%ls)", event.str_param1.c_str());
            }
            else
            {
                res = L"EVENT_VARIABLE([any])";
            }
            break;
        case EVENT_SIGNAL:
            sig = event.param1.signal;
            if (sig == EVENT_ANY_SIGNAL)
            {
                temp = L"[all signals]";
            }
            else if (sig == 0)
            {
                temp = L"not set";
            }
            else
            {
                temp = sig2wcs(sig);
            }
            res = format_string(L"EVENT_SIGNAL(%ls)", temp);
            break;
        case EVENT_EXIT:
            if (event.param1.pid == EVENT_ANY_PID)
            {
                res = wcstring(L"EVENT_EXIT([all child processes])");
            }
            else if (event.param1.pid > 0)
            {
                res = format_string(L"EVENT_EXIT(pid %d)", event.param1.pid);
            }
            else
            {
                job_t *j = job_get_from_pid(-event.param1.pid);
                if (j)
                    res = format_string(L"EVENT_EXIT(jobid %d: \"%ls\")", j->job_id, j->command_wcstr());
                else
                    res = format_string(L"EVENT_EXIT(pgid %d)", -event.param1.pid);
            }
            break;
        case EVENT_JOB_ID:
        {
            job_t *j = job_get(event.param1.job_id);
            if (j)
                res = format_string(L"EVENT_JOB_ID(job %d: \"%ls\")", j->job_id, j->command_wcstr());
            else
                res = format_string(L"EVENT_JOB_ID(jobid %d)", event.param1.job_id);
            break;
        }
        case EVENT_GENERIC:
            res = format_string(L"EVENT_GENERIC(%ls)", event.str_param1.c_str());
            break;
        default:
            res = format_string(L"unknown/illegal event(%x)", event.type);
    }
    if (event.function_name.size())
    {
        return format_string(L"%ls: \"%ls\"", res.c_str(), event.function_name.c_str());
    }
    else
    {
        return res;
    }
}
コード例 #26
0
ファイル: App.cpp プロジェクト: DarkMagicCK/UKN
    void AppLauncher::doCreate() {
        mist_assert(mInited);
        
		GraphicDevice& graphic_device = Context::Instance().getGraphicFactory().getGraphicDevice();
        	
		try {
			mMainWindow = graphic_device.createRenderWindow(mName, Context::Instance().getCfg().render_cfg);
		} catch(mist::Exception& e) {
			mist::MessageBox::Show(e.what(),
								   L"Error",
								   mist::MBB_OK | mist::MBO_IconError);
		}
        if(!mMainWindow)
            return terminate();
        
        mMainWindow->onClose() += Bind(this, &AppLauncher::onWindowClose);
        
        // log basic information
        Logger::Instance().setFeature(LF_PrependRunningTime, false);
        
        log_info(format_string("Project Unknown %d.%d Rev %d", 
                               UKN_VERSION_MAJOR,
                               UKN_VERSION_MINOR,
                               UKN_VERSION_REV));
        log_info(SystemInformation::GetOSVersion());
        log_info(format_string("CPU Speed: %d mhz", 
                               SystemInformation::GetProcessorSpeed()));
        log_info(format_string("Memory Size: %d kb", SystemInformation::GetMemorySize() / 1024));
        
        CpuInfo cpuinfo;
        log_info(format_string("CPU: %s, %s, Cores: %d Threads: %d", 
                               cpuinfo.getCPUString().c_str(),
                               cpuinfo.getCPUBrandString().c_str(),
                               cpuinfo.getNumCores(),
                               cpuinfo.getNumHWThreads()));
      
        
        log_info(graphic_device.description());
        
        GraphicDeviceCaps caps;
        graphic_device.fillGraphicCaps(caps);
        log_info(format_string("Graphic Device Caps:\n\tMaxTextureSize:\t(%d, %d)\n\tMaxCubeMapSize:\t%d\n\tMaxIndices:\t%d\n\tMaxVertices:\t%d\n\tMaxPixelTextureUnits:\t%d\n\tMaxVertexTextureUnits:\t%d\n",
                               caps.max_texture_width,
                               caps.max_texture_height,
                               caps.max_texture_cube_map_size,
                               caps.max_indices,
                               caps.max_vertices,
                               caps.max_pixel_texture_units,
                               caps.max_vertex_texture_units));
        
        Logger::Instance().setFeature(LF_PrependRunningTime, true);

        // setup default rendering states

        BlendStateObject::InitializeBuildInStates();
        RasterizerStateObject::InitializeBuildInStates();
        SamplerStateObject::InitializeBuildInStates();
        DepthStencilStateObject::InitializeBuildInStates();

        graphic_device.setBlendState(BlendStateObject::BlendOff());
        graphic_device.setRasterizerState(RasterizerStateObject::CullCounterClockwise());
        graphic_device.setSamplerState(SamplerStateObject::LinearClamp());
        graphic_device.setDepthStencilState(DepthStencilStateObject::Default());

    }
コード例 #27
0
void t_quest_log_window::create_quests_windows()
{
    t_screen_rect           rect;
    t_screen_point          text_background_offset;
    t_screen_point          background_offset;
    t_screen_point          mini_map_offset;
    t_screen_point          frame_offset;
    t_screen_point          origin(0,0);
    t_screen_point          point;
    t_window_ptr            window_ptr;
    t_text_window*          text_window_ptr;
    t_bitmap_layer const*   layer;
    t_bitmap_layer*         exit_marker = m_bitmaps_ptr->find( "marker" );
    std::string             name;
    int i;

    rect = exit_marker->get_rect();
    exit_marker->offset( -rect.top_left() );

    t_bitmap_layer const* text_background = m_bitmaps_ptr->find( "text_background" );
    background_offset = text_background->get_rect().top_left() -
                        m_bitmaps_ptr->find( "quest_1" )->get_rect().top_left();
    background_offset -= m_bitmaps_ptr->find( "text_background" )->get_rect().top_left();

    text_background_offset = m_bitmaps_ptr->find( "quest_text" )->get_rect().top_left() -
                             m_bitmaps_ptr->find( "quest_1" )->get_rect().top_left();

    layer = m_bitmaps_ptr->find( "frame" );
    m_map_frame = new t_bitmap_layer_window( layer, t_screen_point(0, 0), this );
    m_map_frame->set_visible( false );

    frame_offset = layer->get_rect().top_left() -
                   m_bitmaps_ptr->find( "quest_1" )->get_rect().top_left();
    mini_map_offset = m_bitmaps_ptr->find( "mini_map" )->get_rect().top_left() -
                      m_bitmaps_ptr->find( "quest_1" )->get_rect().top_left();

    i=0;
    while ((i<m_data.size()) && (i<k_max_windows))
    {
        i++;
        // Create background layer for text window.
        name = format_string( "quest_%i", i );
        origin = m_bitmaps_ptr->find( name )->get_rect().top_left();
        point = origin + background_offset;
        window_ptr = new t_bitmap_layer_window( text_background, point, this );

        // Create text window.
        point = origin + text_background_offset;

        rect = m_bitmaps_ptr->find( "quest_text" )->get_rect();
        rect -= m_bitmaps_ptr->find( "quest_text" )->get_rect().top_left();
        rect += point;

        text_window_ptr = new t_text_window( get_font( 20 ), rect, this, "", t_pixel_24(0,0,0) );
        text_window_ptr->set_center_horizontal();

        m_text_window_list.push_back( text_window_ptr );

        // Frame points.
        t_screen_point mini_map_point;
        t_screen_point frame_point;

        mini_map_point = origin + mini_map_offset;
        frame_point = origin + frame_offset;

        // Create button holder for mini-map.
        t_button *      map_button_ptr;
        map_button_ptr = new t_button( mini_map_point, this );

        // Create mini-map.
        t_center_map_window *   mini_map_ptr;

        rect = m_bitmaps_ptr->find( "mini_map" )->get_rect();
        rect -= rect.top_left();
        mini_map_ptr = new t_center_map_window( *m_map, rect, m_frame->get_map_window(),
                                                map_button_ptr );

        map_button_ptr->enable( true );
        map_button_ptr->update_size();
        map_button_ptr->set_click_handler( add_2nd_argument( bound_handler( *this, &t_quest_log_window::mini_map_clicked ), (i - 1)));
        m_map_button_list.push_back( map_button_ptr );
        m_mini_map_list.push_back( mini_map_ptr );

        // Frame window.
        layer = m_bitmaps_ptr->find( "frame" );
        window_ptr = new t_bitmap_layer_window( layer, frame_point-layer->get_rect().top_left(), this );
        //m_screen_frame_points.push_back( frame_point );

        // Create teleporter exit marker.
        window_ptr = new t_bitmap_layer_window( exit_marker, t_screen_point(0,0), mini_map_ptr );
        m_marker_window_list.push_back ( window_ptr );
    }

    // Create scrollbar.
    if ( m_data.size() > k_max_windows )
    {
        int scrollbar_limit = 0;
        scrollbar_limit = m_data.size() - k_max_windows;

        rect = m_bitmaps_ptr->find( "scrollbar" )->get_rect();
        m_scrollbar = new t_scrollbar( rect.top_left(), rect.height(), this, 0, 0, true );
        m_scrollbar->set_position( 0 );
        m_scrollbar->set_handler( bound_handler( *this, &t_quest_log_window::scrollbar_move));
        m_scrollbar->set_limits( 0, scrollbar_limit );
    }

    m_current_quest_index = 0;
}
コード例 #28
0
string resolve_express_http(const string express) {
    string result;
    split_result split(split_string(express,find_string(express,";")));

    if (split.second.empty())
        return split.first;

    string format_string(split.first);
    left_move_string(split.second,1);
    string arg_string(split.second);
    split=split_string(split.second,find_string(split.second,","));
    arg_list list;

    while (!split.second.empty()) {
        list.push_back(split.first);
        left_move_string(split.second,1);
        split=split_string(split.second,find_string(split.second,","));
    }
    list.push_back(split.first);

    string element;
    string element_name,element_value;
    unsigned int arg_index=0;
    split=split_string(format_string,find_string(format_string,","));

    while (!split.second.empty()) {
        element=split.first;
        split_result element_split(split_string(element,find_string(element,":")));
        left_move_string(element_split.second,1);
        element_name=element_split.first;
        element_value=element_split.second;

        if (-1!=find_string(element_value,"%")) {
            left_move_string(element_value,find_string(element_value,"%")+1);//  TIPS : There is no Get Type ..
            //  But I dont want to use it ..
            element_value=list[arg_index];
            ++arg_index;
        }
        result+=element_name;
        result+=":";
        result+=element_value;
        result+="\r\n";
        left_move_string(split.second,1);
        split=split_string(split.second,find_string(split.second,","));
    }
    split_result element_split(split_string(split.first,find_string(split.first,":")));
    left_move_string(element_split.second,1);
    element_name=element_split.first;
    element_value=element_split.second;

    if (-1!=find_string(element_value,"%")) {
        left_move_string(element_value,find_string(element_value,"%")+1);//  TIPS : There is no Get Type ..
        //  But I dont want to use it ..
        element_value=list[arg_index];
        ++arg_index;
    }
    result+=element_name;
    result+=":";
    result+=element_value;
    result+="\r\n\r\n";

    return result;
}
コード例 #29
0
ファイル: xplist.c プロジェクト: EchoLiao/libplist
static void node_to_xml(node_t* node, void *xml_struct)
{
    struct xml_node *xstruct = NULL;
    plist_data_t node_data = NULL;

    xmlNodePtr child_node = NULL;
    char isStruct = FALSE;
    char isUIDNode = FALSE;

    const xmlChar *tag = NULL;
    char *val = NULL;

    //for base64
    char *valtmp = NULL;

    uint32_t i = 0;

    if (!node)
        return;

    xstruct = (struct xml_node *) xml_struct;
    node_data = plist_get_data(node);

    switch (node_data->type)
    {
    case PLIST_BOOLEAN:
    {
        if (node_data->boolval)
            tag = XPLIST_TRUE;
        else
            tag = XPLIST_FALSE;
    }
    break;

    case PLIST_UINT:
        tag = XPLIST_INT;
        val = (char*)malloc(64);
        if (node_data->length == 16) {
	        (void)snprintf(val, 64, "%"PRIu64, node_data->intval);
	} else {
	        (void)snprintf(val, 64, "%"PRIi64, node_data->intval);
	}
        break;

    case PLIST_REAL:
        tag = XPLIST_REAL;
        val = (char*)malloc(64);
        (void)snprintf(val, 64, "%f", node_data->realval);
        break;

    case PLIST_STRING:
        tag = XPLIST_STRING;
        val = strdup((char*) node_data->strval);
        break;

    case PLIST_KEY:
        tag = XPLIST_KEY;
        val = strdup((char*) node_data->strval);
        break;

    case PLIST_DATA:
        tag = XPLIST_DATA;
        if (node_data->length)
        {
            size_t len = node_data->length;
            valtmp = base64encode(node_data->buff, &len);
            val = format_string(valtmp, len, 68, xstruct->depth);
            free(valtmp);
        }
        break;
    case PLIST_ARRAY:
        tag = XPLIST_ARRAY;
        isStruct = TRUE;
        break;
    case PLIST_DICT:
        tag = XPLIST_DICT;
        isStruct = TRUE;
        break;
    case PLIST_DATE:
        tag = XPLIST_DATE;
        {
            time_t timev = (time_t)node_data->timeval.tv_sec + MAC_EPOCH;
            struct tm *btime = gmtime(&timev);
            if (btime) {
                val = (char*)malloc(24);
                memset(val, 0, 24);
                if (strftime(val, 24, "%Y-%m-%dT%H:%M:%SZ", btime) <= 0) {
                    free (val);
                    val = NULL;
                }
            }
        }
        break;
    case PLIST_UID:
        // special case for keyed encoding
        tag = XPLIST_DICT;
        isStruct = TRUE;
        isUIDNode = TRUE;
        node_data->type = PLIST_DICT;
        node_attach(node, new_key_node("CF$UID"));
        node_attach(node, new_uint_node(node_data->intval));
        break;
    default:
        break;
    }

    for (i = 0; i < xstruct->depth; i++)
    {
        xmlNodeAddContent(xstruct->xml, BAD_CAST("\t"));
    }
    if (node_data->type == PLIST_STRING || node_data->type == PLIST_KEY) {
        /* make sure we convert the following predefined xml entities */
        /* < = &lt; > = &gt; ' = &apos; " = &quot; & = &amp; */
        child_node = xmlNewTextChild(xstruct->xml, NULL, tag, BAD_CAST(val));
    } else
        child_node = xmlNewChild(xstruct->xml, NULL, tag, BAD_CAST(val));
    xmlNodeAddContent(xstruct->xml, BAD_CAST("\n"));
    if (val) {
        free(val);
    }

    //add return for structured types
    if (node_data->type == PLIST_ARRAY || node_data->type == PLIST_DICT)
        xmlNodeAddContent(child_node, BAD_CAST("\n"));

    //make sure we don't produce <data/> if it's empty
    if ((node_data->type == PLIST_DATA) && !val) {
        xmlNodeAddContent(child_node, BAD_CAST("\n"));
        for (i = 0; i < xstruct->depth; i++)
        {
            xmlNodeAddContent(child_node, BAD_CAST("\t"));
        }
    }

    if (isStruct)
    {
        struct xml_node child = { child_node, xstruct->depth + 1 };
        node_iterator_t *ni = node_iterator_create(node->children);
        node_t *ch;
        while ((ch = node_iterator_next(ni))) {
            node_to_xml(ch, &child);
        }
        node_iterator_destroy(ni);
    }
    //fix indent for structured types
    if (node_data->type == PLIST_ARRAY || node_data->type == PLIST_DICT)
    {

        for (i = 0; i < xstruct->depth; i++)
        {
            xmlNodeAddContent(child_node, BAD_CAST("\t"));
        }
    }
    if (isUIDNode)
    {
        unsigned int num = node_n_children(node);
        unsigned int j;
        for (j = num; j > 0; j--) {
            node_t* ch = node_nth_child(node, j-1);
            node_detach(node, ch);
            node_destroy(ch);
        }
        node_data->type = PLIST_UID;
    }

    return;
}
コード例 #30
0
// Pass in ratio... (for purchases)
void t_dialog_marketplace::init_dialog( t_window* parent, t_adventure_frame* frame, std::string const& name_text, std::string const& intro_text, 
                int market_efficiency_ratio )
{

	t_bitmap_layer const*   layer;
	//t_window *              window;
	t_window *              background_window;
	t_screen_point          origin(0,0);
	t_screen_point          point(0,0);
	t_screen_rect           rect;
	t_bitmap_group_ptr      material_bitmaps_ptr = k_large_material_bitmaps.get();
    int                     i;
	t_help_block const&     material_help = get_help_block( "material_display" );
	t_help_block const&		help = get_help_block( "marketplace" );

	m_player_ptr = &frame->get_map()->get_player();
	m_player_funds = m_player_ptr->get_funds()[k_gold];
	m_bitmaps_ptr = k_marketplace_bitmaps.get();
    m_market_efficiency_ratio = market_efficiency_ratio;

	layer = m_bitmaps_ptr->find( "background" );
	background_window = new t_bitmap_layer_window( layer, origin, this );

	layer = m_bitmaps_ptr->find( "frame" );
   	rect = layer->get_rect();
	m_player_frame = new t_bitmap_layer_window( layer, -rect.top_left(), this );
	m_player_frame->set_visible( false );
	m_player_frame->update_size();

	layer = m_bitmaps_ptr->find( "frame" );
   	rect = layer->get_rect();
	m_market_frame = new t_bitmap_layer_window( layer, -rect.top_left(), this );
	m_market_frame->set_visible( false );
	m_market_frame->update_size();

    // Find wood frame (first item) - get diff for frame.
	t_screen_point  frame_diff(0,0);

    point = m_bitmaps_ptr->find( "wood_icon" )->get_rect().top_left();
    frame_diff = (point - rect.top_left());

    /*
    ** Materials:
    */
	std::string     material_icon_text;

	for (i=0; i<k_material_count; i++)
    {
        // Player's material.
		material_icon_text = format_string ( "%s_icon", k_material_keyword[i] );
	    rect = m_bitmaps_ptr->find( material_icon_text )->get_rect();
        m_player_button[i] = create_marketplace_player_button ( rect.top_left(), background_window, i,
                        k_material_keyword[i], help );
	
        m_player_button[i]->set_click_handler( add_2nd_argument( bound_handler( *this, &t_dialog_marketplace::player_material_clicked ), i));
	    m_player_frame_locations.push_back ( rect.top_left() - frame_diff );

        // Market material.
		material_icon_text = format_string ( "%s_icon_2", k_material_keyword[i] );
	    rect = m_bitmaps_ptr->find( material_icon_text )->get_rect();
        m_market_button[i] = create_marketplace_player_button ( rect.top_left(), background_window, i,
                        format_string( "%s_%s", "available", k_material_keyword[i] ), help );
	
        m_market_button[i]->set_click_handler( add_2nd_argument( bound_handler( *this, &t_dialog_marketplace::market_material_clicked ), i));
	    m_market_frame_locations.push_back ( rect.top_left() - frame_diff );
    }

    /*
    ** Create buttons.
    */
	t_button            *button_ptr;
	t_button_handler    button_handler;

	rect = m_bitmaps_ptr->find( "close_button" )->get_rect();
	button_ptr = new t_button( g_ok_button.get(), rect.top_left(), this );
	button_ptr->set_click_handler( bound_handler( *this, &t_dialog_marketplace::close_click ));
	set_help( button_ptr, help, "ok" );

    /*
    ** Add buy button.
    */
	point = m_bitmaps_ptr->find( "sell_button" )->get_rect().top_left() + origin;
	m_buy_button = new t_button( k_buy_button.get(), point, this );
	button_handler = bound_handler( *this, &t_dialog_marketplace::buy_clicked );
	m_buy_button->set_click_handler( button_handler );
	set_help( m_buy_button, help, "purchase" );
	m_buy_button->enable( false );

    // Add max button.
	point = m_bitmaps_ptr->find( "max_button" )->get_rect().top_left() + origin;
	m_max_button = new t_button( g_max_button.get(), point, this );
	button_handler = bound_handler( *this, &t_dialog_marketplace::max_clicked );
	m_max_button->set_click_handler( button_handler );
	set_help( m_max_button, help, "maximum" );
	m_max_button->enable( false );

    /*
    ** Add scrollbar.
    */
	layer = m_bitmaps_ptr->find( "scrollbar" );
	rect  = layer->get_rect();

	m_scrollbar = new t_scrollbar( rect.top_left(), rect.width(), this, 0, 0, false );
	m_scrollbar->set_handler( bound_handler( *this, &t_dialog_marketplace::scrollbar_move));
	m_scrollbar->set_position( 0 );
	m_scrollbar->set_limits( 0, 0 );

    /*
    ** Text windows.
    */
	t_text_window* text_window_ptr;

    // Title.
	rect = m_bitmaps_ptr->find( "title" )->get_rect() + origin;
	text_window_ptr = new t_text_window( get_font( 20 ), rect, this, name_text, t_pixel_24(0,0,0));
	text_window_ptr->set_center_horizontal();
	text_window_ptr->set_drop_shadow( false );

    // Intro text.
	rect = m_bitmaps_ptr->find( "text" )->get_rect() + origin;
	text_window_ptr = new t_text_window( get_font( 20 ), rect, this, intro_text, t_pixel_24(0,0,0));
	text_window_ptr->set_center_horizontal();
	text_window_ptr->set_drop_shadow( false );

	std::string     material_text_box;
    
	for (i=0; i<k_material_count; i++)
    {
        // Player's side.  Kindgom amount.
		material_text_box = format_string ( "kingdom_%s", k_material_keyword[i] );
	    rect = m_bitmaps_ptr->find( material_text_box )->get_rect();
	    m_player_amount_text[i] = new t_text_window( get_font( 16 ), rect, this, "", t_pixel_24(0,0,0));
	    m_player_amount_text[i]->set_center_horizontal();
        
        // Market exchange text.
		material_text_box = format_string ( "%s_exchange", k_material_keyword[i] );
	    rect = m_bitmaps_ptr->find( material_text_box )->get_rect();
	    m_market_exchange_text[i] = new t_text_window( get_font( 16 ), rect, this, "", t_pixel_24(0,0,0));
	    m_market_exchange_text[i]->set_center_horizontal();

    }

    show_player_material_amount();

    // Player quantity text.
	rect = m_bitmaps_ptr->find( "qty_selling" )->get_rect() + origin;
	m_player_quantity_text = new t_text_window( get_font( rect.height() ), rect, this, "", t_pixel_24(0,0,0));
	m_player_quantity_text->set_center_horizontal();
	m_player_quantity_text->set_drop_shadow( false );

    // Market quantity text.
	rect = m_bitmaps_ptr->find( "exchange_rate" )->get_rect() + origin;
	m_market_quantity_text = new t_text_window( get_font( rect.height() ), rect, this, "", t_pixel_24(0,0,0));
	m_market_quantity_text->set_center_horizontal();
	m_market_quantity_text->set_drop_shadow( false );

    show_exchange_rates();

    /*
    ** Center the position and display the window.
    */
    t_screen_rect parent_rect = get_parent()->get_client_rect();
    
    rect = m_bitmaps_ptr->get_rect();
    rect += (parent_rect.size() - rect.size()) / 2;
    init( rect );

}