Esempio n. 1
0
void UserConnection::on(Data, uint8_t* data, size_t len) noexcept { 
	lastActivity = GET_TICK(); 
	fire(UserConnectionListener::Data(), this, data, len); 
}
void SettingsManager::delSearchType(const string& name) {
    validateSearchTypeName(name);
    searchTypes.erase(name);
    fire(SettingsManagerListener::SearchTypesChanged());
}
Esempio n. 3
0
void inventory::form_from_map( const tripoint &origin, int range, bool assign_invlet )
{
    items.clear();
    // TODO: Z
    tripoint p( origin.x - range, origin.y - range, origin.z );
    int &x = p.x;
    int &y = p.y;
    for( x = origin.x - range; x <= origin.x + range; x++ ) {
        for( y = origin.y - range; y <= origin.y + range; y++ ) {
            if (g->m.has_furn(x, y) && g->m.accessible_furniture( origin, p, range )) {
                const furn_t &f = g->m.furn_at(x, y);
                itype *type = f.crafting_pseudo_item_type();
                if (type != NULL) {
                    item furn_item(type->id, 0);
                    const itype *ammo = f.crafting_ammo_item_type();
                    if (ammo != NULL) {
                        furn_item.charges = count_charges_in_list(ammo, g->m.i_at(x, y));
                    }
                    furn_item.item_tags.insert("PSEUDO");
                    add_item(furn_item);
                }
            }
            if( !g->m.accessible_items( origin, p, range ) ) {
                continue;
            }
            for (auto &i : g->m.i_at(x, y)) {
                if (!i.made_of(LIQUID)) {
                    add_item(i, false, assign_invlet);
                }
            }
            // Kludges for now!
            ter_id terrain_id = g->m.ter(x, y);
            if (g->m.has_nearby_fire( p, 0)) {
                item fire("fire", 0);
                fire.charges = 1;
                add_item(fire);
            }
            if (terrain_id == t_water_sh || terrain_id == t_water_dp ||
                    terrain_id == t_water_pool || terrain_id == t_water_pump) {
                item water("water", 0);
                water.charges = 50;
                add_item(water);
            }
            if (terrain_id == t_swater_sh || terrain_id == t_swater_dp) {
                item swater("salt_water", 0);
                swater.charges = 50;
                add_item(swater);
            }
            // add cvd forge from terrain
            if (terrain_id == t_cvdmachine) {
                item cvd_machine("cvd_machine", 0);
                cvd_machine.charges = 1;
                cvd_machine.item_tags.insert("PSEUDO");
                add_item(cvd_machine);
            }
            // kludge that can probably be done better to check specifically for toilet water to use in
            // crafting
            if (furnlist[g->m.furn(x, y)].examine == &iexamine::toilet) {
                // get water charges at location
                auto toilet = g->m.i_at(x, y);
                auto water = toilet.end();
                for( auto candidate = toilet.begin(); candidate != toilet.end(); ++candidate ) {
                    if( candidate->typeId() == "water" ) {
                        water = candidate;
                        break;
                    }
                }
                if( water != toilet.end() && water->charges > 0) {
                    add_item( *water );
                }
            }

            // keg-kludge
            if (furnlist[g->m.furn(x, y)].examine == &iexamine::keg) {
                auto liq_contained = g->m.i_at(x, y);
                for( auto &i : liq_contained ) {
                    if( i.made_of(LIQUID) ) {
                        add_item(i);
                    }
                }
            }

            int vpart = -1;
            vehicle *veh = g->m.veh_at(x, y, vpart);

            if (veh) {
                //Adds faucet to kitchen stuff; may be horribly wrong to do such....
                //ShouldBreak into own variable
                const int kpart = veh->part_with_feature(vpart, "KITCHEN");
                const int faupart = veh->part_with_feature(vpart, "FAUCET");
                const int weldpart = veh->part_with_feature(vpart, "WELDRIG");
                const int craftpart = veh->part_with_feature(vpart, "CRAFTRIG");
                const int forgepart = veh->part_with_feature(vpart, "FORGE");
                const int chempart = veh->part_with_feature(vpart, "CHEMLAB");
                const int cargo = veh->part_with_feature(vpart, "CARGO");

                if (cargo >= 0) {
                    *this += std::list<item>( veh->get_items(cargo).begin(),
                                              veh->get_items(cargo).end() );
                }

                if(faupart >= 0 ) {
                    item water("water_clean", 0);
                    water.charges = veh->fuel_left("water_clean");
                    add_item(water);
                }

                if (kpart >= 0) {
                    item hotplate("hotplate", 0);
                    hotplate.charges = veh->fuel_left("battery", true);
                    hotplate.item_tags.insert("PSEUDO");
                    add_item(hotplate);

                    item water("water_clean", 0);
                    water.charges = veh->fuel_left("water_clean");
                    add_item(water);

                    item pot("pot", 0);
                    pot.item_tags.insert("PSEUDO");
                    add_item(pot);
                    item pan("pan", 0);
                    pan.item_tags.insert("PSEUDO");
                    add_item(pan);
                }
                if (weldpart >= 0) {
                    item welder("welder", 0);
                    welder.charges = veh->fuel_left("battery", true);
                    welder.item_tags.insert("PSEUDO");
                    add_item(welder);

                    item soldering_iron("soldering_iron", 0);
                    soldering_iron.charges = veh->fuel_left("battery", true);
                    soldering_iron.item_tags.insert("PSEUDO");
                    add_item(soldering_iron);
                }
                if (craftpart >= 0) {
                    item vac_sealer("vac_sealer", 0);
                    vac_sealer.charges = veh->fuel_left("battery", true);
                    vac_sealer.item_tags.insert("PSEUDO");
                    add_item(vac_sealer);

                    item dehydrator("dehydrator", 0);
                    dehydrator.charges = veh->fuel_left("battery", true);
                    dehydrator.item_tags.insert("PSEUDO");
                    add_item(dehydrator);

                    item press("press", 0);
                    press.charges = veh->fuel_left("battery", true);
                    press.item_tags.insert("PSEUDO");
                    add_item(press);
                }
                if (forgepart >= 0) {
                    item forge("forge", 0);
                    forge.charges = veh->fuel_left("battery", true);
                    forge.item_tags.insert("PSEUDO");
                    add_item(forge);
                }
                if (chempart >= 0) {
                    item hotplate("hotplate", 0);
                    hotplate.charges = veh->fuel_left("battery", true);
                    hotplate.item_tags.insert("PSEUDO");
                    add_item(hotplate);

                    item chemistry_set("chemistry_set", 0);
                    chemistry_set.charges = veh->fuel_left("battery", true);
                    chemistry_set.item_tags.insert("PSEUDO");
                    add_item(chemistry_set);
                }
            }
        }
    }
}
Esempio n. 4
0
void firm::set_vacancies()
{
    if (labor_capacity < workers.size())
        fire();
}
void SettingsManager::load(string const& aFileName)
{
    try {
        SimpleXML xml;

        xml.fromXML(File(aFileName, File::READ, File::OPEN).read());

        xml.resetCurrentChild();

        xml.stepIn();

        if(xml.findChild("Settings"))
        {
            xml.stepIn();

            int i;

            for(i=STR_FIRST; i<STR_LAST; i++)
            {
                const string& attr = settingTags[i];
                dcassert(attr.find("SENTRY") == string::npos);

                if(xml.findChild(attr))
                    set(StrSetting(i), xml.getChildData());
                xml.resetCurrentChild();
            }
            for(i=INT_FIRST; i<INT_LAST; i++)
            {
                const string& attr = settingTags[i];
                dcassert(attr.find("SENTRY") == string::npos);

                if(xml.findChild(attr))
                    set(IntSetting(i), Util::toInt(xml.getChildData()));
                xml.resetCurrentChild();
            }
            for(i=FLOAT_FIRST; i<FLOAT_LAST; i++)
            {
                const string& attr = settingTags[i];
                dcassert(attr.find("SENTRY") == string::npos);

                if(xml.findChild(attr))
                    set(FloatSetting(i), Util::toInt(xml.getChildData()) / 1000.);
                xml.resetCurrentChild();
            }
            for(i=INT64_FIRST; i<INT64_LAST; i++)
            {
                const string& attr = settingTags[i];
                dcassert(attr.find("SENTRY") == string::npos);

                if(xml.findChild(attr))
                    set(Int64Setting(i), Util::toInt64(xml.getChildData()));
                xml.resetCurrentChild();
            }

            xml.stepOut();
        }

        xml.resetCurrentChild();
        if(xml.findChild("SearchTypes")) {
            try {
                searchTypes.clear();
                xml.stepIn();
                while(xml.findChild("SearchType")) {
                    const string& extensions = xml.getChildData();
                    if(extensions.empty()) {
                        continue;
                    }
                    const string& name = xml.getChildAttrib("Id");
                    if(name.empty()) {
                        continue;
                    }
                    searchTypes[name] = StringTokenizer<string>(extensions, ';').getTokens();
                }
                xml.stepOut();
            } catch(const SimpleXMLException&) {
                setSearchTypeDefaults();
            }
        }

        if(SETTING(PRIVATE_ID).length() != 39 || CID(SETTING(PRIVATE_ID)).isZero()) {
            set(PRIVATE_ID, CID::generate().toBase32());
        }

        double v = Util::toDouble(SETTING(CONFIG_VERSION));
        // if(v < 0.x) { // Fix old settings here }

        if(v <= 0.674) {

            // Formats changed, might as well remove these...
            unset(LOG_FORMAT_POST_DOWNLOAD);
            unset(LOG_FORMAT_POST_UPLOAD);
            unset(LOG_FORMAT_MAIN_CHAT);
            unset(LOG_FORMAT_PRIVATE_CHAT);
            unset(LOG_FORMAT_STATUS);
            unset(LOG_FORMAT_SYSTEM);
            unset(LOG_FILE_MAIN_CHAT);
            unset(LOG_FILE_STATUS);
            unset(LOG_FILE_PRIVATE_CHAT);
            unset(LOG_FILE_UPLOAD);
            unset(LOG_FILE_DOWNLOAD);
            unset(LOG_FILE_SYSTEM);
        }

        if(SETTING(SET_MINISLOT_SIZE) < 64)
            set(SET_MINISLOT_SIZE, 64);
        if(SETTING(AUTODROP_INTERVAL) < 1)
            set(AUTODROP_INTERVAL, 1);
        if(SETTING(AUTODROP_ELAPSED) < 1)
            set(AUTODROP_ELAPSED, 1);
        if(SETTING(AUTO_SEARCH_LIMIT) > 5)
            set(AUTO_SEARCH_LIMIT, 5);
        else if(SETTING(AUTO_SEARCH_LIMIT) < 1)
            set(AUTO_SEARCH_LIMIT, 1);

#ifdef _DEBUG
        set(PRIVATE_ID, CID::generate().toBase32());
#endif
        setDefault(UDP_PORT, SETTING(TCP_PORT));

        File::ensureDirectory(SETTING(TLS_TRUSTED_CERTIFICATES_PATH));

        fire(SettingsManagerListener::Load(), xml);

        xml.stepOut();

    } catch(const Exception&) {
        if(CID(SETTING(PRIVATE_ID)).isZero())
            set(PRIVATE_ID, CID::generate().toBase32());
    }
    if (SETTING(DHT_KEY).length() != 39 || CID(SETTING(DHT_KEY)).isZero())
        set(DHT_KEY, CID::generate().toBase32());
}
Esempio n. 6
0
void Bot::actions()
{
    QString line;
    QStringList list;

    line = bot->readLine();
    list = line.split(" ");

    for (int i = 0; i < list.count(); i++)
    {
        // если player вышел за границы
        if (this->x() < game->dop - pixsize/2 ||
            this->x() > game->scene->width()-game->dop*2 + 20 ||
            this->y() < game->dop - pixsize/2 ||
            this->y() > game->scene->height()-game->dop*2 + 20)
        {
            if (out == false)
            {
                out = true;
                outTime = QTime::currentTime();
                outTimer = outMaxTime;
            }

            if (outTime.msecsTo(QTime::currentTime()) > 1000)
            {
                if (outTimer > 0)
                {
                    outTimer--;
                    outTime = outTime.addSecs(1);
                }
                else
                {
                    // DIE M**********R!
                    out = false;
                    outTimer = outMaxTime;
                    killBot();
                    // BUHAHA
                }
            }
        }
        else
        {
            if (out == true)
            {
                out = false;
                outTimer = outMaxTime;
            }
        }

        if (list[i] == "mf")
            moveForward();
        if (list[i] == "mb")
            moveBack();
        if (list[i] == "rr")
            rotateRight();
        if (list[i] == "rl")
            rotateLeft();
        if (list[i] == "hr")
            headRight();
        if (list[i] == "hl")
            headLeft();
        if (list[i] == "fr")
            fire();
    }

    if (bot->atEnd())
    {
        switch (mode)
        {
            case 0:
                //timer->stop();
                killBot();
            break;

            case 1:
                bot->reset();
            break;
        }
    }

}
void SearchManager::onData(const uint8_t* buf, size_t aLen, const string& remoteIp) {
	string x((char*)buf, aLen);
	if(x.compare(0, 4, "$SR ") == 0) {
		string::size_type i, j;
		// Directories: $SR <nick><0x20><directory><0x20><free slots>/<total slots><0x05><Hubname><0x20>(<Hubip:port>)
		// Files:		$SR <nick><0x20><filename><0x05><filesize><0x20><free slots>/<total slots><0x05><Hubname><0x20>(<Hubip:port>)
		i = 4;
		if( (j = x.find(' ', i)) == string::npos) {
			return;
		}
		string nick = x.substr(i, j-i);
		i = j + 1;

		// A file has 2 0x05, a directory only one
		size_t cnt = count(x.begin() + j, x.end(), 0x05);

		SearchResult::Types type = SearchResult::TYPE_FILE;
		string file;
		int64_t size = 0;

		if(cnt == 1) {
			// We have a directory...find the first space beyond the first 0x05 from the back
			// (dirs might contain spaces as well...clever protocol, eh?)
			type = SearchResult::TYPE_DIRECTORY;
			// Get past the hubname that might contain spaces
			if((j = x.rfind(0x05)) == string::npos) {
				return;
			}
			// Find the end of the directory info
			if((j = x.rfind(' ', j-1)) == string::npos) {
				return;
			}
			if(j < i + 1) {
				return;
			}
			file = x.substr(i, j-i) + '\\';
		} else if(cnt == 2) {
			if( (j = x.find((char)5, i)) == string::npos) {
				return;
			}
			file = x.substr(i, j-i);
			i = j + 1;
			if( (j = x.find(' ', i)) == string::npos) {
				return;
			}
			size = Util::toInt64(x.substr(i, j-i));
		}
		i = j + 1;

		if( (j = x.find('/', i)) == string::npos) {
			return;
		}
		int freeSlots = Util::toInt(x.substr(i, j-i));
		i = j + 1;
		if( (j = x.find((char)5, i)) == string::npos) {
			return;
		}
		int slots = Util::toInt(x.substr(i, j-i));
		i = j + 1;
		if( (j = x.rfind(" (")) == string::npos) {
			return;
		}
		string hubName = x.substr(i, j-i);
		i = j + 2;
		if( (j = x.rfind(')')) == string::npos) {
			return;
		}

		string hubIpPort = x.substr(i, j-i);
		string url = ClientManager::getInstance()->findHub(hubIpPort);

		string encoding = ClientManager::getInstance()->findHubEncoding(url);
		nick = Text::toUtf8(nick, encoding);
		file = Text::toUtf8(file, encoding);
		hubName = Text::toUtf8(hubName, encoding);

		User::Ptr user = ClientManager::getInstance()->findUser(nick, url);
		if(!user) {
			// Could happen if hub has multiple URLs / IPs
			user = ClientManager::getInstance()->findLegacyUser(nick);
			if(!user)
				return;
		}

		string tth;
		if(hubName.compare(0, 4, "TTH:") == 0) {
			tth = hubName.substr(4);
			StringList names = ClientManager::getInstance()->getHubNames(user->getCID());
			hubName = names.empty() ? STRING(OFFLINE) : Util::toString(names);
		}

		if(tth.empty() && type == SearchResult::TYPE_FILE) {
			return;
		}


		SearchResult* sr = new SearchResult(user, type, slots, freeSlots, size,
			file, hubName, url, remoteIp, TTHValue(tth), Util::emptyString);
		fire(SearchManagerListener::SR(), sr);
		sr->decRef();
	} else if(x.compare(1, 4, "RES ") == 0 && x[x.length() - 1] == 0x0a) {
		AdcCommand c(x.substr(0, x.length()-1));
		if(c.getParameters().empty())
			return;
		string cid = c.getParam(0);
		if(cid.size() != 39)
			return;

		User::Ptr user = ClientManager::getInstance()->findUser(CID(cid));
		if(!user)
			return;

		// This should be handled by AdcCommand really...
		c.getParameters().erase(c.getParameters().begin());

		onRES(c, user, remoteIp);

	} /*else if(x.compare(1, 4, "SCH ") == 0 && x[x.length() - 1] == 0x0a) {
		try {
			respond(AdcCommand(x.substr(0, x.length()-1)));
		} catch(ParseException& ) {
		}
	}*/ // Needs further DoS investigation
}
Esempio n. 8
0
	void runStage()
	{
		fire();
		++stageNo_;
		stageStep_ *= 2;
	}
Esempio n. 9
0
/*
 * A generic function to handle
 * the basics of weapon thinking
 */
void Weapon_Generic(edict_t *ent, int FRAME_ACTIVATE_LAST, int FRAME_FIRE_LAST, int FRAME_IDLE_LAST,
                    int FRAME_DEACTIVATE_LAST, int *pause_frames, int *fire_frames, void (*fire)(edict_t *ent))
{
  int n;

  if (!ent || !fire_frames || !fire) {
    return;
  }

  if (ent->deadflag || (ent->s.modelindex != 255)) /* VWep animations screw up corpses */
  {
    return;
  }

  if (ent->client->weaponstate == WEAPON_DROPPING) {
    if (ent->client->ps.gunframe == FRAME_DEACTIVATE_LAST) {
      ChangeWeapon(ent);
      return;
    } else if ((FRAME_DEACTIVATE_LAST - ent->client->ps.gunframe) == 4) {
      ent->client->anim_priority = ANIM_REVERSE;

      if (ent->client->ps.pmove.pm_flags & PMF_DUCKED) {
        ent->s.frame = FRAME_crpain4 + 1;
        ent->client->anim_end = FRAME_crpain1;
      } else {
        ent->s.frame = FRAME_pain304 + 1;
        ent->client->anim_end = FRAME_pain301;
      }
    }

    ent->client->ps.gunframe++;
    return;
  }

  if (ent->client->weaponstate == WEAPON_ACTIVATING) {
    if (ent->client->ps.gunframe == FRAME_ACTIVATE_LAST) {
      ent->client->weaponstate = WEAPON_READY;
      ent->client->ps.gunframe = FRAME_IDLE_FIRST;
      return;
    }

    ent->client->ps.gunframe++;
    return;
  }

  if ((ent->client->newweapon) && (ent->client->weaponstate != WEAPON_FIRING)) {
    ent->client->weaponstate = WEAPON_DROPPING;
    ent->client->ps.gunframe = FRAME_DEACTIVATE_FIRST;

    if ((FRAME_DEACTIVATE_LAST - FRAME_DEACTIVATE_FIRST) < 4) {
      ent->client->anim_priority = ANIM_REVERSE;

      if (ent->client->ps.pmove.pm_flags & PMF_DUCKED) {
        ent->s.frame = FRAME_crpain4 + 1;
        ent->client->anim_end = FRAME_crpain1;
      } else {
        ent->s.frame = FRAME_pain304 + 1;
        ent->client->anim_end = FRAME_pain301;
      }
    }

    return;
  }

  if (ent->client->weaponstate == WEAPON_READY) {
    if (((ent->client->latched_buttons | ent->client->buttons) & BUTTON_ATTACK)) {
      ent->client->latched_buttons &= ~BUTTON_ATTACK;

      if ((!ent->client->ammo_index) ||
          (ent->client->pers.inventory[ent->client->ammo_index] >= ent->client->pers.weapon->quantity)) {
        ent->client->ps.gunframe = FRAME_FIRE_FIRST;
        ent->client->weaponstate = WEAPON_FIRING;

        /* start the animation */
        ent->client->anim_priority = ANIM_ATTACK;

        if (ent->client->ps.pmove.pm_flags & PMF_DUCKED) {
          ent->s.frame = FRAME_crattak1 - 1;
          ent->client->anim_end = FRAME_crattak9;
        } else {
          ent->s.frame = FRAME_attack1 - 1;
          ent->client->anim_end = FRAME_attack8;
        }
      } else {
        if (level.time >= ent->pain_debounce_time) {
          PF_StartSound(ent, CHAN_VOICE, SV_SoundIndex("weapons/noammo.wav"), 1, ATTN_NORM, 0);
          ent->pain_debounce_time = level.time + 1;
        }

        NoAmmoWeaponChange(ent);
      }
    } else {
      if (ent->client->ps.gunframe == FRAME_IDLE_LAST) {
        ent->client->ps.gunframe = FRAME_IDLE_FIRST;
        return;
      }

      if (pause_frames) {
        for (n = 0; pause_frames[n]; n++) {
          if (ent->client->ps.gunframe == pause_frames[n]) {
            if (randk() & 15) {
              return;
            }
          }
        }
      }

      ent->client->ps.gunframe++;
      return;
    }
  }

  if (ent->client->weaponstate == WEAPON_FIRING) {
    for (n = 0; fire_frames[n]; n++) {
      if (ent->client->ps.gunframe == fire_frames[n]) {
        fire(ent);
        break;
      }
    }

    if (!fire_frames[n]) {
      ent->client->ps.gunframe++;
    }

    if (ent->client->ps.gunframe == FRAME_IDLE_FIRST + 1) {
      ent->client->weaponstate = WEAPON_READY;
    }
  }
}
Esempio n. 10
0
void UserConnection::on(Failed, const string& aLine) noexcept {
	//setState(STATE_UNCONNECTED);  // let the listeners to see the old state
	fire(UserConnectionListener::Failed(), this, aLine);

	delete this;	
}
Esempio n. 11
0
void UserConnection::on(BufferedSocketListener::Line, const string& aLine) throw () {

	COMMAND_DEBUG(aLine, DebugManager::TYPE_CLIENT, DebugManager::INCOMING, getRemoteIp());
	
	if(aLine.length() < 2) {
		fire(UserConnectionListener::ProtocolError(), this, "Invalid data"); // TODO: translate
		return;
	}

	if(aLine[0] == 'C' && !isSet(FLAG_NMDC)) {
		if(!Text::validateUtf8(aLine)) {
			fire(UserConnectionListener::ProtocolError(), this, "Non-UTF-8 data in an ADC connection");  // TODO: translate
			return;
		}
		dispatch(aLine);
		return;
	} else if(aLine[0] == '$') {
		setFlag(FLAG_NMDC);
	} else {
		// We shouldn't be here?
		fire(UserConnectionListener::ProtocolError(), this, "Invalid data");  // TODO: translate
		return;
	}

	string cmd;
	string param;

	string::size_type x;
                
	if( (x = aLine.find(' ')) == string::npos) {
		cmd = aLine.substr(1);
	} else {
		cmd = aLine.substr(1, x - 1);
		param = aLine.substr(x+1);
    }
    
	if(cmd == "MyNick") {
		if(!param.empty())
			fire(UserConnectionListener::MyNick(), this, param);
	} else if(cmd == "Direction") {
		x = param.find(" ");
		if(x != string::npos) {
			fire(UserConnectionListener::Direction(), this, param.substr(0, x), param.substr(x+1));
		}
	} else if(cmd == "Error") {
		if(Util::stricmp(param.c_str(), FILE_NOT_AVAILABLE) == 0 ||
			param.rfind(/*path/file*/" no more exists") != string::npos) { 
    		fire(UserConnectionListener::FileNotAvailable(), this);
    	} else {
			fire(UserConnectionListener::ProtocolError(), this, param);
	    }
	} else if(cmd == "GetListLen") {
    	fire(UserConnectionListener::GetListLength(), this);
	} else if(cmd == "Get") {
		x = param.find('$');
		if(x != string::npos) {
			fire(UserConnectionListener::Get(), this, Text::toUtf8(param.substr(0, x), encoding), Util::toInt64(param.substr(x+1)) - (int64_t)1);
	    }
	} else if(cmd == "Key") {
		if(!param.empty())
			fire(UserConnectionListener::Key(), this, param);
	} else if(cmd == "Lock") {
		if(!param.empty()) {
			x = param.find(" Pk=");
			if(x != string::npos) {
				fire(UserConnectionListener::CLock(), this, param.substr(0, x));
			} else {
				// Workaround for faulty linux clients...
				x = param.find(' ');
				if(x != string::npos) {
					fire(UserConnectionListener::CLock(), this, param.substr(0, x));
	    		} else {
					fire(UserConnectionListener::CLock(), this, param);
    			}
	        }
       	}
	} else if(cmd == "Send") {
    	fire(UserConnectionListener::Send(), this);
	} else if(cmd == "MaxedOut") {
		fire(UserConnectionListener::MaxedOut(), this, param);
	} else if(cmd == "Supports") {
		if(!param.empty()) {
			fire(UserConnectionListener::Supports(), this, StringTokenizer<string>(param, ' ').getTokens());
	    }
	} else if(cmd.compare(0, 3, "ADC") == 0) {
    	dispatch(aLine, true);
	} else if (cmd == "ListLen") {
		if(!param.empty()) {
			fire(UserConnectionListener::ListLength(), this, param);
		}
	} else {

		
		fire(UserConnectionListener::ProtocolError(), this, "Invalid data"); // TODO: translate
	}
}
Esempio n. 12
0
void UserConnection::on(TransmitDone) noexcept {
	fire(UserConnectionListener::TransmitDone(), this);
}
Esempio n. 13
0
void UserConnection::on(ModeChange) noexcept { 
	lastActivity = GET_TICK(); 
	fire(UserConnectionListener::ModeChange(), this); 
}
Esempio n. 14
0
void UserConnection::on(BytesSent, size_t bytes, size_t actual) noexcept { 
	lastActivity = GET_TICK();
	fire(UserConnectionListener::BytesSent(), this, bytes, actual); 
}
Esempio n. 15
0
void beforegame()								/******游戏主界面*******/
{
	int i,j;

	fire();

	ShowBmp256(70,65,".\\source\\login.bmp",1,0);

	InitGraph();
	star=malloc(sizeof(struct STAR)*STARNUM);
	initstar(star);
	InitMouse(0,0,maxx,maxy);

	getdat();
	handler=getvect(0x1c);

	mousex=getmaxx()/2;
	mousey=getmaxy()/2;

	logo=bmp_to_dat(".\\source\\snooker.bmp");
	vs1=bmp_to_dat(".\\source\\head0.bmp");
	vs2=bmp_to_dat(".\\source\\head1.bmp");

	play(1);
	for (i=0;i<3;i++)
	{
		putimage(0,0,logo,NOT_PUT);
		for (j=20;j<=1000;j+=10)
		{
			delay(1000);
		}
		delay(3000);
		putimage(0,0,logo,COPY_PUT);
		for (j=1000;j>=20;j-=10)
		{
			delay(2000);
		}
		delay(3000);
	}
	putimage(0,0,logo,COPY_PUT);
	for (i=0;i<STARNUM;i++) drawstar(star);

	outchinese(400,80,s_cn,EOF,4,2);
	putimage(300,280,vs1,COPY_PUT);
	putimage(520,280,vs2,COPY_PUT);

	settextstyle(1,0,12);
	setcolor(GREEN);
	outtextxy(380,260,"Vs");

	drawmouse(mousex,mousey);
	play(2);
	drawmenu(mm);
	while(1)
	{
		while(bioskey(1)!=0) getch();
		position(1);
		mm=fill();
		drawmouse(mousex,mousey);
		if (button==1)
		{
			switch (mm)
			{
				case 0:
					{
						free(logo);
						free(star);
						cleardevice();
						return;
					}
				case 1:
					{
						practice();
						restore();
						break;
					}
				case 2:
					{
						noplay();
						option();
						break;
					}
				case 3:
					{
						noplay();
						toprank();
						restore();
						break;
					}
				case 4:
					{
						if (Music_on==1) play(0);
						showhelp();
						break;
					}
				case 5:
					{
						position(0);
						End(1);
						drawmouse(mousex,mousey);
						break;
					}
			}
		}
		button=0;
	}
}
Esempio n. 16
0
void MummyDragon::move(Map *map)
{
    Monster::move(map);

    switch(m_action) {
        case Still:
            set_action(Move);
            break;

        case Move:
            if (m_is_flying) {
                set_speed(0, m_fly_speed);
                if (m_fly_timer.check(m_fly_time) ||
                    m_y < m_top || m_y > m_bottom) {
                    m_fly_timer.reset();
                    m_is_flying = false;
                }
            }
            else {
                if (get_left() < m_left || get_right() > m_right) {
                    swap_move_dir();
                    if (m_turn_counter.expired(get_attribute("num_turns"))) {
                        m_fly_time = 600;
                        if (m_y < m_top + 100) {
                            m_fly_speed = get_attribute("fly_speed");
                        }
                        else {
                            m_fly_speed = -get_attribute("fly_speed");
                        }
                        m_is_flying = true;
                    }
                    else {
                        m_attack_timer.enable(true);
                    }
                }

                if (m_dir == Right) {
                    set_speed(get_move_speed(map), 0);
                }
                else {
                    set_speed(-get_move_speed(map), 0);
                }
            }

            animate_move();

            if (m_attack_timer.expired(get_attribute("attack_timer"))) {
                m_attack_timer.enable(false);
                set_attack();
            }
            break;

        case Attack:
            fire();
            break;

        case Hit:
            m_fly_time = get_attribute("fly_time_after_hit");
            m_fly_speed = -get_attribute("fly_speed");
            m_is_flying = true;
            break;

        default:
            break;
    }

    unsigned n = m_bullets.size();
    for (unsigned i = 0; i < n; i++) {
        m_bullets[i]->move(map);
    }
}
Esempio n. 17
0
void inventory::form_from_map( const tripoint &origin, int range, bool assign_invlet )
{
    items.clear();
    for( const tripoint &p : g->m.points_in_radius( origin, range ) ) {
        // can not reach this -> can not access its contents
        if( origin != p && !g->m.clear_path( origin, p, range, 1, 100 ) ) {
            continue;
        }

        if( g->m.has_furn( p ) ) {
            const furn_t &f = g->m.furn( p ).obj();
            const itype *type = f.crafting_pseudo_item_type();
            if (type != NULL) {
                const itype *ammo = f.crafting_ammo_item_type();
                item furn_item( type, calendar::turn, 0);
                furn_item.item_tags.insert("PSEUDO");
                furn_item.charges = ammo ? count_charges_in_list(ammo, g->m.i_at(p)) : 0;
                add_item(furn_item);
            }
        }
        if( g->m.accessible_items( p ) ) {
            for( auto &i : g->m.i_at( p ) ) {
                if( !i.made_of( LIQUID ) ) {
                    add_item( i, false, assign_invlet );
                }
            }
        }
        // Kludges for now!
        if (g->m.has_nearby_fire( p, 0 )) {
            item fire("fire", 0);
            fire.charges = 1;
            add_item(fire);
        }
        // Handle any water from infinite map sources.
        item water = g->m.water_from( p );
        if( !water.is_null() ) {
            add_item( water );
        }
        // kludge that can probably be done better to check specifically for toilet water to use in
        // crafting
        if (g->m.furn( p ).obj().examine == &iexamine::toilet) {
            // get water charges at location
            auto toilet = g->m.i_at( p );
            auto water = toilet.end();
            for( auto candidate = toilet.begin(); candidate != toilet.end(); ++candidate ) {
                if( candidate->typeId() == "water" ) {
                    water = candidate;
                    break;
                }
            }
            if( water != toilet.end() && water->charges > 0) {
                add_item( *water );
            }
        }

        // keg-kludge
        if (g->m.furn( p ).obj().examine == &iexamine::keg) {
            auto liq_contained = g->m.i_at( p );
            for( auto &i : liq_contained ) {
                if( i.made_of(LIQUID) ) {
                    add_item(i);
                }
            }
        }

        // WARNING: The part below has a bug that's currently quite minor
        // When a vehicle has multiple faucets in range, available water is
        //  multiplied by the number of faucets.
        // Same thing happens for all other tools and resources, but not cargo
        const optional_vpart_position vp = g->m.veh_at( p );
        if( !vp ) {
            continue;
        }
        vehicle *const veh = &vp->vehicle();

        //Adds faucet to kitchen stuff; may be horribly wrong to do such....
        //ShouldBreak into own variable
        const cata::optional<vpart_reference> kpart = vp.part_with_feature( "KITCHEN" );
        const cata::optional<vpart_reference> faupart = vp.part_with_feature( "FAUCET" );
        const cata::optional<vpart_reference> weldpart = vp.part_with_feature( "WELDRIG" );
        const cata::optional<vpart_reference> craftpart = vp.part_with_feature( "CRAFTRIG" );
        const cata::optional<vpart_reference> forgepart = vp.part_with_feature( "FORGE" );
        const cata::optional<vpart_reference> chempart = vp.part_with_feature( "CHEMLAB" );
        const cata::optional<vpart_reference> cargo = vp.part_with_feature( "CARGO" );

        if( cargo ) {
            const auto items = veh->get_items( cargo->part_index() );
            *this += std::list<item>( items.begin(), items.end() );
        }

        if( faupart ) {
            for( const auto &it : veh->fuels_left() ) {
                item fuel( it.first , 0 );
                if( fuel.made_of( LIQUID ) ) {
                    fuel.charges = it.second;
                    add_item( fuel );
                }
            }
        }

        if( kpart ) {
            item hotplate("hotplate", 0);
            hotplate.charges = veh->fuel_left("battery", true);
            hotplate.item_tags.insert("PSEUDO");
            add_item(hotplate);

            item pot("pot", 0);
            pot.item_tags.insert("PSEUDO");
            add_item(pot);
            item pan("pan", 0);
            pan.item_tags.insert("PSEUDO");
            add_item(pan);
        }
        if( weldpart ) {
            item welder("welder", 0);
            welder.charges = veh->fuel_left("battery", true);
            welder.item_tags.insert("PSEUDO");
            add_item(welder);

            item soldering_iron("soldering_iron", 0);
            soldering_iron.charges = veh->fuel_left("battery", true);
            soldering_iron.item_tags.insert("PSEUDO");
            add_item(soldering_iron);
        }
        if( craftpart ) {
            item vac_sealer("vac_sealer", 0);
            vac_sealer.charges = veh->fuel_left("battery", true);
            vac_sealer.item_tags.insert("PSEUDO");
            add_item(vac_sealer);

            item dehydrator("dehydrator", 0);
            dehydrator.charges = veh->fuel_left("battery", true);
            dehydrator.item_tags.insert("PSEUDO");
            add_item(dehydrator);

            item food_processor("food_processor", 0);
            food_processor.charges = veh->fuel_left("battery", true);
            food_processor.item_tags.insert("PSEUDO");
            add_item(food_processor);

            item press("press", 0);
            press.charges = veh->fuel_left("battery", true);
            press.item_tags.insert("PSEUDO");
            add_item(press);
        }
        if( forgepart ) {
            item forge("forge", 0);
            forge.charges = veh->fuel_left("battery", true);
            forge.item_tags.insert("PSEUDO");
            add_item(forge);
        }
        if( chempart ) {
            item hotplate("hotplate", 0);
            hotplate.charges = veh->fuel_left("battery", true);
            hotplate.item_tags.insert("PSEUDO");
            add_item(hotplate);

            item chemistry_set("chemistry_set", 0);
            chemistry_set.charges = veh->fuel_left("battery", true);
            chemistry_set.item_tags.insert("PSEUDO");
            add_item(chemistry_set);
        }
    }
}
Esempio n. 18
0
Status AuditEventPublisher::run() {
  if (!FLAGS_disable_audit && (count_ == 0 || count_++ % 10 == 0)) {
    // Request an update to the audit status.
    // This will also fill in the status on first run.
    audit_request_status(handle_);
  }

  // Reset the reply data.
  int result = 0;
  bool handle_reply = false;
  while (true) {
    handle_reply = false;

    // Request a reply in a non-blocking mode.
    // This allows the publisher's run loop to periodically request an audit
    // status update. These updates can check for other processes attempting to
    // gain control over the audit sink.
    // This non-blocking also allows faster receipt of multi-message events.
    result = audit_get_reply(handle_, &reply_, GET_REPLY_NONBLOCKING, 0);
    if (result > 0) {
      switch (reply_.type) {
      case NLMSG_NOOP:
      case NLMSG_DONE:
      case NLMSG_ERROR:
        // Not handled, request another reply.
        break;
      case AUDIT_LIST_RULES:
        // Build rules cache.
        handleListRules();
        break;
      case AUDIT_GET:
        // Make a copy of the status reply and store as the most-recent.
        if (reply_.status != nullptr) {
          memcpy(&status_, reply_.status, sizeof(struct audit_status));
        }
        break;
      case AUDIT_FIRST_USER_MSG... AUDIT_LAST_USER_MSG:
        handle_reply = true;
        break;
      case (AUDIT_GET + 1)...(AUDIT_LIST_RULES - 1):
      case (AUDIT_LIST_RULES + 1)...(AUDIT_FIRST_USER_MSG - 1):
        // Not interested in handling meta-commands and actions.
        break;
      case AUDIT_DAEMON_START... AUDIT_DAEMON_CONFIG: // 1200 - 1203
      case AUDIT_CONFIG_CHANGE:
        handleAuditConfigChange(reply_);
        break;
      case AUDIT_SYSCALL: // 1300
        // A monitored syscall was issued, most likely part of a multi-record.
        handle_reply = true;
        break;
      case AUDIT_CWD: // 1307
      case AUDIT_PATH: // 1302
      case AUDIT_EXECVE: // // 1309 (execve arguments).
        handle_reply = true;
      case AUDIT_EOE: // 1320 (multi-record event).
        break;
      default:
        // All other cases, pass to reply.
        handle_reply = true;
      }
    } else {
      // Fall through to the run loop cool down.
      break;
    }

    // Replies are 'handled' as potential events for several audit types.
    if (handle_reply) {
      auto ec = createEventContext();
      // Build the event context from the reply type and parse the message.
      if (handleAuditReply(reply_, ec)) {
        fire(ec);
      }
    }
  }
Esempio n. 19
0
/* test function */
int test(char *URL)
{
    int res;
    CURLSHcode scode;
    char *url;
    struct Tdata tdata;
    CURL *curl;
    CURLSH *share;
    struct curl_slist *headers;
    int i;
    struct userdata user;

    user.text = (char *)"Pigs in space";
    user.counter = 0;

    printf( "GLOBAL_INIT\n" );
    curl_global_init( CURL_GLOBAL_ALL );

    /* prepare share */
    printf( "SHARE_INIT\n" );
    share = curl_share_init();
    curl_share_setopt( share, CURLSHOPT_LOCKFUNC,   lock);
    curl_share_setopt( share, CURLSHOPT_UNLOCKFUNC, unlock);
    curl_share_setopt( share, CURLSHOPT_USERDATA,   &user);
    printf( "CURL_LOCK_DATA_COOKIE\n" );
    curl_share_setopt( share, CURLSHOPT_SHARE,      CURL_LOCK_DATA_COOKIE);
    printf( "CURL_LOCK_DATA_DNS\n" );
    curl_share_setopt( share, CURLSHOPT_SHARE,      CURL_LOCK_DATA_DNS);

    res = 0;

    /* start treads */
    for (i=1; i<=THREADS; i++ )
    {

        /* set thread data */
        tdata.url   = suburl( URL, i ); /* must be freed */
        tdata.share = share;

        /* simulate thread, direct call of "thread" function */
        printf( "*** run %d\n",i );
        fire( &tdata );

        free( tdata.url );

    }


    /* fetch a another one and save cookies */
    printf( "*** run %d\n", i );
    curl = curl_easy_init();

    url = suburl( URL, i );
    headers = sethost( NULL );
    curl_easy_setopt( curl, CURLOPT_HTTPHEADER, (void*)headers );
    curl_easy_setopt( curl, CURLOPT_URL,        url );
    printf( "CURLOPT_SHARE\n" );
    curl_easy_setopt( curl, CURLOPT_SHARE,      share );
    printf( "CURLOPT_COOKIEJAR\n" );
    curl_easy_setopt( curl, CURLOPT_COOKIEJAR,  JAR );

    printf( "PERFORM\n" );
    curl_easy_perform( curl );

    /* try to free share, expect to fail because share is in use*/
    printf( "try SHARE_CLEANUP...\n" );
    scode = curl_share_cleanup( share );
    if ( scode==CURLSHE_OK )
    {
        fprintf(stderr, "curl_share_cleanup succeed but error expected\n");
        share = NULL;
    }
    else
    {
        printf( "SHARE_CLEANUP failed, correct\n" );
    }

    /* clean up last handle */
    printf( "CLEANUP\n" );
    curl_easy_cleanup( curl );
    curl_slist_free_all( headers );
    free(url);


    /* free share */
    printf( "SHARE_CLEANUP\n" );
    scode = curl_share_cleanup( share );
    if ( scode!=CURLSHE_OK )
    {
        fprintf(stderr, "curl_share_cleanup failed, code errno %d\n", scode);
    }

    printf( "GLOBAL_CLEANUP\n" );
    curl_global_cleanup();

    return res;
}
Esempio n. 20
0
int DirectoryMonitor::Server::read() {
	DWORD		dwBytesXFered = 0;
	ULONG_PTR	ulKey = 0;
	OVERLAPPED*	pOl;

	auto ret = GetQueuedCompletionStatus(m_hIOCP, &dwBytesXFered, &ulKey, &pOl, INFINITE);
	auto dwError = GetLastError();
	if (!ret) {
		if (!m_hIOCP) {
			// shutting down
			return 0;
		}

		if (dwError == WAIT_TIMEOUT) {
			//harmless
			return 1;
		}
	}

	{
		WLock l(cs);
		auto mon = find_if(monitors | map_values, [ulKey](const Monitor* m) { return (ULONG_PTR)m->key == ulKey; });
		if (mon.base() != monitors.end()) {
			if (!(*mon)->m_hDirectory) {
				//this is going to be deleted
				deleteDirectory(mon.base());
				return 1;
			}

			try {
				if (dwError != 0 || !ret) {
					// Too many changes to track, http://blogs.msdn.com/b/oldnewthing/archive/2011/08/12/10195186.aspx
					// The documentation only states the code ERROR_NOTIFY_ENUM_DIR for this, but according to the testing ERROR_NOT_ENOUGH_QUOTA and ERROR_ALREADY_EXISTS seem to be used instead....
					// (and ERROR_TOO_MANY_CMDS with network drives)
					if (dwError == ERROR_NOTIFY_ENUM_DIR || dwError == ERROR_NOT_ENOUGH_QUOTA || dwError == ERROR_ALREADY_EXISTS || dwError == ERROR_TOO_MANY_CMDS) {
						(*mon)->beginRead();
						auto base = (*mon)->server->base;
						base->callAsync([=] { base->fire(DirectoryMonitorListener::Overflow(), (*mon)->path); });
					} else {
						throw MonitorException(getErrorStr(dwError));
					}
				} else {
					if ((*mon)->errorCount > 0) {
						//LogManager::getInstance()->message("Monitoring was successfully restored for " + Text::fromT((*mon)->path), LogManager::LOG_ERROR);
						(*mon)->errorCount = 0;
					}

					if (dwBytesXFered > 0) {
						(*mon)->changes++;
						(*mon)->queueNotificationTask(dwBytesXFered);
					} /*else {
						LogManager::getInstance()->message("An empty notification was received when monitoring " + Text::fromT((*mon)->path) + " (report this)", LogManager::LOG_WARNING);
					}*/

					(*mon)->beginRead();
				}
			} catch (const MonitorException& e) {
				(*mon)->errorCount++;
				if ((*mon)->errorCount < 60) {
					//we'll most likely get the error instantly again...
					Thread::sleep(1000);

					try {
						(*mon)->openDirectory(m_hIOCP);
						(*mon)->beginRead();
						return 1;
					} catch (const MonitorException& /*e*/) {
						//go to removal
					}
				}

				//remove this
				(*mon)->stopMonitoring();
				(*mon)->server->base->fire(DirectoryMonitorListener::DirectoryFailed(), (*mon)->path, e.getError());
				deleteDirectory(mon.base());
			}
		}
	}

	return 1;
}
Esempio n. 21
0
void display_loop(){
//	mcuf_serial_mode();

	mode = setjmp(newmode_jmpbuf);

#ifdef JOYSTICK_SUPPORT
	// in case we get here via mode jump, we (re)enable joystick queries
	waitForFire = 1;
#endif

	oldOldmode = oldMode;

#ifdef JOYSTICK_SUPPORT
	waitForFire = 1;
#endif

	for(;;){
#ifndef MENU_SUPPORT
		clear_screen(0);
#endif
		oldMode = mode;

		switch(mode++) {

#ifdef ANIMATION_SCROLLTEXT
		case 1:
			scrolltext(scrolltext_text);

	#ifdef RANDOM_SUPPORT
			{
				char a[28];
				sprintf(a,"</# counter == %lu  ",
					(unsigned long)percnt_get(&g_reset_counter, &g_reset_counter_idx));
				scrolltext(a);
			}
	#endif
#endif
#ifdef ANIMATION_TIME
#ifndef ANIMATION_SCROLLTEXT
		case 1:
#endif
			time_anim();
			break;
#else
#ifdef ANIMATION_SCROLLTEXT
			break;
#endif
#endif

#ifdef ANIMATION_SPIRAL
#		ifndef SPIRAL_DELAY
#			define SPIRAL_DELAY 5
#		endif

		case 2:
			spiral(SPIRAL_DELAY);
			break;
#endif

#ifdef ANIMATION_JOERN1
		case 3:
			joern1();
			break;
#endif

#ifdef ANIMATION_SNAKE
		case 4:
			snake_animation();
			break;
#endif

#ifdef ANIMATION_CHECKERBOARD
		case 5:
			checkerboard(20);
			break;
#endif

#ifdef ANIMATION_FIRE
		case 6:
			fire();
			break;
#endif

#ifdef ANIMATION_TIME
		case 7:
			time_anim();
			break;
#endif

#ifdef ANIMATION_MATRIX
		case 8:
			matrix();
			break;
#endif

#ifdef ANIMATION_RANDOM_BRIGHT
		case 9:
			random_bright(30);
			break;
#endif

#ifdef ANIMATION_STONEFLY
		case 10:
			stonefly();
			break;
#endif

#ifdef ANIMATION_GAMEOFLIFE
		case 11:
			gameoflife();
			break;
#endif

#ifdef ANIMATION_FLYINGDOTS
		case 12:
			flyingdots();
			break;
#endif

#ifdef ANIMATION_BREAKOUT
		case 13:
			breakout_demo();
			break;
#endif

#ifdef ANIMATION_MHERWEG
		case 14:
			mherweg();
			break;
#endif

#ifdef ANIMATION_MOIRE
		case 15:
			moire();
			break;
#endif

#ifdef ANIMATION_TIME
		case 16:
			time_anim();
			break;
#endif

#ifdef ANIMATION_LTN_ANT
		case 17:
			ltn_ant();
			break;
#endif

#ifdef ANIMATION_LABORLOGO
		case 18:
			laborlogo();
			break;
#endif

#ifdef ANIMATION_AMPHIBIAN
		case 19:
			amphibian();
			break;
#endif

#ifdef ANIMATION_LOGO_OOS
		case 20:
			logo_OutOfSpec();
			break;
#endif

#ifdef ANIMATION_FAIRYDUST
		case 21:
			fairydust();
			break;
#endif

#ifdef ANIMATION_PLASMA
		case 22:
			plasma();
			break;
#endif

#ifdef ANIMATION_PSYCHEDELIC
		case 23:
			psychedelic();
			break;
#endif

#ifdef ANIMATION_BLACKHOLE
		case 24:
			blackhole();
			break;
#endif

#ifdef ANIMATION_SQUARES
		case 25:
			squares();
			break;
#endif

#ifdef ANIMATION_DNA
		case 26:
			dna();
			break;
#endif

#ifdef ANIMATION_TESTS
		case 31:
			test_level(1, false);
			break;

		case 32:
			test_level(2, false);
			break;

		case 33:
			test_level(3, false);
			break;

		case 35:
			test_palette(false);
			test_palette2(false);
			break;
#endif

#ifdef SMALLANIMATION_ROWWALK
		case 36:
		  rowwalk(SMALLANIMATION_ROWWALK_COUNT,SMALLANIMATION_ROWWALK_SPEED);
		  break;
#endif

#ifdef SMALLANIMATION_COLWALK
		case 37:
		  colwalk(SMALLANIMATION_COLWALK_COUNT,SMALLANIMATION_COLWALK_SPEED);
		  break;
#endif
#ifdef SMALLANIMATION_COLBOUNCE
		case 38:
		  colbounce(SMALLANIMATION_COLBOUNCE_COUNT,SMALLANIMATION_COLBOUNCE_SPEED);
		  break;
#endif
#ifdef SMALLANIMATION_ROWBOUNCE
		case 39:
		  rowbounce(SMALLANIMATION_ROWBOUNCE_COUNT,SMALLANIMATION_ROWBOUNCE_SPEED);
		  break;
#endif

#ifdef MENU_SUPPORT
		case 0xFDu:
			mode = 1;
			break;

		case 0xFEu:
			menu();
			mode = oldOldmode;
			break;
#else

		case 0xFDu:
#ifdef JOYSTICK_SUPPORT
			if (JOYISFIRE)
				mode = 0xFEu;
			else
#endif
				mode = 1;
			break;

		case 0xFEu:
#ifdef JOYSTICK_SUPPORT
			waitForFire = 0;   // avoid circular jumps
			while (JOYISFIRE); // wait until user released the fire button
#endif
			wait(25);          // wait for button to settle

#  ifdef GAME_TETRIS
			tetris();
#  endif

#  ifdef GAME_BASTET
			tetris_bastet();
#  endif

#  ifdef GAME_TETRIS_FP
			tetris_fp();
#  endif

#  ifdef GAME_SPACE_INVADERS
			borg_invaders();
#  endif

#  ifdef GAME_SNAKE
			snake_game();
#  endif

#  ifdef GAME_BREAKOUT
			borg_breakout(0);
#  endif

#ifdef JOYSTICK_SUPPORT
			while (JOYISFIRE); // avoid an unwanted restart of the game loop
#endif
			wait(25);          // wait for button to settle
			mode = oldOldmode; // restore old animation mode
#ifdef JOYSTICK_SUPPORT
			waitForFire = 1;   // reenable joystick query of the wait() function
#endif
			break;
#endif

#ifdef ANIMATION_OFF
		case 0xFFu:
			off();
			break;
#endif
		default:
			if (reverseMode) {
				if (reverseMode-- == (mode - 1)) {
					mode -= 2;
				} else {
					reverseMode = 0;
				}
			}
			break;
		}
	}
}
Esempio n. 22
0
	void Session::onSocketDisconnected() noexcept {
		// Set the expiration time from this moment if there is no further activity
		updateActivity();

		fire(SessionListener::SocketDisconnected());
	}
Esempio n. 23
0
Status KernelEventPublisher::run() {
  {
    WriteLock lock(mutex_);
    if (queue_ == nullptr) {
      return Status(1, "No kernel communication");
    }
  }

  // Perform queue read min/max synchronization.
  try {
    int drops = 0;
    WriteLock lock(mutex_);
    if ((drops = queue_->kernelSync(OSQUERY_OPTIONS_NO_BLOCK)) > 0 &&
        kToolType == ToolType::DAEMON) {
      LOG(WARNING) << "Dropping " << drops << " kernel events";
    }
  } catch (const CQueueException &e) {
    LOG(WARNING) << "Queue synchronization error: " << e.what();
  }

  auto dequeueEvents = [this]() {
    // Dequeue several events while holding the lock.
    int max_before_lock = kKernelEventsIterate;
    while (max_before_lock > 0) {
      // Request an event from the synchronized, safe, portion of the queue.
      CQueue::event *event = nullptr;
      auto event_type = queue_->dequeue(&event);
      if (event_type == OSQUERY_NULL_EVENT) {
        return false;
      }

      // Each event type may use a specific event type structure.
      KernelEventContextRef ec = nullptr;
      switch (event_type) {
      case OSQUERY_PROCESS_EVENT:
        ec = createEventContextFrom<osquery_process_event_t>(event_type, event);
        fire(ec);
        break;
      case OSQUERY_FILE_EVENT:
        ec = createEventContextFrom<osquery_file_event_t>(event_type, event);
        fire(ec);
        break;
      default:
        LOG(WARNING) << "Unknown kernel event received: " << event_type;
        break;
      }
      max_before_lock--;
    }
    return true;
  };

  // Iterate over each event type in the queue and appropriately fire each.
  int max_before_sync = kKernelEventsSyncMax;
  while (max_before_sync > 0) {
    WriteLock lock(mutex_);
    // The kernel publisher may have been torn down.
    if (queue_ == nullptr) {
      break;
    }
    // A NULL event occurred, stop dequeuing.
    if (!dequeueEvents()) {
      break;
    }
    // Append the number of dequeue events to the synchronization counter.
    max_before_sync -= kKernelEventsIterate;
  }

  // Pause for a cool-off since we implement comms in a no-blocking mode.
  pauseMilli(1000);
  return Status(0, "Continue");
}
Esempio n. 24
0
int vehicle::automatic_fire_turret( vehicle_part &pt )
{
    auto gun = turret_query( pt );
    if( gun.query() != turret_data::status::ready ) {
        return 0;
    }

    tripoint pos = global_part_pos3( pt );

    npc tmp;
    tmp.set_fake( true );
    tmp.name = rmp_format( _( "<veh_player>The %s" ), pt.name().c_str() );
    tmp.set_skill_level( gun.base()->gun_skill(), 8 );
    tmp.set_skill_level( skill_id( "gun" ), 4 );
    tmp.recoil = abs( velocity ) / 100 / 4;
    tmp.setpos( pos );
    tmp.str_cur = 16;
    tmp.dex_cur = 8;
    tmp.per_cur = 12;
    // Assume vehicle turrets are friendly to the player.
    tmp.attitude = NPCATT_FOLLOW;

    int area = aoe_size( gun.ammo_effects() );
    if( area > 0 ) {
        area += area == 1 ? 1 : 2; // Pad a bit for less friendly fire
    }

    tripoint targ = pos;
    auto &target = pt.target;
    if( target.first == target.second ) {
        // Manual target not set, find one automatically
        const bool u_see = g->u.sees( pos );
        int boo_hoo;

        // @todo calculate chance to hit and cap range based upon this
        int range = std::min( gun.range(), 12 );
        Creature *auto_target = tmp.auto_find_hostile_target( range, boo_hoo, area );
        if( auto_target == nullptr ) {
            if( u_see && boo_hoo ) {
                add_msg( m_warning, ngettext( "%s points in your direction and emits an IFF warning beep.",
                                              "%s points in your direction and emits %d annoyed sounding beeps.",
                                              boo_hoo ),
                         tmp.name.c_str(), boo_hoo );
            }
            return 0;
        }

        targ = auto_target->pos();
    } else if( target.first != target.second ) {
        // Target set manually
        // Make sure we didn't move between aiming and firing (it's a bug if we did)
        if( targ != target.first ) {
            target.second = target.first;
            return 0;
        }

        targ = target.second;
        // Remove the target
        target.second = target.first;
    } else {
        // Shouldn't happen
        target.first = target.second;
        return 0;
    }

    auto shots = gun.fire( tmp, targ );

    if( g->u.sees( pos ) && shots ) {
        add_msg( _( "The %1$s fires its %2$s!" ), name.c_str(), pt.name().c_str() );
    }

    return shots;
}
void SettingsManager::save(string const& aFileName) {

    SimpleXML xml;
    xml.addTag("DCPlusPlus");
    xml.stepIn();
    xml.addTag("Settings");
    xml.stepIn();

    int i;
    string type("type"), curType("string");

    for(i=STR_FIRST; i<STR_LAST; i++)
    {
        if(i == CONFIG_VERSION) {
            xml.addTag(settingTags[i], VERSIONSTRING);
            xml.addChildAttrib(type, curType);
        } else if(isSet[i]) {
            xml.addTag(settingTags[i], get(StrSetting(i), false));
            xml.addChildAttrib(type, curType);
        }
    }

    curType = "int";
    for(i=INT_FIRST; i<INT_LAST; i++)
    {
        if(isSet[i]) {
            xml.addTag(settingTags[i], get(IntSetting(i), false));
            xml.addChildAttrib(type, curType);
        }
    }
    for(i=FLOAT_FIRST; i<FLOAT_LAST; i++)
    {
        if(isSet[i]) {
            xml.addTag(settingTags[i], static_cast<int>(get(FloatSetting(i), false) * 1000.));
            xml.addChildAttrib(type, curType);
        }
    }
    curType = "int64";
    for(i=INT64_FIRST; i<INT64_LAST; i++)
    {
        if(isSet[i])
        {
            xml.addTag(settingTags[i], get(Int64Setting(i), false));
            xml.addChildAttrib(type, curType);
        }
    }
    xml.stepOut();

    xml.addTag("SearchTypes");
    xml.stepIn();
    for(SearchTypesIterC i = searchTypes.begin(); i != searchTypes.end(); ++i) {
        xml.addTag("SearchType", Util::toString(";", i->second));
        xml.addChildAttrib("Id", i->first);
    }
    xml.stepOut();

    fire(SettingsManagerListener::Save(), xml);

    try {
        File out(aFileName + ".tmp", File::WRITE, File::CREATE | File::TRUNCATE);
        BufferedOutputStream<false> f(&out);
        f.write(SimpleXML::utf8Header);
        xml.toXML(&f);
        f.flush();
        out.close();
        File::deleteFile(aFileName);
        File::renameFile(aFileName + ".tmp", aFileName);
    } catch(const FileException&) {
        // ...
    }
}
Esempio n. 26
0
/* test function */
int test(char *URL)
{
  int res;
  CURLSHcode scode = CURLSHE_OK;
  char *url = NULL;
  struct Tdata tdata;
  CURL *curl;
  CURLSH *share;
  struct curl_slist *headers = NULL;
  int i;
  struct userdata user;

  user.text = (char *)"Pigs in space";
  user.counter = 0;

  printf( "GLOBAL_INIT\n" );
  if (curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK) {
    fprintf(stderr, "curl_global_init() failed\n");
    return TEST_ERR_MAJOR_BAD;
  }

  /* prepare share */
  printf( "SHARE_INIT\n" );
  if ((share = curl_share_init()) == NULL) {
    fprintf(stderr, "curl_share_init() failed\n");
    curl_global_cleanup();
    return TEST_ERR_MAJOR_BAD;
  }

  if ( CURLSHE_OK == scode ) {
    printf( "CURLSHOPT_LOCKFUNC\n" );
    scode = curl_share_setopt( share, CURLSHOPT_LOCKFUNC, my_lock);
  }
  if ( CURLSHE_OK == scode ) {
    printf( "CURLSHOPT_UNLOCKFUNC\n" );
    scode = curl_share_setopt( share, CURLSHOPT_UNLOCKFUNC, my_unlock);
  }
  if ( CURLSHE_OK == scode ) {
    printf( "CURLSHOPT_USERDATA\n" );
    scode = curl_share_setopt( share, CURLSHOPT_USERDATA, &user);
  }
  if ( CURLSHE_OK == scode ) {
    printf( "CURL_LOCK_DATA_COOKIE\n" );
    scode = curl_share_setopt( share, CURLSHOPT_SHARE, CURL_LOCK_DATA_COOKIE);
  }
  if ( CURLSHE_OK == scode ) {
    printf( "CURL_LOCK_DATA_DNS\n" );
    scode = curl_share_setopt( share, CURLSHOPT_SHARE, CURL_LOCK_DATA_DNS);
  }

  if ( CURLSHE_OK != scode ) {
    fprintf(stderr, "curl_share_setopt() failed\n");
    curl_share_cleanup(share);
    curl_global_cleanup();
    return TEST_ERR_MAJOR_BAD;
  }

  /* initial cookie manipulation */
  if ((curl = curl_easy_init()) == NULL) {
    fprintf(stderr, "curl_easy_init() failed\n");
    curl_share_cleanup(share);
    curl_global_cleanup();
    return TEST_ERR_MAJOR_BAD;
  }
  printf( "CURLOPT_SHARE\n" );
  test_setopt( curl, CURLOPT_SHARE,      share );
  printf( "CURLOPT_COOKIELIST injected_and_clobbered\n" );
  test_setopt( curl, CURLOPT_COOKIELIST,
               "Set-Cookie: injected_and_clobbered=yes; "
               "domain=host.foo.com; expires=Sat Feb 2 11:56:27 GMT 2030" );
  printf( "CURLOPT_COOKIELIST ALL\n" );
  test_setopt( curl, CURLOPT_COOKIELIST, "ALL" );
  printf( "CURLOPT_COOKIELIST session\n" );
  test_setopt( curl, CURLOPT_COOKIELIST, "Set-Cookie: session=elephants" );
  printf( "CURLOPT_COOKIELIST injected\n" );
  test_setopt( curl, CURLOPT_COOKIELIST,
               "Set-Cookie: injected=yes; domain=host.foo.com; "
               "expires=Sat Feb 2 11:56:27 GMT 2030" );
  printf( "CURLOPT_COOKIELIST SESS\n" );
  test_setopt( curl, CURLOPT_COOKIELIST, "SESS" );
  printf( "CLEANUP\n" );
  curl_easy_cleanup( curl );


  res = 0;

  /* start treads */
  for (i=1; i<=THREADS; i++ ) {

    /* set thread data */
    tdata.url   = suburl( URL, i ); /* must be curl_free()d */
    tdata.share = share;

    /* simulate thread, direct call of "thread" function */
    printf( "*** run %d\n",i );
    fire( &tdata );

    curl_free( tdata.url );

  }


  /* fetch a another one and save cookies */
  printf( "*** run %d\n", i );
  if ((curl = curl_easy_init()) == NULL) {
    fprintf(stderr, "curl_easy_init() failed\n");
    curl_share_cleanup(share);
    curl_global_cleanup();
    return TEST_ERR_MAJOR_BAD;
  }

  url = suburl( URL, i );
  headers = sethost( NULL );
  test_setopt( curl, CURLOPT_HTTPHEADER, headers );
  test_setopt( curl, CURLOPT_URL,        url );
  printf( "CURLOPT_SHARE\n" );
  test_setopt( curl, CURLOPT_SHARE,      share );
  printf( "CURLOPT_COOKIEJAR\n" );
  test_setopt( curl, CURLOPT_COOKIEJAR,  JAR );
  printf( "CURLOPT_COOKIELIST FLUSH\n" );
  test_setopt( curl, CURLOPT_COOKIELIST, "FLUSH" );

  printf( "PERFORM\n" );
  curl_easy_perform( curl );

  /* try to free share, expect to fail because share is in use*/
  printf( "try SHARE_CLEANUP...\n" );
  scode = curl_share_cleanup( share );
  if ( scode==CURLSHE_OK )
  {
    fprintf(stderr, "curl_share_cleanup succeed but error expected\n");
    share = NULL;
  } else {
    printf( "SHARE_CLEANUP failed, correct\n" );
  }

test_cleanup:

  /* clean up last handle */
  printf( "CLEANUP\n" );
  curl_easy_cleanup( curl );

  if ( headers )
    curl_slist_free_all( headers );

  if ( url )
    curl_free(url);

  /* free share */
  printf( "SHARE_CLEANUP\n" );
  scode = curl_share_cleanup( share );
  if ( scode!=CURLSHE_OK )
    fprintf(stderr, "curl_share_cleanup failed, code errno %d\n",
            (int)scode);

  printf( "GLOBAL_CLEANUP\n" );
  curl_global_cleanup();

  return res;
}
void SettingsManager::modSearchType(const string& name, const StringList& extensions) {
    getSearchType(name)->second = extensions;
    fire(SettingsManagerListener::SearchTypesChanged());
}
Esempio n. 28
0
void Hero::onlogic()
{
	
	if(ifire == true)
	{
		procfire();
		return;
	}
	
	hlogic();

	// synchonized logic, based on 'speed' of the hero
	speedc++;
	
	if(speedc > speed)
	{
		speedc = 0;
		// first check for keys then joystick
		
		if(mxhwnd.KeyCheck(DIK_LEFT))
		{
			moveleft();
		}
		
		if(mxhwnd.KeyCheck(DIK_RIGHT))
		{
			moveright();
		}
		
		if(mxhwnd.KeyCheck(DIK_A))
		{
			jump();
		}

		if(mxhwnd.KeyCheck(DIK_S))
		{
			fire();
		}
		
		/*if(player.joystick == true)
		{
			MasterJoyStick* stick = getstick();
			if(stick->JoyLeft())
			{
				moveleft();
			}
			if(stick->JoyRight())
			{
				moveright();
			}
			int b;
			b = stick->JoyButtonDown();
			switch(b)
			{
			case 0:
				jump();
				break;
			case 1:
				fire();
				break;
			}
		}*/
	}
	
	
}
Esempio n. 29
0
int
optionsEditor(dialogMenuItem *self)
{
    int i, optcol, optrow, key;
    static int currOpt = 0;

    dialog_clear_norefresh();
    clear();

    while (1) {
	/* Whap up the header */
	attrset(A_REVERSE); mvaddstr(0, 0, "Options Editor"); attrset(A_NORMAL);
	for (i = 0; i < 2; i++) {
	    mvaddstr(OPT_START_ROW - 2, OPT_NAME_COL + (i * GROUP_OFFSET), "Name");
	    mvaddstr(OPT_START_ROW - 1, OPT_NAME_COL + (i * GROUP_OFFSET), "----");

	    mvaddstr(OPT_START_ROW - 2, OPT_VALUE_COL + (i * GROUP_OFFSET), "Value");
	    mvaddstr(OPT_START_ROW - 1, OPT_VALUE_COL + (i * GROUP_OFFSET), "-----");
	}
	/* And the footer */
	mvprintw(OPT_END_ROW + 1, 0, "Use SPACE to select/toggle an option, arrow keys to move,");
	mvprintw(OPT_END_ROW + 2, 0, "? or F1 for more help.  When you're done, type Q to Quit.");

	optrow = OPT_START_ROW;
	optcol = OPT_NAME_COL;
	for (i = 0; Options[i].name; i++) {
	    /* Names are painted somewhat gratuitously each time, but it's easier this way */
	    mvprintw(optrow, OPT_NAME_COL + optcol, Options[i].name);
	    if (currOpt == i)
		attrset(ATTR_SELECTED);
	    mvprintw(optrow++, OPT_VALUE_COL + optcol, value_of(Options[i]));
	    if (currOpt == i)
		attrset(A_NORMAL);
	    if (optrow == OPT_END_ROW) {
		optrow = OPT_START_ROW;
		optcol += GROUP_OFFSET;
	    }
	    clrtoeol();
	}
	attrset(ATTR_TITLE);
	mvaddstr(OPT_END_ROW + 4, 0, Options[currOpt].desc);
	attrset(A_NORMAL);
	clrtoeol();
	move(0, 14);
        refresh();

	/* Start the edit loop */
	key = toupper(getch());
	switch (key) {
	case KEY_F(1):
	case '?':
	    systemDisplayHelp("options");
	    clear();
	    break;

	case '\020':	/* ^P */
	case KEY_UP:
	    if (currOpt)
		--currOpt;
	    else
		for (currOpt = 0; Options[currOpt + 1].name; currOpt++);
	    continue;

	case '\016':	/* ^N */
	case KEY_DOWN:
	    if (Options[currOpt + 1].name)
		++currOpt;
	    else
		currOpt = 0;
	    continue;

	case KEY_HOME:
	    currOpt = 0;
	    continue;

	case KEY_END:
	    while (Options[currOpt + 1].name)
		++currOpt;
	    continue;

	case ' ':
	    if (fire(Options[currOpt]))
	    	clear();
	    continue;

	case '\033':	/* ESC */
	case 'Q':
	    clear();
	    dialog_clear();
	    return DITEM_SUCCESS | DITEM_RESTORE;

	default:
	    beep();
	}
    }
    /* NOTREACHED */
    return DITEM_SUCCESS | DITEM_RESTORE;
}
Esempio n. 30
0
void UserConnection::on(Connected) noexcept {
	lastActivity = GET_TICK();
    fire(UserConnectionListener::Connected(), this); 
}