示例#1
0
LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam,
                            LPARAM lParam) {
    BrowserWindow* browser = 0;
    BOOL b = 0;
    WORD childEvent = 0;
    HWND childHandle = 0;
    HWND shellBrowserHandle = 0;

    switch (uMsg) {
        case WM_SIZE:
            browser = GetBrowserWindow(hwnd);
            if (browser) {
                browser->OnSize();
            } else {
                LOG_WARNING << "WindowProc(): event WM_SIZE: "
                               "could not fetch BrowserWindow";
            }
            break;
        case WM_CREATE:
            if (GetWindow(hwnd, GW_OWNER)) {
                browser = new BrowserWindow(hwnd, true);
            } else {
                browser = new BrowserWindow(hwnd, false);
            }
            StoreBrowserWindow(hwnd, browser);
            return 0;
        case WM_DESTROY:
            LOG_DEBUG << "WM_DESTROY";
            RemoveBrowserWindow(hwnd);
            if (g_browserWindows.empty()) {
                StopWebServer();
#ifdef DEBUG
                // Debugging mongoose, see InitializeLogging().
                printf("----------------------------------------");
                printf("----------------------------------------\n");
#endif
                // Cannot call PostQuitMessage as cookies won't be flushed to disk
                // if application is closed immediately. See comment #2:
                // https://code.google.com/p/phpdesktop/issues/detail?id=146
                // I suppose that this PostQuitMessage was added here so that
                // application is forced to exit cleanly in case Mongoose
                // web server hanged while stopping it, as I recall such case.
                // -------------------
                // PostQuitMessage(0);
                // -------------------
            }
            return 0;
        case WM_GETMINMAXINFO:
            browser = GetBrowserWindow(hwnd);
            if (browser) {
                browser->OnGetMinMaxInfo(uMsg, wParam, lParam);
                return 0;
            } else {
                // GetMinMaxInfo may fail during window creation, so
                // log severity is only DEBUG.
                LOG_DEBUG << "WindowProc(): event WM_GETMINMAXINFO: "
                             "could not fetch BrowserWindow";
            }
            break;
        case WM_SETFOCUS:
            browser = GetBrowserWindow(hwnd);
            if (browser) {
                browser->SetFocus();
                return 0;
            } else {
                LOG_DEBUG << "WindowProc(): event WM_SETFOCUS: "
                             "could not fetch BrowserWindow";
            }
            break;
        case WM_ERASEBKGND:
            browser = GetBrowserWindow(hwnd);
            if (browser && browser->GetCefBrowser().get()) {
                CefWindowHandle hwnd = \
                        browser->GetCefBrowser()->GetHost()->GetWindowHandle();
                if (hwnd) {
                    // Dont erase the background if the browser window has been loaded
                    // (this avoids flashing)
                    return 1;
                }
            }
            break;
    }
    return DefWindowProc(hwnd, uMsg, wParam, lParam);
}
示例#2
0
char_t Tokenizer::GetDelimiter(TokenRange range) const {
  // Symbols are sorted by their precedence, in decreasing order. While the most
  // common delimiters are underscore, space and dot, we give comma the priority
  // to handle the case where words are separated by ", ". Besides, we'll be
  // trimming whitespace later on.
  static const string_t kDelimiterTable = L",_ .-+;&|~";

  // Trim whitespace so that it doesn't interfere with our frequency analysis.
  // This proves useful for handling some edge cases, and it doesn't seem to
  // have any side effects.
  if (!TrimWhitespace(filename_, range))
    return L' ';

  static std::map<char_t, size_t> frequency;

  if (frequency.empty()) {
    // Initialize frequency map
    for (const auto& character : kDelimiterTable) {
      frequency.insert(std::make_pair(character, 0));
    }
  } else {
    // Reset frequency map
    for (auto& pair : frequency) {
      pair.second = 0;
    }
  }

  // Count all possible delimiters
  for (size_t i = range.offset; i < range.offset + range.size; i++) {
    const char_t character = filename_.at(i);
    if (IsAlphanumericChar(character))
      continue;
    if (frequency.find(character) == frequency.end())
      continue;
    frequency.at(character) += 1;
  }

  char_t delimiter = L'\0';

  for (const auto& pair : frequency) {
    if (pair.second == 0)
      continue;

    // Initialize delimiter at first iteration
    if (delimiter == L'\0') {
      delimiter = pair.first;
      continue;
    }

    int character_distance =
        static_cast<int>(kDelimiterTable.find(pair.first)) -
        static_cast<int>(kDelimiterTable.find(delimiter));
    // If the distance is negative, then the new delimiter has higher priority
    if (character_distance < 0) {
      delimiter = pair.first;
      continue;
    }

    // Even if the new delimiter has lower priority, it may be much more common
    float frequency_ratio = static_cast<float>(pair.second) /
                            static_cast<float>(frequency[delimiter]);
    // The constant value was chosen by trial and error. There should be room
    // for improvement.
    if (frequency_ratio / abs(character_distance) > 0.8f)
      delimiter = pair.first;
  }

  return delimiter;
}
示例#3
0
static guint32 internal_sp_svg_read_color(gchar const *str, gchar const **end_ptr, guint32 def)
{
    static std::map<string, unsigned long> colors;
    guint32 val = 0;

    if (str == NULL) return def;
    while ((*str <= ' ') && *str) str++;
    if (!*str) return def;

    if (str[0] == '#') {
        gint i;
        for (i = 1; str[i]; i++) {
            int hexval;
            if (str[i] >= '0' && str[i] <= '9')
                hexval = str[i] - '0';
            else if (str[i] >= 'A' && str[i] <= 'F')
                hexval = str[i] - 'A' + 10;
            else if (str[i] >= 'a' && str[i] <= 'f')
                hexval = str[i] - 'a' + 10;
            else
                break;
            val = (val << 4) + hexval;
        }
        /* handle #rgb case */
        if (i == 1 + 3) {
            val = ((val & 0xf00) << 8) |
                ((val & 0x0f0) << 4) |
                (val & 0x00f);
            val |= val << 4;
        } else if (i != 1 + 6) {
            /* must be either 3 or 6 digits. */
            return def;
        }
        if (end_ptr) {
            *end_ptr = str + i;
        }
    } else if (strneq(str, "rgb(", 4)) {
        bool hasp, hasd;
        gchar *s, *e;
        gdouble r, g, b;

        s = (gchar *) str + 4;
        hasp = false;
        hasd = false;

        r = g_ascii_strtod(s, &e);
        if (s == e) return def;
        s = e;
        if (*s == '%') {
            hasp = true;
            s += 1;
        } else {
            hasd = true;
        }
        while (*s && g_ascii_isspace(*s)) s += 1;
        if (*s != ',') return def;
        s += 1;
        while (*s && g_ascii_isspace(*s)) s += 1;
        g = g_ascii_strtod(s, &e);
        if (s == e) return def;
        s = e;
        if (*s == '%') {
            hasp = true;
            s += 1;
        } else {
            hasd = true;
        }
        while (*s && g_ascii_isspace(*s)) s += 1;
        if (*s != ',') return def;
        s += 1;
        while (*s && g_ascii_isspace(*s)) s += 1;
        b = g_ascii_strtod(s, &e);
        if (s == e) return def;
        s = e;
        if (*s == '%') {
            hasp = true;
            s += 1;
        } else {
            hasd = true;
        }
        while(*s && g_ascii_isspace(*s)) s += 1;
        if (*s != ')') {
            return def;
        }
        ++s;
        if (hasp && hasd) return def;
        if (hasp) {
            val = static_cast<guint>(floor(CLAMP(r, 0.0, 100.0) * 2.559999)) << 24;
            val |= (static_cast<guint>(floor(CLAMP(g, 0.0, 100.0) * 2.559999)) << 16);
            val |= (static_cast<guint>(floor(CLAMP(b, 0.0, 100.0) * 2.559999)) << 8);
        } else {
            val = static_cast<guint>(CLAMP(r, 0, 255)) << 24;
            val |= (static_cast<guint>(CLAMP(g, 0, 255)) << 16);
            val |= (static_cast<guint>(CLAMP(b, 0, 255)) << 8);
        }
        if (end_ptr) {
            *end_ptr = s;
        }
        return val;
    } else if (strneq(str, "hsl(", 4)) {

        gchar *ptr = (gchar *) str + 4;

        gchar *e; // ptr after read

        double h = g_ascii_strtod(ptr, &e); // Read h (0-360)
        if (ptr == e) return def; // Read failed
        ptr = e;

        while (*ptr && g_ascii_isspace(*ptr)) ptr += 1; // Remove any white space
        if (*ptr != ',') return def; // Need comma
        ptr += 1;
        while (*ptr && g_ascii_isspace(*ptr)) ptr += 1; // Remove any white space

        double s = g_ascii_strtod(ptr, &e); // Read s (percent)
        if (ptr == e) return def; // Read failed
        ptr = e;
        while (*ptr && g_ascii_isspace(*ptr)) ptr += 1; // Remove any white space
        if (*ptr != '%') return def; // Need %
        ptr += 1;

        while (*ptr && g_ascii_isspace(*ptr)) ptr += 1; // Remove any white space
        if (*ptr != ',') return def; // Need comma
        ptr += 1;
        while (*ptr && g_ascii_isspace(*ptr)) ptr += 1; // Remove any white space

        double l = g_ascii_strtod(ptr, &e); // Read l (percent)
        if (ptr == e) return def; // Read failed
        ptr = e;
        while (*ptr && g_ascii_isspace(*ptr)) ptr += 1; // Remove any white space
        if (*ptr != '%') return def; // Need %
        ptr += 1;

        if (end_ptr) {
            *end_ptr = ptr;
        }


        // Normalize to 0..1
        h /= 360.0;
        s /= 100.0;
        l /= 100.0;

        gfloat rgb[3];

        sp_color_hsl_to_rgb_floatv( rgb, h, s, l );

        val  =  static_cast<guint>(floor(CLAMP(rgb[0], 0.0, 1.0) * 255.9999)) << 24;
        val |= (static_cast<guint>(floor(CLAMP(rgb[1], 0.0, 1.0) * 255.9999)) << 16);
        val |= (static_cast<guint>(floor(CLAMP(rgb[2], 0.0, 1.0) * 255.9999)) << 8);
        return val;

    } else {
        gint i;
        if (colors.empty()) {
            colors = sp_svg_create_color_hash();
        }
        gchar c[32];
        for (i = 0; i < 31; i++) {
            if (str[i] == ';' || g_ascii_isspace(str[i])) {
                c[i] = '\0';
                break;
            }
            c[i] = g_ascii_tolower(str[i]);
            if (!str[i]) break;
        }
        c[31] = '\0';

        if (colors.count(string(c))) {
            val = colors[string(c)];
        }
        else {
            return def;
        }
        if (end_ptr) {
            *end_ptr = str + i;
        }
    }

    return (val << 8);
}
示例#4
0
CScript ParseScript(const std::string& s)
{
    CScript result;

    static std::map<std::string, opcodetype> mapOpNames;

    if (mapOpNames.empty())
    {
        for (int op = 0; op <= OP_NOP10; op++)
        {
            // Allow OP_RESERVED to get into mapOpNames
            if (op < OP_NOP && op != OP_RESERVED)
                continue;

            const char* name = GetOpName((opcodetype)op);
            if (strcmp(name, "OP_UNKNOWN") == 0)
                continue;
            std::string strName(name);
            mapOpNames[strName] = (opcodetype)op;
            // Convenience: OP_ADD and just ADD are both recognized:
            boost::algorithm::replace_first(strName, "OP_", "");
            mapOpNames[strName] = (opcodetype)op;
        }
    }

    std::vector<std::string> words;
    boost::algorithm::split(words, s, boost::algorithm::is_any_of(" \t\n"), boost::algorithm::token_compress_on);

    for (std::vector<std::string>::const_iterator w = words.begin(); w != words.end(); ++w)
    {
        if (w->empty())
        {
            // Empty string, ignore. (boost::split given '' will return one word)
        }
        else if (all(*w, boost::algorithm::is_digit()) ||
            (boost::algorithm::starts_with(*w, "-") && all(std::string(w->begin()+1, w->end()), boost::algorithm::is_digit())))
        {
            // Number
            int64_t n = atoi64(*w);
            result << n;
        }
        else if (boost::algorithm::starts_with(*w, "0x") && (w->begin()+2 != w->end()) && IsHex(std::string(w->begin()+2, w->end())))
        {
            // Raw hex data, inserted NOT pushed onto stack:
            std::vector<unsigned char> raw = ParseHex(std::string(w->begin()+2, w->end()));
            result.insert(result.end(), raw.begin(), raw.end());
        }
        else if (w->size() >= 2 && boost::algorithm::starts_with(*w, "'") && boost::algorithm::ends_with(*w, "'"))
        {
            // Single-quoted string, pushed as data. NOTE: this is poor-man's
            // parsing, spaces/tabs/newlines in single-quoted strings won't work.
            std::vector<unsigned char> value(w->begin()+1, w->end()-1);
            result << value;
        }
        else if (mapOpNames.count(*w))
        {
            // opcode, e.g. OP_ADD or ADD:
            result << mapOpNames[*w];
        }
        else
        {
            throw std::runtime_error("script parse error");
        }
    }

    return result;
}
示例#5
0
inline bool KerningTable::isEmpty() const
{
	return pairs.empty();
}
示例#6
0
文件: halo.cpp 项目: xyecs/wesnoth
void halo_impl::unrender(std::set<map_location> invalidated_locations)
{
    if(preferences::show_haloes() == false || haloes.empty()) {
        return;
    }
    //assert(invalidated_haloes.empty());

    // Remove expired haloes
    std::map<int, effect>::iterator itor = haloes.begin();
    for(; itor != haloes.end(); ++itor ) {
        if(itor->second.expired()) {
            deleted_haloes.insert(itor->first);
        }
    }

    // Add the haloes marked for deletion to the invalidation set
    std::set<int>::const_iterator set_itor = deleted_haloes.begin();
    for(; set_itor != deleted_haloes.end(); ++set_itor) {
        invalidated_haloes.insert(*set_itor);
        haloes.find(*set_itor)->second.add_overlay_location(invalidated_locations);
    }

    // Test the multi-frame haloes whether they need an update
    for(set_itor = changing_haloes.begin();
            set_itor != changing_haloes.end(); ++set_itor) {
        if(haloes.find(*set_itor)->second.need_update()) {
            invalidated_haloes.insert(*set_itor);
            haloes.find(*set_itor)->second.add_overlay_location(invalidated_locations);
        }
    }

    // Find all halo's in a the invalidated area
    size_t halo_count;

    // Repeat until set of haloes in the invalidated area didn't change
    // (including none found) or all existing haloes are found.
    do {
        halo_count = invalidated_haloes.size();
        for(itor = haloes.begin(); itor != haloes.end(); ++itor) {
            // Test all haloes not yet in the set
            // which match one of the locations
            if(invalidated_haloes.find(itor->first) == invalidated_haloes.end() &&
                    (itor->second.location_not_known() ||
                     itor->second.on_location(invalidated_locations))) {

                // If found, add all locations which the halo invalidates,
                // and add it to the set
                itor->second.add_overlay_location(invalidated_locations);
                invalidated_haloes.insert(itor->first);
            }
        }
    } while (halo_count != invalidated_haloes.size() && halo_count != haloes.size());

    if(halo_count == 0) {
        return;
    }

    // Render the haloes:
    // iterate through all the haloes and invalidate if in set
    for(std::map<int, effect>::reverse_iterator ritor = haloes.rbegin(); ritor != haloes.rend(); ++ritor) {
        if(invalidated_haloes.find(ritor->first) != invalidated_haloes.end()) {
            ritor->second.unrender();
        }
    }

    // Really delete the haloes marked for deletion
    for(set_itor = deleted_haloes.begin(); set_itor != deleted_haloes.end(); ++set_itor) {
        // It can happen a deleted halo hasn't been rendered yet, invalidate them as well
        new_haloes.erase(*set_itor);

        changing_haloes.erase(*set_itor);
        invalidated_haloes.erase(*set_itor);
        haloes.erase(*set_itor);
    }

    deleted_haloes.clear();
}
示例#7
0
void GD_API CreateObjectOnScene(RuntimeScene & scene, std::map <gd::String, std::vector<RuntimeObject*> *> pickedObjectLists, float positionX, float positionY, const gd::String & layer)
{
    if ( pickedObjectLists.empty() ) return;

    ::DoCreateObjectOnScene(scene, pickedObjectLists.begin()->first, pickedObjectLists, positionX, positionY, layer);
}
示例#8
0
        void UpdateAI(uint32 diff)
        {
            if (!UpdateVictim())
                return;

            events.Update(diff);

            if (Phase == 1)
            {
                while (uint32 eventId = events.GetEvent())
                {
                    switch (eventId)
                    {
                        case EVENT_WASTE:
                            DoSummon(NPC_WASTE, Pos[RAND(0, 3, 6, 9)]);
                            events.RepeatEvent(urand(2000, 5000));
                            break;
                        case EVENT_ABOMIN:
                            if (nAbomination < 8)
                            {
                                DoSummon(NPC_ABOMINATION, Pos[RAND(1, 4, 7, 10)]);
                                nAbomination++;
                                events.RepeatEvent(20000);
                            }
                            else
                                events.PopEvent();
                            break;
                        case EVENT_WEAVER:
                            if (nWeaver < 8)
                            {
                                DoSummon(NPC_WEAVER, Pos[RAND(0, 3, 6, 9)]);
                                nWeaver++;
                                events.RepeatEvent(25000);
                            }
                            else
                                events.PopEvent();
                            break;
                        case EVENT_TRIGGER:
                            if (GameObject* pKTTrigger = me->GetMap()->GetGameObject(KTTriggerGUID))
                                pKTTrigger->SetPhaseMask(2, true);
                            events.PopEvent();
                            break;
                        case EVENT_PHASE:
                            events.Reset();
                            Talk(SAY_AGGRO);
                            spawns.DespawnAll();
                            me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_DISABLE_MOVE | UNIT_FLAG_NOT_SELECTABLE);
                            me->CastStop();

                            DoStartMovement(me->getVictim());
                            events.ScheduleEvent(EVENT_BOLT, urand(5000, 10000));
                            events.ScheduleEvent(EVENT_NOVA, 15000);
                            events.ScheduleEvent(EVENT_DETONATE, urand(30000, 40000));
                            events.ScheduleEvent(EVENT_FISSURE, urand(10000, 30000));
                            events.ScheduleEvent(EVENT_BLAST, urand(60000, 120000));
                            if (GetDifficulty() == RAID_DIFFICULTY_25MAN_NORMAL)
                                events.ScheduleEvent(EVENT_CHAIN, urand(30000, 60000));
                            Phase = 2;
                            break;
                        default:
                            events.PopEvent();
                            break;
                    }
                }
            }
            else
            {
                //start phase 3 when we are 45% health
                if (Phase != 3)
                {
                    if (HealthBelowPct(45))
                    {
                        Phase = 3;
                        Talk(SAY_REQUEST_AID);
                        //here Lich King should respond to KelThuzad but I don't know which Creature to make talk
                        //so for now just make Kelthuzad says it.
                        Talk(SAY_ANSWER_REQUEST);

                        for (uint8 i = 0; i <= 3; ++i)
                        {
                            if (GameObject* pPortal = me->GetMap()->GetGameObject(PortalsGUID[i]))
                            {
                                if (pPortal->getLootState() == GO_READY)
                                    pPortal->UseDoorOrButton();
                            }
                        }
                    }
                }
                else if (nGuardiansOfIcecrownCount < RAID_MODE(2, 4))
                {
                    if (uiGuardiansOfIcecrownTimer <= diff)
                    {
                        /// @todo Add missing text
                        if (Creature* pGuardian = DoSummon(NPC_ICECROWN, Pos[RAND(2, 5, 8, 11)]))
                            pGuardian->SetFloatValue(UNIT_FIELD_COMBATREACH, 2);
                        ++nGuardiansOfIcecrownCount;
                        uiGuardiansOfIcecrownTimer = 5000;
                    }
                    else uiGuardiansOfIcecrownTimer -= diff;
                }

                if (me->HasUnitState(UNIT_STATE_CASTING))
                    return;

                if (uint32 eventId = events.GetEvent())
                {
                    switch (eventId)
                    {
                        case EVENT_BOLT:
                            DoCastVictim(RAID_MODE(SPELL_FROST_BOLT, H_SPELL_FROST_BOLT));
                            events.RepeatEvent(urand(5000, 10000));
                            break;
                        case EVENT_NOVA:
                            DoCastAOE(RAID_MODE(SPELL_FROST_BOLT_AOE, H_SPELL_FROST_BOLT_AOE));
                            events.RepeatEvent(urand(15000, 30000));
                            break;
                        case EVENT_CHAIN:
                        {
                            uint32 count = urand(1, 3);
                            for (uint8 i = 1; i <= count; i++)
                            {
                                Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 1, 200, true);
                                if (target && !target->isCharmed() && (chained.find(target->GetGUID()) == chained.end()))
                                {
                                    DoCast(target, SPELL_CHAINS_OF_KELTHUZAD);
                                    float scale = target->GetFloatValue(OBJECT_FIELD_SCALE_X);
                                    chained.insert(std::make_pair(target->GetGUID(), scale));
                                    target->SetObjectScale(scale * 2);
                                    events.ScheduleEvent(EVENT_CHAINED_SPELL, 2000); //core has 2000ms to set unit flag charm
                                }
                            }
                            if (!chained.empty())
                                Talk(SAY_CHAIN);
                            events.RepeatEvent(urand(100000, 180000));
                            break;
                        }
                        case EVENT_CHAINED_SPELL:
                        {
                            std::map<uint64, float>::iterator itr;
                            for (itr = chained.begin(); itr != chained.end();)
                            {
                                if (Unit* player = Unit::GetPlayer(*me, (*itr).first))
                                {
                                    if (!player->isCharmed())
                                    {
                                        player->SetObjectScale((*itr).second);
                                        std::map<uint64, float>::iterator next = itr;
                                        ++next;
                                        chained.erase(itr);
                                        itr = next;
                                        continue;
                                    }

                                    if (Unit* target = SelectTarget(SELECT_TARGET_TOPAGGRO, 0, NotCharmedTargetSelector()))
                                    {
                                        switch (player->getClass())
                                        {
                                            case CLASS_DRUID:
                                                if (urand(0, 1))
                                                    player->CastSpell(target, SPELL_MOONFIRE, false);
                                                else
                                                    player->CastSpell(me, SPELL_LIFEBLOOM, false);
                                                break;
                                            case CLASS_HUNTER:
                                                player->CastSpell(target, RAND(SPELL_MULTI_SHOT, SPELL_VOLLEY), false);
                                                break;
                                            case CLASS_MAGE:
                                                player->CastSpell(target, RAND(SPELL_FROST_FIREBOLT, SPELL_ARCANE_MISSILES), false);
                                                break;
                                            case CLASS_WARLOCK:
                                                player->CastSpell(target, RAND(SPELL_CURSE_OF_AGONY, SPELL_SHADOW_BOLT), true);
                                                break;
                                            case CLASS_WARRIOR:
                                                player->CastSpell(target, RAND(SPELL_BLADESTORM, SPELL_CLEAVE), false);
                                                break;
                                            case CLASS_PALADIN:
                                                if (urand(0, 1))
                                                    player->CastSpell(target, SPELL_HAMMER_OF_JUSTICE, false);
                                                else
                                                    player->CastSpell(me, SPELL_HOLY_SHOCK, false);
                                                break;
                                            case CLASS_PRIEST:
                                                if (urand(0, 1))
                                                    player->CastSpell(target, SPELL_VAMPIRIC_TOUCH, false);
                                                else
                                                    player->CastSpell(me, SPELL_RENEW, false);
                                                break;
                                            case CLASS_SHAMAN:
                                                if (urand(0, 1))
                                                    player->CastSpell(target, SPELL_EARTH_SHOCK, false);
                                                else
                                                    player->CastSpell(me, SPELL_HEALING_WAVE, false);
                                                break;
                                            case CLASS_ROGUE:
                                                player->CastSpell(target, RAND(SPELL_HEMORRHAGE, SPELL_MUTILATE), false);
                                                break;
                                            case CLASS_DEATH_KNIGHT:
                                                if (urand(0, 1))
                                                    player->CastSpell(target, SPELL_PLAGUE_STRIKE, true);
                                                else
                                                    player->CastSpell(target, SPELL_HOWLING_BLAST, true);
                                                break;
                                        }
                                    }
                                }
                                ++itr;
                            }

                            if (chained.empty())
                                events.PopEvent();
                            else
                                events.RepeatEvent(5000);

                            break;
                        }
                        case EVENT_DETONATE:
                        {
                            std::vector<Unit*> unitList;
                            ThreatContainer::StorageType const &threatList = me->getThreatManager().getThreatList();
                            for (ThreatContainer::StorageType::const_iterator itr = threatList.begin(); itr != threatList.end(); ++itr)
                            {
                                Unit* const target = (*itr)->getTarget();

                                if (target->GetTypeId() == TYPEID_PLAYER
                                        && target->getPowerType() == POWER_MANA
                                        && target->GetPower(POWER_MANA))
                                {
                                    unitList.push_back(target);
                                }
                            }

                            if (!unitList.empty())
                            {
                                std::vector<Unit*>::const_iterator itr = unitList.begin();
                                advance(itr, rand()%unitList.size());
                                DoCast(*itr, SPELL_MANA_DETONATION);
                                Talk(SAY_SPECIAL);
                            }

                            events.RepeatEvent(urand(20000, 50000));
                            break;
                        }
                        case EVENT_FISSURE:
                            if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0))
                                DoCast(target, SPELL_SHADOW_FISURE);
                            events.RepeatEvent(urand(10000, 45000));
                            break;
                        case EVENT_BLAST:
                            if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, RAID_MODE(1, 0), 0, true))
                                DoCast(target, SPELL_FROST_BLAST);
                            if (rand()%2)
                                Talk(SAY_FROST_BLAST);
                            events.RepeatEvent(urand(30000, 90000));
                            break;
                        default:
                            events.PopEvent();
                            break;
                    }
                }

                DoMeleeAttackIfReady();
            }
        }
示例#9
0
	bool empty() { return symbols.empty(); }
示例#10
0
 bool hasVariable() const { return !(VariableUses.empty() &&
                                     VariableDefs.empty()); }
示例#11
0
int curses_start_color(void)
{
    colorpairs = new pairs[100];
    windowsPalette = new RGBQUAD[16];

    //Load the console colors from colors.json
    std::ifstream colorfile("data/raw/colors.json", std::ifstream::in | std::ifstream::binary);
    try{
        JsonIn jsin(colorfile);
        char ch;
        // Manually load the colordef object because the json handler isn't loaded yet.
        jsin.eat_whitespace();
        ch = jsin.peek();
        if( ch == '[' ) {
            jsin.start_array();
            // find type and dispatch each object until array close
            while (!jsin.end_array()) {
                jsin.eat_whitespace();
                char ch = jsin.peek();
                if (ch != '{') {
                    std::stringstream err;
                    err << jsin.line_number() << ": ";
                    err << "expected array of objects but found '";
                    err << ch << "', not '{'";
                    throw err.str();
                }
                JsonObject jo = jsin.get_object();
                load_colors(jo);
                jo.finish();
            }
        } else {
            // not an array?
            std::stringstream err;
            err << jsin.line_number() << ": ";
            err << "expected object or array, but found '" << ch << "'";
            throw err.str();
        }
    }
    catch(std::string e){
        throw "data/raw/colors.json: " + e;
    }

    if(consolecolors.empty())return SetDIBColorTable(backbuffer, 0, 16, windowsPalette);
    windowsPalette[0]  = BGR(ccolor("BLACK"));
    windowsPalette[1]  = BGR(ccolor("RED"));
    windowsPalette[2]  = BGR(ccolor("GREEN"));
    windowsPalette[3]  = BGR(ccolor("BROWN"));
    windowsPalette[4]  = BGR(ccolor("BLUE"));
    windowsPalette[5]  = BGR(ccolor("MAGENTA"));
    windowsPalette[6]  = BGR(ccolor("CYAN"));
    windowsPalette[7]  = BGR(ccolor("GRAY"));
    windowsPalette[8]  = BGR(ccolor("DGRAY"));
    windowsPalette[9]  = BGR(ccolor("LRED"));
    windowsPalette[10] = BGR(ccolor("LGREEN"));
    windowsPalette[11] = BGR(ccolor("YELLOW"));
    windowsPalette[12] = BGR(ccolor("LBLUE"));
    windowsPalette[13] = BGR(ccolor("LMAGENTA"));
    windowsPalette[14] = BGR(ccolor("LCYAN"));
    windowsPalette[15] = BGR(ccolor("WHITE"));
    return SetDIBColorTable(backbuffer, 0, 16, windowsPalette);
}
void CoverTree<MetricType, RootPointPolicy, StatisticType>::
DualTreeTraverser<RuleType>::ReferenceRecursion(
    CoverTree& queryNode,
    std::map<int, std::vector<DualCoverTreeMapEntry> >& referenceMap)
{
  // First, reduce the maximum scale in the reference map down to the scale of
  // the query node.
  while (!referenceMap.empty())
  {
    // Hacky bullshit to imitate jl cover tree.
    if (queryNode.Parent() == NULL && (*referenceMap.rbegin()).first <
        queryNode.Scale())
      break;
    if (queryNode.Parent() != NULL && (*referenceMap.rbegin()).first <=
        queryNode.Scale())
      break;
    // If the query node's scale is INT_MIN and the reference map's maximum
    // scale is INT_MIN, don't try to recurse...
    if ((queryNode.Scale() == INT_MIN) &&
       ((*referenceMap.rbegin()).first == INT_MIN))
      break;

    // Get a reference to the current largest scale.
    std::vector<DualCoverTreeMapEntry>& scaleVector = (*referenceMap.rbegin()).second;

    // Before traversing all the points in this scale, sort by score.
    std::sort(scaleVector.begin(), scaleVector.end());

    // Now loop over each element.
    for (size_t i = 0; i < scaleVector.size(); ++i)
    {
      // Get a reference to the current element.
      const DualCoverTreeMapEntry& frame = scaleVector.at(i);

      CoverTree<MetricType, RootPointPolicy, StatisticType>* refNode =
          frame.referenceNode;

      // Create the score for the children.
      double score = rule.Rescore(queryNode, *refNode, frame.score);

      // Now if this childScore is DBL_MAX we can prune all children.  In this
      // recursion setup pruning is all or nothing for children.
      if (score == DBL_MAX)
      {
        ++numPrunes;
        continue;
      }

      // If it is not pruned, we must evaluate the base case.

      // Add the children.
      for (size_t j = 0; j < refNode->NumChildren(); ++j)
      {
        rule.TraversalInfo() = frame.traversalInfo;
        double childScore = rule.Score(queryNode, refNode->Child(j));
        if (childScore == DBL_MAX)
        {
          ++numPrunes;
          continue;
        }

        // It wasn't pruned; evaluate the base case.
        const double baseCase = rule.BaseCase(queryNode.Point(),
            refNode->Child(j).Point());

        DualCoverTreeMapEntry newFrame;
        newFrame.referenceNode = &refNode->Child(j);
        newFrame.score = childScore; // Use the score of the parent.
        newFrame.baseCase = baseCase;
        newFrame.traversalInfo = rule.TraversalInfo();

        referenceMap[newFrame.referenceNode->Scale()].push_back(newFrame);
      }
    }

    // Now clear the memory for this scale; it isn't needed anymore.
    referenceMap.erase((*referenceMap.rbegin()).first);
  }
}
void CoverTree<MetricType, RootPointPolicy, StatisticType>::
DualTreeTraverser<RuleType>::PruneMap(
    CoverTree& queryNode,
    std::map<int, std::vector<DualCoverTreeMapEntry> >& referenceMap,
    std::map<int, std::vector<DualCoverTreeMapEntry> >& childMap)
{
  if (referenceMap.empty())
    return; // Nothing to do.

  // Copy the zero set first.
  if ((*referenceMap.begin()).first == INT_MIN)
  {
    // Get a reference to the vector representing the entries at this scale.
    std::vector<DualCoverTreeMapEntry>& scaleVector =
        (*referenceMap.begin()).second;

    // Before traversing all the points in this scale, sort by score.
    std::sort(scaleVector.begin(), scaleVector.end());

    const int thisScale = (*referenceMap.begin()).first;
    childMap[thisScale].reserve(scaleVector.size());
    std::vector<DualCoverTreeMapEntry>& newScaleVector = childMap[thisScale];

    // Loop over each entry in the vector.
    for (size_t j = 0; j < scaleVector.size(); ++j)
    {
      const DualCoverTreeMapEntry& frame = scaleVector[j];

      // First evaluate if we can prune without performing the base case.
      CoverTree<MetricType, RootPointPolicy, StatisticType>* refNode =
          frame.referenceNode;

      // Perform the actual scoring, after restoring the traversal info.
      rule.TraversalInfo() = frame.traversalInfo;
      double score = rule.Score(queryNode, *refNode);

      if (score == DBL_MAX)
      {
        // Pruned.  Move on.
        ++numPrunes;
        continue;
      }

      // If it isn't pruned, we must evaluate the base case.
      const double baseCase = rule.BaseCase(queryNode.Point(),
          refNode->Point());

      // Add to child map.
      newScaleVector.push_back(frame);
      newScaleVector.back().score = score;
      newScaleVector.back().baseCase = baseCase;
      newScaleVector.back().traversalInfo = rule.TraversalInfo();
    }

    // If we didn't add anything, then strike this vector from the map.
    if (newScaleVector.size() == 0)
      childMap.erase((*referenceMap.begin()).first);
  }

  typename std::map<int, std::vector<DualCoverTreeMapEntry> >::reverse_iterator
      it = referenceMap.rbegin();

  while ((it != referenceMap.rend()))
  {
    const int thisScale = (*it).first;
    if (thisScale == INT_MIN) // We already did it.
      break;

    // Get a reference to the vector representing the entries at this scale.
    std::vector<DualCoverTreeMapEntry>& scaleVector = (*it).second;

    // Before traversing all the points in this scale, sort by score.
    std::sort(scaleVector.begin(), scaleVector.end());

    childMap[thisScale].reserve(scaleVector.size());
    std::vector<DualCoverTreeMapEntry>& newScaleVector = childMap[thisScale];

    // Loop over each entry in the vector.
    for (size_t j = 0; j < scaleVector.size(); ++j)
    {
      const DualCoverTreeMapEntry& frame = scaleVector[j];

      // First evaluate if we can prune without performing the base case.
      CoverTree<MetricType, RootPointPolicy, StatisticType>* refNode =
          frame.referenceNode;

      // Perform the actual scoring, after restoring the traversal info.
      rule.TraversalInfo() = frame.traversalInfo;
      double score = rule.Score(queryNode, *refNode);

      if (score == DBL_MAX)
      {
        // Pruned.  Move on.
        ++numPrunes;
        continue;
      }

      // If it isn't pruned, we must evaluate the base case.
      const double baseCase = rule.BaseCase(queryNode.Point(),
          refNode->Point());

      // Add to child map.
      newScaleVector.push_back(frame);
      newScaleVector.back().score = score;
      newScaleVector.back().baseCase = baseCase;
      newScaleVector.back().traversalInfo = rule.TraversalInfo();
    }

    // If we didn't add anything, then strike this vector from the map.
    if (newScaleVector.size() == 0)
      childMap.erase((*it).first);

    ++it; // Advance to next scale.
  }
}
bool group_weights_cache_impl::initialized() {
    boost::shared_lock<boost::shared_mutex> lock(shared_mutex_);
    return !map_.empty();
}
示例#15
0
pplx::task<web::http::http_response> ApiClient::callApi(
    const utility::string_t& path,
    const utility::string_t& method,
    const std::map<utility::string_t, utility::string_t>& queryParams,
    const std::shared_ptr<IHttpBody> postBody,
    const std::map<utility::string_t, utility::string_t>& headerParams,
    const std::map<utility::string_t, utility::string_t>& formParams,
    const std::map<utility::string_t, std::shared_ptr<HttpContent>>& fileParams,
    const utility::string_t& contentType
) const
{
    if (postBody != nullptr && formParams.size() != 0)
    {
        throw ApiException(400, utility::conversions::to_string_t("Cannot have body and form params"));
    }

    if (postBody != nullptr && fileParams.size() != 0)
    {
        throw ApiException(400, utility::conversions::to_string_t("Cannot have body and file params"));
    }

    if (fileParams.size() > 0 && contentType != utility::conversions::to_string_t("multipart/form-data"))
    {
        throw ApiException(400, utility::conversions::to_string_t("Operations with file parameters must be called with multipart/form-data"));
    }

    web::http::client::http_client client(m_Configuration->getBaseUrl(), m_Configuration->getHttpConfig());

    web::http::http_request request;
    for ( auto& kvp : headerParams )
    {
        request.headers().add(kvp.first, kvp.second);
    }

    if (fileParams.size() > 0)
    {
        MultipartFormData uploadData;
        for (auto& kvp : formParams)
        {
            uploadData.add(ModelBase::toHttpContent(kvp.first, kvp.second));
        }
        for (auto& kvp : fileParams)
        {
            uploadData.add(ModelBase::toHttpContent(kvp.first, kvp.second));
        }
        std::stringstream data;
        uploadData.writeTo(data);
        auto bodyString = data.str();
        auto length = bodyString.size();
        request.set_body(concurrency::streams::bytestream::open_istream(std::move(bodyString)), length, utility::conversions::to_string_t("multipart/form-data; boundary=") + uploadData.getBoundary());
    }
    else
    {
        if (postBody != nullptr)
        {
            std::stringstream data;
            postBody->writeTo(data);
            auto bodyString = data.str();
            auto length = bodyString.size();
            request.set_body(concurrency::streams::bytestream::open_istream(std::move(bodyString)), length, contentType);
        }
        else
        {
            if (contentType == utility::conversions::to_string_t("application/json"))
            {
                web::json::value body_data = web::json::value::object();
                for (auto& kvp : formParams)
                {
                    body_data[kvp.first] = ModelBase::toJson(kvp.second);
                }
                if (!formParams.empty())
                {
                    request.set_body(body_data);
		}
            }
            else
            {
                web::http::uri_builder formData;
                for (auto& kvp : formParams)
                {
                    formData.append_query(kvp.first, kvp.second);
                }
                if (!formParams.empty())
                {
                    request.set_body(formData.query(), utility::conversions::to_string_t("application/x-www-form-urlencoded"));
                }
            }
        }
    }

    web::http::uri_builder builder(path);
    for (auto& kvp : queryParams)
    {
        builder.append_query(kvp.first, kvp.second);
    }
    request.set_request_uri(builder.to_uri());
    request.set_method(method);
    if ( !request.headers().has( web::http::header_names::user_agent ) )
    {
        request.headers().add( web::http::header_names::user_agent, m_Configuration->getUserAgent() );
    }

    return client.request(request);
}
示例#16
0
std::string CSeqWriter::transformAS( CSeqLog &log, const char* packetPath, std::list<std::string> &import, std::map< std::string, std::string > &classDir )
{
    if ( log.className == "SPackHead" )
        log.className = "SPackHead";
    std::list<std::string> importList = import;

    //import 统计
    if ( !classDir.empty() )
        parseImport( log, classDir, importList );

    std::stringstream stream;

    //输出package{
    stream << "package";
    if ( packetPath != NULL && packetPath[0] != '\0' )
        stream << " " << packetPath;
    stream << std::endl;
    stream << '{' << std::endl;

    //输出import
    for ( std::vector< wd::CSeqEle >::iterator iter = log.eleList.begin();
        iter != log.eleList.end();
        ++iter )
    {
        if ( VarType2As( iter->eleType ) == "ByteArray" )
        {
            stream << taps << "import flash.utils.ByteArray;" << std::endl;
            break;
        }
    }
    if ( !importList.empty() )
    {
        for ( std::list<std::string>::iterator iter = importList.begin();
            iter != importList.end();
            ++iter )
        {
            stream << taps << "import " << *iter << ";" << std::endl;
        }
    }
    stream << std::endl;

    //输出注释
    if ( !log.classDescript.empty() )
    {
        std::string descript = log.classDescript;
        for ( int i = (int)descript.find_first_of( '\n' ); i >= 0 && i < (int)descript.length(); )
        {
            if ( descript[i] == '\n' )
            {
                descript.insert( i + 1, taps );
                i += sizeof( taps );
            }
            else
                ++i;
        }
        stream << taps << "/*" << descript << "*/" << std::endl;
    }

    //输出类名
    stream << taps << "public class " << log.className;

    //输出父类
    if ( !log.classParent.empty() )
        stream << " extends " << log.classParent;
    else
        stream << " extends CSeq";
    stream << std::endl;

    //类 {
    stream << taps << '{' << std::endl;

    for ( std::vector< wd::CSeqEle >::iterator iter = log.eleList.begin();
        iter != log.eleList.end();
        ++iter )
    {
        std::string init_type;
        stream << taps << taps << "public var " << iter->eleName << ':' << output_element_as( *iter, init_type );

        if ( !init_type.empty() )
            stream << " = " << init_type;
        stream << ";";

        if ( !iter->eleDescript.empty() )
            stream << taps << "//" << iter->eleDescript;

        stream << std::endl;
    }
    stream << std::endl;

    //输出构造
    stream << taps << taps << "public function " << log.className << "()" << std::endl;
    stream << taps << taps << '{' << std::endl;
    stream << taps << taps << taps << "elementInfo = static_element_info;" << std::endl;

    //输出构造项
    if ( !log.initList.empty() )
    {
        stream << std::endl;

        for ( std::vector< CSeqInit >::iterator iter = log.initList.begin();
            iter != log.initList.end();
            ++iter )
        {
            stream << taps << taps << taps << iter->eleName << " = " << iter->eleDefault << ';' << std::endl;
        }
    }

    stream << taps << taps << '}' << std::endl;

    stream << std::endl;

    //输出父类结构继承
    stream << taps << taps << "static protected var static_element_info:Vector.<CSeqEleInfo> = ";
    if ( !log.classParent.empty() )
        stream << log.classParent;
    else
        stream << "CSeq";
    stream << ".static_element_info" << std::endl;
    stream << taps << taps << taps << ".concat" << std::endl;
    stream << taps << taps << taps << '(' << std::endl;
    stream << taps << taps << taps << taps << "new <CSeqEleInfo>" << std::endl;
    stream << taps << taps << taps << taps << '[' << std::endl;
    for ( std::vector< wd::CSeqEle >::iterator iter = log.eleList.begin();
        iter != log.eleList.end();
        ++iter )
    {
        stream << taps << taps << taps << taps << taps;

        stream << output_register_as( *iter );

        if ( iter + 1 != log.eleList.end() )
            stream << ',';
        stream << std::endl;
    }
    stream << taps << taps << taps << taps << ']' << std::endl;
    stream << taps << taps << taps << ");" << std::endl;

    //类 }
    stream << taps << '}' << std::endl;

    //package }
    stream << '}' << std::endl;

    return stream.str();
}
示例#17
0
// -1 不是有效的LayerFolder
//IN:文件所在的路径,如:f:\example
//out:
int searchWinSysLayerFolder (string sLayerFolderPath, std::map<int,TLevelBundleExistStatus*>& pBlEstIdx) 
{
	struct _finddata64i32_t fileInfo;//保存文件信息的结构体
	long handle;//句柄
	int done;//查找nextfile是否成功
	string fileName = sLayerFolderPath+"\\*.*"; //要搜索的文件名

	//查找第一个文件,返回句柄
	handle=_findfirst64i32(fileName.c_str(), &fileInfo);
	if(handle==-1)
		return -1;

	do
	{
		//如果是文件夹".",或者"..",则进行判断下一个文件
		if( (strcmp(fileInfo.name,".")==0) || (strcmp(fileInfo.name,"..") == 0))
			continue;

		//如果是文件夹,则进入下一层文件夹搜索
		if((fileInfo.attrib&_A_SUBDIR)==_A_SUBDIR)
		{
			std::string filePathSub=sLayerFolderPath+"\\"+fileInfo.name;

			if( 3 != strlen(fileInfo.name) )
			{
				std::cout << "文件夹["<< filePathSub <<"]"<< "跳过"<< std::endl;
				continue;
			}

			if( 'L' != fileInfo.name[0] )
			{
				std::cout << "文件夹["<< filePathSub <<"]"<< "跳过"<< std::endl;
				continue;
			}

			char szNum[4];
			memcpy(szNum, fileInfo.name+1, 4/* * sizeof(char) */ );
			szNum[3] = '\0';
			int nLv = 0;
			if( -1 == sscanf(szNum, "%d", &nLv) )
			{
				string fileNameTure = sLayerFolderPath + "\\" +fileInfo.name;
				std::cout << "文件["<< fileNameTure <<"] "<< "跳过"<< std::endl;
				continue;
			}

			TLevelBundleExistStatus* pNode = new TLevelBundleExistStatus;
			pNode->nSize = calcBunldeExistStatusOccupyByte(nLv);
			pNode->pbyteIndex = new unsigned char[pNode->nSize];
			memset(pNode->pbyteIndex, 0, pNode->nSize);

			//递归调用
			searchWinSysLevelFolder(filePathSub, nLv, pNode->pbyteIndex);

			// 记录索引
			pBlEstIdx.insert( std::make_pair(nLv, pNode) );
		}
		//把搜集到的信息连接到文件
		else
		{
			// 跳过文件
			string fileNameTure=sLayerFolderPath+"\\"+fileInfo.name;
			std::cout << "文件["<< fileNameTure <<"]"<< "跳过"<< std::endl;
		}

	}while( 0 == (done=_findnext64i32(handle,&fileInfo)) );

	_findclose(handle);
	if( pBlEstIdx.empty() )
		return -1;

	return 0;
}
示例#18
0
void CloseNetwork()
{
	if (IsNetworkRunning())
	{
		QString strNetCloseFile, strNetCloseArgs;
		bool bContinue = true;
		int iErrorCode;

		// stop clients, server
		CloseAllConnections();
		if (g_pMainWindow != NULL)
			g_pMainWindow->m_pNetworkManager->UpdateClientTable();
		if (!g_mapClients.empty())
			return;

		StopServer();
		if (g_pServer != NULL)
			return;

		g_pLogger->LogInfo("Closing Network Interface...");
		signal(SIGPIPE, g_pOldSigPipeHandler);

		/*if (g_strDeviceType.compare("denso") == 0)
			g_bNetworkEnabled = !CloseDensoUnit();
		*/
		strNetCloseFile = g_pSettings->m_sSettings[SETTINGS_NETWORK_CLOSEFILE_NUM].GetValue().strValue;
		if (!g_bNetworkEnabled && !strNetCloseFile.isEmpty())
		{
			strNetCloseArgs = g_pSettings->m_sSettings[SETTINGS_NETWORK_CLOSEARGS_NUM].GetValue().strValue;

			strNetCloseArgs.replace("%dn", g_strDeviceName);
			strNetCloseArgs.replace("%dt", g_strDeviceType);
			strNetCloseArgs.replace("%ip", IPAddressToString(g_ipAddress));
			strNetCloseArgs.replace("%sub", IPAddressToString(g_ipSubnet));
			strNetCloseArgs.replace("%txp", QString::number(g_iTXPower));
			strNetCloseArgs.replace("%txr", QString::number(g_iTXRate));

			if (!strNetCloseArgs.isEmpty())
				strNetCloseFile += " " + strNetCloseArgs;

			while (bContinue)
			{
				iErrorCode = system(strNetCloseFile);
				if (iErrorCode == 0) {
					g_bNetworkEnabled = false;
					bContinue = false;
				} else
					bContinue = g_pLogger->PromptLogError(PACKAGE_TITLE, QString("Could not close network interface (code %1)").arg(iErrorCode), false);
			}
		}
		else
			g_bNetworkEnabled = false;

		if (g_bNetworkEnabled) {
			g_pLogger->LogInfo("Failed\n");
			return;
		} else
			g_pLogger->LogInfo("Successful\n");

		if (g_pMainWindow != NULL)
		{
			g_pMainWindow->m_pNetInit->setMenuText("&Initialize");
			g_pMainWindow->m_pNetInit->setToolTip("Initialize network devices and connections");
			g_pMainWindow->m_pNetClose->setEnabled(false);
			g_pMainWindow->m_pNetMenu->setItemEnabled(g_pMainWindow->m_iNetServerMenuID, false);
			g_pMainWindow->m_pNetworkManager->SetNetworkInitialized(false);
		}
	}
}
示例#19
0
/**
**  Initialize SDLKey to string map
*/
static void InitKey2Str()
{
	if (!Key2Str.empty()) {
		return;
	}

	int i;
	char str[20];

	Key2Str[SDLK_BACKSPACE] = "backspace";
	Key2Str[SDLK_TAB] = "tab";
	Key2Str[SDLK_CLEAR] = "clear";
	Key2Str[SDLK_RETURN] = "return";
	Key2Str[SDLK_PAUSE] = "pause";
	Key2Str[SDLK_ESCAPE] = "escape";
	Key2Str[SDLK_SPACE] = " ";
	Key2Str[SDLK_EXCLAIM] = "!";
	Key2Str[SDLK_QUOTEDBL] = "\"";
	Key2Str[SDLK_HASH] = "#";
	Key2Str[SDLK_DOLLAR] = "$";
	Key2Str[SDLK_AMPERSAND] = "&";
	Key2Str[SDLK_QUOTE] = "'";
	Key2Str[SDLK_LEFTPAREN] = "(";
	Key2Str[SDLK_RIGHTPAREN] = ")";
	Key2Str[SDLK_ASTERISK] = "*";
	Key2Str[SDLK_PLUS] = "+";
	Key2Str[SDLK_COMMA] = ",";
	Key2Str[SDLK_MINUS] = "-";
	Key2Str[SDLK_PERIOD] = ".";
	Key2Str[SDLK_SLASH] = "/";

	str[1] = '\0';
	for (i = SDLK_0; i <= SDLK_9; ++i) {
		str[0] = i;
		Key2Str[i] = str;
	}

	Key2Str[SDLK_COLON] = ":";
	Key2Str[SDLK_SEMICOLON] = ";";
	Key2Str[SDLK_LESS] = "<";
	Key2Str[SDLK_EQUALS] = "=";
	Key2Str[SDLK_GREATER] = ">";
	Key2Str[SDLK_QUESTION] = "?";
	Key2Str[SDLK_AT] = "@";
	Key2Str[SDLK_LEFTBRACKET] = "[";
	Key2Str[SDLK_BACKSLASH] = "\\";
	Key2Str[SDLK_RIGHTBRACKET] = "]";
	Key2Str[SDLK_BACKQUOTE] = "`";

	str[1] = '\0';
	for (i = SDLK_a; i <= SDLK_z; ++i) {
		str[0] = i;
		Key2Str[i] = str;
	}

	Key2Str[SDLK_DELETE] = "delete";

	for (i = SDLK_KP0; i <= SDLK_KP9; ++i) {
		sprintf(str, "kp_%d", i - SDLK_KP0);
		Key2Str[i] = str;
	}

	Key2Str[SDLK_KP_PERIOD] = "kp_period";
	Key2Str[SDLK_KP_DIVIDE] = "kp_divide";
	Key2Str[SDLK_KP_MULTIPLY] = "kp_multiply";
	Key2Str[SDLK_KP_MINUS] = "kp_minus";
	Key2Str[SDLK_KP_PLUS] = "kp_plus";
	Key2Str[SDLK_KP_ENTER] = "kp_enter";
	Key2Str[SDLK_KP_EQUALS] = "kp_equals";
	Key2Str[SDLK_UP] = "up";
	Key2Str[SDLK_DOWN] = "down";
	Key2Str[SDLK_RIGHT] = "right";
	Key2Str[SDLK_LEFT] = "left";
	Key2Str[SDLK_INSERT] = "insert";
	Key2Str[SDLK_HOME] = "home";
	Key2Str[SDLK_END] = "end";
	Key2Str[SDLK_PAGEUP] = "pageup";
	Key2Str[SDLK_PAGEDOWN] = "pagedown";

	for (i = SDLK_F1; i <= SDLK_F15; ++i) {
		sprintf(str, "f%d", i - SDLK_F1 + 1);
		Key2Str[i] = str;
	}

	Key2Str[SDLK_HELP] = "help";
	Key2Str[SDLK_PRINT] = "print";
	Key2Str[SDLK_SYSREQ] = "sysreq";
	Key2Str[SDLK_BREAK] = "break";
	Key2Str[SDLK_MENU] = "menu";
	Key2Str[SDLK_POWER] = "power";
	Key2Str[SDLK_EURO] = "euro";
	Key2Str[SDLK_UNDO] = "undo";
}