示例#1
0
  BOOST_CHRONO_INLINE
  void show_time( const boost::chrono::process_times & times,
                  const char * format, int places, std::ostream & os )
  //  NOTE WELL: Will truncate least-significant digits to LDBL_DIG, which may
  //  be as low as 10, although will be 15 for many common platforms.
  {
    if ( times.real < nanoseconds(0) ) return;
    if ( places > 9 )
      places = 9;  // sanity check
    else if ( places < 0 )
      places = 0;

    boost::io::ios_flags_saver ifs( os );
    os.setf( std::ios_base::fixed, std::ios_base::floatfield );
    boost::io::ios_precision_saver ips( os );
    os.precision( places );

    nanoseconds total = times.system + times.user;

    for ( ; *format; ++format )
    {
      if ( *format != '%' || !*(format+1) || !std::strchr("rcpus", *(format+1)) )
        os << *format;
      else
      {
        ++format;
        switch ( *format )
        {
        case 'r':
          os << duration<double>(times.real).count();
          break;
        case 'u':
          os << duration<double>(times.user).count();
          break;
        case 's':
          os << duration<double>(times.system).count();
          break;
        case 'c':
          os << duration<double>(total).count();
          break;
        case 'p':
          {
            boost::io::ios_precision_saver ips( os );
            os.precision( 1 );
            if ( times.real.count() && total.count() )
              os << duration<double>(total).count()
                   /duration<double>(times.real).count() * 100.0;
            else
              os << 0.0;
          }
          break;
        default:
          BOOST_ASSERT(0 && "run_timer internal logic error");
        }
      }
    }
  }
示例#2
0
	/**
	 * Set this tap's IP addresses to exactly this set of IPs
	 *
	 * New IPs are created. Any IP that overlaps with the network of an IP in
	 * this list is removed, but other IPs are left intact.
	 *
	 * @param ips IP addresses with netmask in port field
	 */
	inline void setIps(const std::set<InetAddress> &allIps)
	{
		for(std::set<InetAddress>::iterator i(allIps.begin());i!=allIps.end();++i)
			addIP(*i);
		std::set<InetAddress> myIps(ips());
#ifdef __APPLE__
		bool haveV6LinkLocal = false;
		for(std::set<InetAddress>::iterator i(myIps.begin());i!=myIps.end();++i) {
			if (i->isLinkLocal()) {
				if (i->isV6())
					haveV6LinkLocal = true;
			} else if (!allIps.count(*i)) {
				for(std::set<InetAddress>::const_iterator i2(allIps.begin());i2!=allIps.end();++i2) {
					if (i->sameNetworkAs(*i2)) {
						removeIP(*i);
						break;
					}
				}
			}
		}
		if (!haveV6LinkLocal)
			addIP(InetAddress::makeIpv6LinkLocal(_mac));
#else
		for(std::set<InetAddress>::iterator i(myIps.begin());i!=myIps.end();++i) {
			if ((!i->isLinkLocal())&&(!allIps.count(*i))) {
				for(std::set<InetAddress>::const_iterator i2(allIps.begin());i2!=allIps.end();++i2) {
					if (i->sameNetworkAs(*i2)) {
						removeIP(*i);
						break;
					}
				}
			}
		}
#endif
	}
bool BSDEthernetTap::addIp(const InetAddress &ip)
{
	if (!ip)
		return false;

	std::vector<InetAddress> allIps(ips());
	if (std::find(allIps.begin(),allIps.end(),ip) != allIps.end())
		return true; // IP/netmask already assigned

	// Remove and reconfigure if address is the same but netmask is different
	for(std::vector<InetAddress>::iterator i(allIps.begin());i!=allIps.end();++i) {
		if ((i->ipsEqual(ip))&&(i->netmaskBits() != ip.netmaskBits())) {
			if (___removeIp(_dev,*i))
				break;
		}
	}

	long cpid = (long)vfork();
	if (cpid == 0) {
		::execl("/sbin/ifconfig","/sbin/ifconfig",_dev.c_str(),ip.isV4() ? "inet" : "inet6",ip.toString().c_str(),"alias",(const char *)0);
		::_exit(-1);
	} else if (cpid > 0) {
		int exitcode = -1;
		::waitpid(cpid,&exitcode,0);
		return (exitcode == 0);
	}
	return false;
}
bool ClusterGeoIpService::locate(const InetAddress &ip,int &x,int &y,int &z)
{
	InetAddress ipNoPort(ip);
	ipNoPort.setPort(0); // we index cache by IP only
	const uint64_t now = OSUtils::now();

	bool r = false;
	{
		Mutex::Lock _l(_cache_m);
		std::map< InetAddress,_CE >::iterator c(_cache.find(ipNoPort));
		if (c != _cache.end()) {
			x = c->second.x;
			y = c->second.y;
			z = c->second.z;
			if ((now - c->second.ts) < ZT_CLUSTERGEOIPSERVICE_INTERNAL_CACHE_TTL)
				return true;
			else r = true; // return true but refresh as well
		}
	}

	{
		Mutex::Lock _l(_sOutputLock);
		if (_sOutputFd >= 0) {
			std::string ips(ipNoPort.toIpString());
			ips.push_back('\n');
			//fprintf(stderr,"ClusterGeoIpService: << %s",ips.c_str());
			::write(_sOutputFd,ips.data(),ips.length());
		}
	}

	return r;
}
void InputDataDialog::on_loadButton_clicked()
{
    QString fname = QFileDialog::getOpenFileName(this,
             tr("Открыть файл с описанием спектра"), "", tr("txt Files (*.txt)"));
    if (fname == "")
        return;
    std::ifstream ifs(fname.toStdString());
    data.clear();
    int N;
    ifs >> N;
    std::string tmp;
    std::getline(ifs, tmp);
    data.resize(N);
    std::string powers, frequencies;
    std::getline(ifs, powers);
    std::getline(ifs, frequencies);
    std::istringstream ips(powers);
    std::istringstream ifrs(frequencies);
    for(int i = 0; i < N; i++)
    {
        int tmp_val;
        ips >> tmp_val;
        data[i].power_8bit_ = tmp_val;
        ifrs >> data[i].frequency_khz_;
        ui->powerEdit->setText(ui->powerEdit->toPlainText() + " " + QString::number(data[i].power_8bit_));
        ui->frequencyEdit->setText(ui->frequencyEdit->toPlainText() + " " + QString::number(data[i].frequency_khz_));
    }
}
示例#6
0
//{{{ handleHello
int handleHello(msg_t mes) {
	type(mes) = HELLOREP;
	tok(mes) = tokenPresent;

	fprintf (stdout, "HELLO received, sending HELLOREP\n");

	strncpy(ip(mes), ips(mes), IPLONG);

	return sendMessageWithAdd(mes);
}
示例#7
0
	/**
	 * Set this tap's IP addresses to exactly this set of IPs
	 *
	 * New IPs are created, ones not in this list are removed.
	 *
	 * @param ips IP addresses with netmask in port field
	 */
	inline void setIps(const std::set<InetAddress> &allIps)
	{
		for(std::set<InetAddress>::iterator i(allIps.begin());i!=allIps.end();++i)
			addIP(*i);
		std::set<InetAddress> myIps(ips());
		for(std::set<InetAddress>::iterator i(myIps.begin());i!=myIps.end();++i) {
			if (!allIps.count(*i))
				removeIP(*i);
		}
	}
示例#8
0
/*
 * Sends a broadcast
 * and then also multicasts to all ips stored in the Settings
 */
bool Messenger::multicast(quint32 command, QByteArray payload)
{
    QByteArray data = makeMessage(command, payload).toAscii();

    socket->writeDatagram(data, QHostAddress::Broadcast, UDP_PORT);

    QString ip;
    foreach(ip, ips())
    {
        socket->writeDatagram(data, QHostAddress(ip), UDP_PORT);
    }
示例#9
0
//{{{ handleHello
int handleHello(msg_t mes) {
//	type(mes) = HELLOREP;	TODO
	type(mes) = RESOURCE;
	tok(mes) = tokenPresent;

	if (_verbose) fprintf (stdout, "HELLO received, sending RESOURCE\n");//TODO

	strncpy(ip(mes), ips(mes), IPLONG);

	return sendMessageWithAdd(mes);
}
示例#10
0
bool BSDEthernetTap::removeIp(const InetAddress &ip)
{
	if (!ip)
		return false;
	std::vector<InetAddress> allIps(ips());
	if (std::find(allIps.begin(),allIps.end(),ip) != allIps.end()) {
		if (___removeIp(_dev,ip))
			return true;
	}
	return false;
}
示例#11
0
//{{{ handleSearchPrev
int handleSearchPrev (msg_t msg){
	if (_verbose) fprintf (stdout, "SEARCH_PREV received.");
	if (position < pos(msg)) {
		if (_verbose) fprintf (stdout, "Sending ACK_SEARCH_PREV.\n");
		type(msg) = ACK_SEARCH_PREV;
		pos(msg) = position;
		strncpy(ip(msg), ips(msg), IPLONG * sizeof(char));
		return (sendMessageWithAdd(msg));
	}
	if (_verbose) fprintf (stdout, "\n");
	return 0;
}
示例#12
0
vector<long> StackUnwind::dynaUnwind() {
	walker->walkStack(stackwalk);

	int n = stackwalk.size();

	vector<long> ips(n, 0);
	int i;
	for (unsigned i=0; i<n; i++) {
		ips[i] = (unsigned long) stackwalk[i].getRA();
	}
	return ips;
}
示例#13
0
//{{{ handleSearchQueue
int handleSearchQueue(msg_t msg){
	if (_verbose) fprintf (stdout, "SEARCH_QUEUE received.");
	if (position >= 0) {
		if (_verbose) fprintf (stdout, "Sending ACK_SEARCH_QUEUE.\n");
		type(msg) = ACK_SEARCH_QUEUE;
		pos(msg) = position;
		strncpy (ip(msg), ips(msg), IPLONG * sizeof(char));
		return sendMessageWithAdd(msg) == -1;
	}
	if (_verbose) fprintf (stdout, "\n");
	return 0;
}
示例#14
0
//{{{ handleCommit
int handleCommit (msg_t msg) {
	unsigned long int ipa = (unsigned long int)inet_addr(ips(msg));
	pthread_t thread_id;

	if (_verbose) fprintf (stdout, "Got a COMMIT, creating a thread to verify validity of predecessor\n");

	if(!getNeighbour(ipa))
		return 0;

	position = pos(msg);
	last = -1;
	int i;
	if (_verbose) fprintf (stdout,"Copy the predecessor adress contained in received COMMIT.\n");
	for (i=0; i<TOLERANCE; predec[i+1] = pred(msg)[i], i++);

	inet_aton(ips(msg),&(predec[0].sin_addr));

	if(pthread_create(&thread_id, NULL, (void*)(checkNeighbour), (void*)predec) != 0)
		if (_verbose) fprintf(stderr, "Thread creation failure.\n");


	return 0;
}
示例#15
0
//{{{ handleHelloRep
int handleHelloRep(msg_t message, struct sockaddr_in* netParamsNeighbour) {
	unsigned long int ipLastJ = (unsigned long int) inet_addr(ips(message));
	int i;

	if (tok(message)) {
		for (i=0; i<this_site.nbNeighbours; i++)
			if ((unsigned long int)this_site.neighbours[i].sin_addr.s_addr == ipLastJ){
				last = i;
				fprintf(stdout, "Get HELLOREP. TOKEN on site %d.\n", last);
				if (i) {
					tokenPresent = 0;
					fprintf (stdout, "Throw up TOKEN\n");
				}
			}
	}
	else 
		fprintf(stdout, "HELLOREP, but no TOKEN.\n");

	return 0;
}
Boolean FQLQueryExpressionRep::evaluate(const CIMInstance & inst) const
{
    if (_stmt == NULL)
    {
        ((FQLQueryExpressionRep*)this)->_parse();
    }

    FQLInstancePropertySource ips(inst);
    try
    {
       if (_stmt->evaluateQuery(&ips))
       {
           return true;
       }
    }
    catch (...)
    {
         return false;
    }
    return false;
}
示例#17
0
void BSDEthernetTap::scanMulticastGroups(std::vector<MulticastGroup> &added,std::vector<MulticastGroup> &removed)
{
	std::vector<MulticastGroup> newGroups;

	struct ifmaddrs *ifmap = (struct ifmaddrs *)0;
	if (!getifmaddrs(&ifmap)) {
		struct ifmaddrs *p = ifmap;
		while (p) {
			if (p->ifma_addr->sa_family == AF_LINK) {
				struct sockaddr_dl *in = (struct sockaddr_dl *)p->ifma_name;
				struct sockaddr_dl *la = (struct sockaddr_dl *)p->ifma_addr;
				if ((la->sdl_alen == 6)&&(in->sdl_nlen <= _dev.length())&&(!memcmp(_dev.data(),in->sdl_data,in->sdl_nlen)))
					newGroups.push_back(MulticastGroup(MAC(la->sdl_data + la->sdl_nlen,6),0));
			}
			p = p->ifma_next;
		}
		freeifmaddrs(ifmap);
	}

	std::vector<InetAddress> allIps(ips());
	for(std::vector<InetAddress>::iterator ip(allIps.begin());ip!=allIps.end();++ip)
		newGroups.push_back(MulticastGroup::deriveMulticastGroupForAddressResolution(*ip));

	std::sort(newGroups.begin(),newGroups.end());
	std::unique(newGroups.begin(),newGroups.end());

	for(std::vector<MulticastGroup>::iterator m(newGroups.begin());m!=newGroups.end();++m) {
		if (!std::binary_search(_multicastGroups.begin(),_multicastGroups.end(),*m))
			added.push_back(*m);
	}
	for(std::vector<MulticastGroup>::iterator m(_multicastGroups.begin());m!=_multicastGroups.end();++m) {
		if (!std::binary_search(newGroups.begin(),newGroups.end(),*m))
			removed.push_back(*m);
	}

	_multicastGroups.swap(newGroups);
}
示例#18
0
int main(int argc, char *argv[])
{
    dem_config *cfg=NULL;
    int createFlag = FLAG_NOT_SET;
    char configFile[255];

    // Check for all those little helper options
    if (   (checkForOption("--help", argc, argv) != FLAG_NOT_SET)
            || (checkForOption("-h", argc, argv) != FLAG_NOT_SET)
            || (checkForOption("-help", argc, argv) != FLAG_NOT_SET) ) {
        print_help();
    }
    handle_license_and_version_args(argc, argv, ASF_NAME_STRING);

    // Check which options were provided
    createFlag = checkForOption("-create", argc, argv);

    // We need to make sure the user specified the proper number of arguments
    int needed_args = 1 + REQUIRED_ARGS;               // command & REQUIRED_ARGS
    if (createFlag != FLAG_NOT_SET)  needed_args += 1; // option

    // Make sure we have the right number of args
    if(argc != needed_args) {
        print_usage();
    }

    if (createFlag != FLAG_NOT_SET)
        createFlag = 1;
    else
        createFlag = 0;

    // Fetch required arguments
    strcpy(configFile, argv[argc-1]);

    // Report the command line
    asfSplashScreen(argc, argv);

    // If requested, create a config file and exit (if the file does not exist),
    // otherwise read it
    if ( createFlag==TRUE && !fileExists(configFile) ) {
        init_config(configFile);
        exit(EXIT_SUCCESS);
    }
    // Extend the configuration file if the file already exist
    else if ( createFlag==TRUE && fileExists(configFile) ) {
        cfg = read_config(configFile, createFlag);
        // Assign names for results to be kept
        sprintf(cfg->igram_coh->igram, "%s_igram", cfg->general->base);
        sprintf(cfg->igram_coh->coh, "%s_coh.img", cfg->general->base);
        sprintf(cfg->coreg->master_power, "%s_a_pwr.img", cfg->general->base);
        sprintf(cfg->coreg->slave_power, "%s_b_pwr.img", cfg->general->base);
        sprintf(cfg->refine->seeds, "%s.seeds", cfg->general->base);
        sprintf(cfg->dinsar->igram, "%s_digram.img", cfg->general->base);
        sprintf(cfg->unwrap->qc, "%s_qc_phase.img", cfg->general->base);
        sprintf(cfg->elevation->dem, "%s_ht.img", cfg->general->base);
        sprintf(cfg->elevation->error, "%s_err_ht.img", cfg->general->base);
        sprintf(cfg->geocode->dem, "%s_dem", cfg->general->base);
        sprintf(cfg->geocode->amp, "%s_amp", cfg->general->base);
        sprintf(cfg->geocode->error, "%s_error", cfg->general->base);
        sprintf(cfg->geocode->coh, "%s_coh", cfg->general->base);
        asfRequire( 0==write_config(configFile, cfg),
                    "Could not update configuration file");
        asfPrintStatus("   Initialized complete configuration file\n\n");
        exit(EXIT_SUCCESS);
    }
    else if (!fileExists(configFile))
        asfPrintError("Configuration file does not exist!\n");
    else {
        cfg = read_config(configFile, createFlag);
    }

    /* Setup log file */
    sprintf(logFile, "%s.log", cfg->general->base);
    if (strncmp(cfg->general->status, "new", 3)==0) fLog = FOPEN(logFile, "w");
    else fLog = FOPEN(logFile, "a");
    if (argc == 3) {
        sprintf(logbuf, "\nCommand line: ips -c %s\n", configFile);
        printLog(logbuf);
    }
    else {
        sprintf(logbuf, "\nCommand line: ips %s\n", configFile);
        printLog(logbuf);
    }
    sprintf(logbuf, "Program: ips\n\n");
    printLog(logbuf);
    FCLOSE(fLog);

    return ips(cfg, configFile, createFlag);
}
示例#19
0
// Write out the config file for the whole application
int configAppSaveXml()
{
	if (bCmdOptUsed) {
		return 1;
	}

	char configName[MAX_PATH];
	createConfigName(configName);

	try {
		char tempStr[64] = "";

		// root
		ticpp::Document doc;
		ticpp::Declaration decl("1.0", "UTF-8", "");
		doc.LinkEndChild(&decl);

		ticpp::Element root("configuration");
		setAttr(root, "version", configVersion);
		ticpp::Comment comment("Don't edit this file manually unless you know what you're doing\n" \
					APP_TITLE " will restore default settings when this file is deleted");
		doc.LinkEndChild(&comment);
		doc.LinkEndChild(&root);

		// title
		sprintf(tempStr, "0x%06X", nBurnVer);
		addTextNode(root, "version", tempStr);

		// emulation
		ticpp::Element emulation("emulation");
		root.LinkEndChild(&emulation);
		setAttr(emulation, "asm-68k", bBurnUseASM68K);
		setAttr(emulation, "all-ram", bDrvSaveAll);

		// video
		ticpp::Element video("video");
		root.LinkEndChild(&video);

		ticpp::Element fullscreen("fullscreen");
		video.LinkEndChild(&fullscreen);
		setAttr(fullscreen, "width", nVidWidth);
		setAttr(fullscreen, "height", nVidHeight);
		setAttr(fullscreen, "depth", nVidDepth);
		setAttr(fullscreen, "refresh", nVidRefresh);

		ticpp::Element adjust("adjust");
		video.LinkEndChild(&adjust);
		setAttr(adjust, "rotate-vertical", nVidRotationAdjust);

		ticpp::Element screen_size("screen-size");
		video.LinkEndChild(&screen_size);
		setAttr(screen_size, "window", nWindowSize);

		ticpp::Element window_position("window-position");
		video.LinkEndChild(&window_position);
		setAttr(window_position, "x", nWindowPosX);
		setAttr(window_position, "y", nWindowPosY);

		ticpp::Element stretch("stretch");
		video.LinkEndChild(&stretch);
		setAttr(stretch, "full-stretch", bVidFullStretch);
		setAttr(stretch, "correct-aspect", bVidCorrectAspect);

		ticpp::Element color("color");
		video.LinkEndChild(&color);
		setAttr(color, "enable", bcolorAdjust);
		setAttr(color, "contrast", color_contrast);
		setAttr(color, "brightness", color_brightness);
		setAttr(color, "gamma", color_gamma);
		setAttr(color, "grayscale", color_grayscale);
		setAttr(color, "invert", color_invert);

		ticpp::Element vsync("vsync");
		video.LinkEndChild(&vsync);
		setAttr(vsync, "enable", bVidVSync);

		ticpp::Element triple_buffer("triple-buffer");
		video.LinkEndChild(&triple_buffer);
		setAttr(triple_buffer, "enable", bVidTripleBuffer);

		// video render
		ticpp::Element render("render");
		video.LinkEndChild(&render);

		ticpp::Element render_driver("render-driver");
		render.LinkEndChild(&render_driver);
		setAttr(render_driver, "driver", nVidSelect);
		setAttr(render_driver, "adapter", nVidAdapter);

		ticpp::Element filter("filter");
		render.LinkEndChild(&filter);
		setAttr(filter, "linear", vidFilterLinear);
		setAttr(filter, "use-pixelfilter", vidUseFilter);
		setAttr(filter, "pixel-filter", nVidFilter);

		ticpp::Element option("option");
		render.LinkEndChild(&option);
		setAttr(option, "force-16bit", bVidForce16bit);
		setAttr(option, "hardware-vertex", vidHardwareVertex);
		setAttr(option, "motion-blur", vidMotionBlur);
		setAttr(option, "projection", nVid3DProjection);
		setAttr(option, "angel", fVidScreenAngle);
		setAttr(option, "curvature", fVidScreenCurvature);
		setAttr(option, "dxmanager", nVidDXTextureManager);

		setAttr(option, "x-offset", nXOffset);
		setAttr(option, "y-offset", nYOffset);
		setAttr(option, "x-scale",  nXScale);
		setAttr(option, "y-scale",  nYScale);

		// video others
		ticpp::Element monitor("monitor");
		video.LinkEndChild(&monitor);
		setAttr(monitor, "auto-aspect", autoVidScrnAspect);
		setAttr(monitor, "aspect-x", nVidScrnAspectX);
		setAttr(monitor, "aspect-y", nVidScrnAspectY);

		ticpp::Element frame("frame");
		video.LinkEndChild(&frame);
		setAttr(frame, "auto-frameskip", autoFrameSkip);
		setAttr(frame, "force-60hz", bForce60Hz);

		// audio
		ticpp::Element audio("audio");
		root.LinkEndChild(&audio);
		addTextNode(audio, "sound", audSelect);

		ticpp::Element device("device");
		audio.LinkEndChild(&device);
		setAttr(device, "ds", dsDevice);
		setAttr(device, "xa2", xa2Device);
		setAttr(device, "oal", oalDevice);

		ticpp::Element audio_set("setting");
		audio.LinkEndChild(&audio_set);
		setAttr(audio_set, "rate", nAudSampleRate);
		setAttr(audio_set, "frame", nAudSegCount);
		setAttr(audio_set, "dsp", nAudDSPModule);
		setAttr(audio_set, "pcm-interp", nInterpolation);
		setAttr(audio_set, "fm-interp", nFMInterpolation);
		setAttr(audio_set, "stereo-upmix", audStereoUpmixing);

		// gui
		ticpp::Element gui("gui");
		root.LinkEndChild(&gui);
		addTextNode(gui, "language", szLanguage);
		//addTextNode(gui, "gamelist", szTransGamelistFile);

		ticpp::Element chat("chat-font");
		gui.LinkEndChild(&chat);
		setAttr(chat, "min-size", nMinChatFontSize);
		setAttr(chat, "max-size", nMaxChatFontSize);

		ticpp::Element menu("menu");
		gui.LinkEndChild(&menu);
		setAttr(menu, "modeless", bModelessMenu);
		setAttr(menu, "style", menuNewStyle);

		ticpp::Element gui_misc("gui-misc");
		gui.LinkEndChild(&gui_misc);
		setAttr(gui_misc, "on-top", bShowOnTop);
		setAttr(gui_misc, "auto-fullscreen", bFullscreenOnStart);
		setAttr(gui_misc, "lastRom", nLastRom);
		setAttr(gui_misc, "lastFilter", nLastFilter);

		setAttr(gui_misc, "hideChildren", HideChildren);
		setAttr(gui_misc, "showThreeFourPlayerOnly", ThreeOrFourPlayerOnly);
		setAttr(gui_misc, "arcadeJoyStickSettings", ArcadeJoystick);

		// gui load game dialog
		ticpp::Element gamelist("gamelist-dlg");
		gui.LinkEndChild(&gamelist);
		setAttr(gamelist, "options", nLoadMenuShowX);
		//setAttr(gamelist, "drivers", nLoadDriverShowX);
		//setAttr(gamelist, "sys-sel", nSystemSel);
		//setAttr(gamelist, "tab-sel", nTabSel);
		//addTextNode(gamelist, "user-filter", szUserFilterStr);

		// gui ips
		ticpp::Element ips("ips");
		gui.LinkEndChild(&ips);
		setAttr(ips, "language", nPatchLang);
		setAttr(ips, "dependancy", bEnforceDep);

		//ticpp::Element skin("skin");
		//gui.LinkEndChild(&skin);
		//setAttr(skin, "use-placeholder", bVidUsePlaceholder);
		//setAttr(skin, "random", nRandomSkin);
		//addTextNode(skin, NULL, szPlaceHolder);

		// preferences
		ticpp::Element preference("preferences");
		root.LinkEndChild(&preference);

		ticpp::Element settings("settings");
		preference.LinkEndChild(&settings);
		setAttr(settings, "always-processkey", bAlwaysProcessKey);
		setAttr(settings, "auto-pause", bAutoPause);
		//setAttr(settings, "avi-audio", nAviIntAudio);
		//setAttr(settings, "use-gdip", bUseGdip);
		ticpp::Element fastforward("fastforward");
		preference.LinkEndChild(&fastforward);
		setAttr(fastforward, "speed", nFastSpeed);
		ticpp::Element thread("thread");
		preference.LinkEndChild(&thread);
		setAttr(thread, "priority", nAppThreadPriority);
		ticpp::Element autofire("autofire");
		preference.LinkEndChild(&autofire);
		setAttr(autofire, "enable", nAutofireEnabled);
		setAttr(autofire, "default-delay", autofireDefaultDelay);
		ticpp::Element macro("macro");
		preference.LinkEndChild(&macro);
		setAttr(macro, "enable", nInputMacroEnabled);

		// pref misc
		ticpp::Element pref_misc("misc");
		preference.LinkEndChild(&pref_misc);
		setAttr(pref_misc, "effect", nShowEffect);

		ticpp::Element controls("controls");
		preference.LinkEndChild(&controls);
		for (int i = 0; i < 4; i++) {
			sprintf(tempStr, "default%d", i);
			addTextNode(controls, tempStr, szPlayerDefaultIni[i]);
		}

		// paths
		ticpp::Element paths("paths");
		root.LinkEndChild(&paths);

		ticpp::Element rom_path("rom");
		paths.LinkEndChild(&rom_path);
		for (int i = 0; i < DIRS_MAX; i++) {
			addTextNode(rom_path, "path", szAppRomPaths[i]);
		}

		ticpp::Element misc_path("misc");
		paths.LinkEndChild(&misc_path);
		for (int i = PATH_PREVIEW; i < PATH_SUM; i++) {
			sprintf(tempStr, "path%d", i);
			addTextNode(misc_path, tempStr, szMiscPaths[i]);
		}

		// hotkeys
		ticpp::Element hotkeys("hotkeys");
		root.LinkEndChild(&hotkeys);

		/*for (int i = 0; !lastCustomKey(customKeys[i]); i++) {
			CustomKey& customkey = customKeys[i];

			ticpp::Element key(customkey.config_code);
			hotkeys.LinkEndChild(&key);
			setAttr(key, "key", customkey.key);
			setAttr(key, "mod", customkey.keymod);
		}*/

		// save file
		doc.SaveFile(configName, TIXML_ENCODING_UTF8);
	}
	catch (ticpp::Exception& ex) {
		return 1;
	}

	return 0;
}
示例#20
0
// {{{ critSectionRequest
// Ask for critical section
int critSectionRequest() {
	msg_t msg;
	type(msg) = REQUEST;
	char *ip_tmp = inet_ntoa(this_site.neighbours[0].sin_addr);
	strncpy (ask(msg), ip_tmp, IPLONG);

	// If already in SC just return -1
	if (state != IDLE) {
		if (_verbose) fprintf (stderr,"Already in critical section.\n");
		return -1;
	}
	state = WAITING;

	// Owns Token ?
	if(tokenPresent) 
		return takeCriticalSection();
	// Sends request to last
	else if(last != -1) {
		// Get ip of last
		char *tmpter = getIPstrFromNb (last);
		if (_verbose) fprintf (stdout, "Last is %d, sending it a request.\n", last);
		strncpy(ip(msg), tmpter, IPLONG);
		free (tmpter);

		strncpy (ask(msg), inet_ntoa(this_site.neighbours[0].sin_addr), IPLONG);

		if(sendMessageWithAdd(msg) == -1){
			if (_verbose) fprintf (stderr, "======> Sending request failure... <======\n");
			return -1;
		}

		// Arms a timer
		time_t timeStart, timeCur;
		int flags = fcntl(this_site.sdRecv, F_GETFL);
		int flags2 = flags | O_NONBLOCK;
		fcntl(this_site.sdRecv, F_SETFL, flags2);

		timeStart = time(&timeStart);
		timeCur = time(&timeCur);

		// Wait for an answer
		if (_verbose) fprintf (stdout, "Waiting for COMMIT.\n");
		while(timeCur - timeStart < (2*TMESG)) {
			timeCur = time(&timeCur);

			if(recvMessage(&msg, NULL) == -1) 
				continue;

			if (type(msg) == COMMIT)
				return handleCommit(msg);
			else {
				// TODO: Work on reaction when receiving request while waiting commit
				if (type(msg) == REQUEST) {
					if (_verbose) fprintf (stdout, "Received a REQUEST instead of a COMMIT.\n");
				}
				else if (type(msg) == TOKEN){
					last = -1;
					return handleToken(msg);
				}
				else
					handleMessage(msg);
			}
		}

		// If receive no answers
		if (_verbose) fprintf (stdout, "I didn't get any COMMIT, looking for the queue...\n");
		fcntl(this_site.sdRecv, F_SETFL, flags);

		memset (&msg, 0, SIZE);
		type(msg) = SEARCH_QUEUE;
		nb_acc(msg) = acces;
		// Broadcast Search_Queue
		if (_verbose) fprintf (stdout, "Broadcasting SEARCH_QUEUE.\n");
		broadcast(msg);

		msg_t max;
		pos(max) = -1;

		fcntl(this_site.sdRecv, F_SETFL, flags2);

		timeStart = time(&timeStart);
		timeCur = time(&timeCur);

		// Wait for ACK_SEARCH_QUEUE
		if (_verbose) fprintf (stdout, "Expecting ACK_SEARCH_QUEUE.\n");
		while(timeCur - timeStart < 2*TMESG) {
			timeCur = time(&timeCur);
			memset (&msg, 0, SIZE);

			if(recvMessage(&msg, NULL) == -1) 
				continue;

			switch(type(msg)) {
				case ACK_SEARCH_QUEUE:
					if (_verbose) fprintf (stdout, "Got an ACK_SEARCH_QUEUE.\n");
					// Save greatest position in the queue
					if (pos(msg) > pos(max)) {
						if (_verbose) fprintf (stdout, "New position in QUEUE : %d.\n", pos(msg));
						memcpy(&max, &msg, SIZE);
					}
					break;
					// Another site discovers the failure
				case SEARCH_QUEUE:
					if (isMe(ips(msg)))
						continue;
					if (_verbose) fprintf (stdout, "Another site discovered the failure.\n");
					// The other site hasn't priority, just continue
					if (nb_acc(msg) > acces) 
						continue;
					// Both of sites have the same numbers of access, defines priority with ip
					if (nb_acc(msg) == acces) {
						char *ip_pers = inet_ntoa(this_site.neighbours[0].sin_addr);
						if (strcmp(ip_pers, ips(msg)) <= 0)
							continue;
					}
					// If the other has the priority, just change last and ask it for CS
					unsigned long int ipa = (unsigned long int) inet_addr(ips(msg));
					last = getNeighbour(ipa);
					if (_verbose) fprintf (stdout, "I don't have priority, changing my last (%d) and asking for CS again.\n", last);
					state = IDLE;
					return critSectionRequest();
					// TODO: Request processing
				case REQUEST:
					break;
				default:
					handleMessage(msg);
					break;
			}
		}

		if (_verbose) fprintf (stdout, "Waiting time passed.\n");

		fcntl(this_site.sdRecv, F_SETFL, flags);

		// No other site in the queue, juste regenerate TOKEN
		if (pos(max) < 0) {
			if (_verbose) fprintf (stdout, "No other sites in the queue, regenerate TOKEN (last = next)\n");
			last = next;
			tokenPresent = 1;
			takeCriticalSection();
		}
		else {
			// Ask for connection to the site with the highest position
			unsigned long int ipa = (unsigned long int) inet_addr(ips(max));
			last = getNeighbour(ipa);
			if (_verbose) fprintf (stdout, "Ask for Connection, new last = %d\n", last);
			strncpy(ip(msg), ips(max),IPLONG *sizeof(char));
			if (next(max)) {
				type(msg) = CONNECTION;
				if (sendMessageWithAdd(msg) == -1)
					return -1;
			}
			state = IDLE;
			critSectionRequest();
		}
	}
	else
		if (_verbose) fprintf (stderr, "======> Last = -1, but don't have TOKEN <======\n");
	return 0;
}
示例#21
0
//{{{ site_failure
void site_failure(int sig) {
	if (_verbose) fprintf (stderr, "/* FAILURE OF A SITE SPOTTED */\n");
	int i=0;
	int sortie = 0;
	msg_t msg;
	time_t timeStart, timeCur;

		pthread_mutex_lock(&mut_check);
		if (check)
			check = 0;
		pthread_mutex_unlock(&mut_check);

	int flags = fcntl(this_site.sdRecv, F_GETFL);
	int flags2 = flags | O_NONBLOCK;
	fcntl(this_site.sdRecv, F_SETFL, flags2);

	// Sends ARE_YOU_ALIVE to other pred
	if (_verbose) fprintf (stdout, "Checking predecessor validity\n");
	for (i=1; i<TOLERANCE+1; i++) {
		if (!strcmp ("0.0.0.0", inet_ntoa(predec[i].sin_addr))) {
			if (_verbose) fprintf (stdout, "Bad ip address\n");
			continue;
		}
		type(msg) = ARE_YOU_ALIVE;
		char *tmp = inet_ntoa(predec[i].sin_addr);
		strncpy (ip(msg), tmp, IPLONG *sizeof(char));
		unsigned long int ipa = (unsigned long int) inet_addr(ip(msg));
		sendMessageWithAdd(msg);

		pthread_mutex_lock(&mut_check);
		if (check)
			check = 0;
		pthread_mutex_unlock(&mut_check);

		timeStart = time(&timeStart);
		timeCur = time(&timeCur);

		while(timeCur - timeStart < (2*TMESG)) {
			timeCur = time(&timeCur);
			memset (&msg, 0, SIZE);

			if(recvMessage(&msg, NULL) == -1) 
				continue;

			// Receive I_AM_ALIVE --> Connection
			if (_verbose) fprintf (stdout, "Received I_AM_ALIVE\n");
			if (type(msg) == I_AM_ALIVE && !isMe(ips(msg))) {
				handleIAmAlive(msg);
				type(msg) = CONNECTION;
				strncpy(ip(msg), ips(msg), IPLONG * sizeof(char));
				sendMessageWithAdd(msg);
				if (_verbose) fprintf (stdout, "Asking for connection\n");
				last = getNeighbour(ipa);
				if (_verbose) fprintf (stdout, "New last after receiving I_AM_ALIVE message : %d\n", last);
				state = IDLE;
				critSectionRequest();
				sortie++;
				break;
			}
			else if (type(msg) == REQUEST) {}
			else
				handleMessage(msg);
		}
	}

	// No pred is alive, broadcast SEARCH_PREV
	fcntl(this_site.sdRecv, F_SETFL, flags);

	if (_verbose) fprintf (stdout, "No alive predecessor found, looking for other sites\n");
	if (!sortie) {
		msg_t min;

		type(msg) = SEARCH_PREV;
		pos(msg) = position;
		if (_verbose) fprintf (stdout, "Broadcasting SEARCH_PREV.\n");
		broadcast(msg);

		fcntl(this_site.sdRecv, F_SETFL, flags2);

		timeStart = time(&timeStart);
		timeCur = time(&timeCur);

		// Wait for ACK_SEARCH_PREV
		while(timeCur - timeStart < (2*TMESG)) {
			timeCur = time(&timeCur);
			memset (&msg, 0, SIZE);

			if(recvMessage(&msg, NULL) == -1) 
				continue;

			pos(min) = -1;
			if (type(msg) == ACK_SEARCH_PREV) {
				if (pos(min) == -1)
					memcpy (&min, &msg, SIZE);
				else if (pos(min) < pos(msg))
					memcpy (&min, &msg, SIZE);
				if (_verbose) fprintf (stdout, "Got an answer.\n");
			}
			else if (type(msg) == REQUEST) {}
			else
				handleMessage(msg);
		}

		fcntl(this_site.sdRecv, F_SETFL, flags);

		// No answers, regenerate the TOKEN
		if (pos(min) == -1) {
			if (_verbose) fprintf (stdout, "No answers, regenerating TOKEN\n");
			tokenPresent = 1;
			last = next;
			takeCriticalSection();
			sortie ++;
		}

		// Got an answer, ask for connection
		if (!sortie) {
			if (_verbose) fprintf (stdout, "Asking for connection\n");
			type(msg) = CONNECTION;
			strncpy(ip(msg), ips(min), IPLONG * sizeof(char));
			last = getNeighbour((unsigned long int)inet_addr(ips(min)));
			sendMessageWithAdd(msg);
			state = IDLE;
			critSectionRequest();
		}
	}
}
示例#22
0
文件: renderer.c 项目: kunaldeo/JESS
void *renderer (void)
{
 
  gint16 data_tmp[2][512];

  nice (10);

 again:;
  printf("Renderer loop (re)started \n");
  
  while (!quit_renderer)
    {   
#ifdef DEBUG  
 	printf("Debut renderer\n");   
#endif 
      if(conteur.freeze == 0)
	{

	  SDL_mutexP(mutex_one); 
	  memcpy (data_tmp, data, sizeof( data ));
	  SDL_mutexV(mutex_one);

#ifdef DEBUG
	  printf("ips()\n");
#endif
	  ips (); 


#ifdef DEBUG
	  printf("manage_dynamic_and_states_open\n");
#endif
	  manage_dynamic_and_states_open();

#ifdef DEBUG
	  printf("render_deformation\n");
#endif
	  render_deformation(conteur.blur_mode);
	
#ifdef DEBUG
	  printf("render_blur\n");
#endif
	  render_blur(0); 
	
#ifdef DEBUG
	  printf("draw_mode\n");
#endif
	  draw_mode(conteur.draw_mode);

#ifdef DEBUG
	  printf("copy_and_fade\n");
#endif
	  copy_and_fade(DEDT_FACTOR*lys.dEdt_moyen);

	  if (conteur.analyser == 1) 
	    {
#ifdef DEBUG
	      printf("analyser\n");
#endif
	      analyser(pixel);
	    }
#ifdef DEBUG
	  printf("manage_states_close\n");
#endif
	  manage_states_close();
	}

#ifdef DEBUG
      printf("SDL_UpdateRect\n");
#endif
     SDL_UpdateRect (screen,0,0,resx,resy);
     
#ifdef DEBUG
     printf("keyboard\n");
#endif
     keyboard ();

    }

  printf("Renderer Ok je quitte\n");
  quit_renderer = 0;
  
  if(resolution_change == 1)
    {
      jess_cleanup();
      jess_init();
      resolution_change = 0;
      goto again;
    }
 
  return NULL;
}
示例#23
0
//{{{ handleAreYouAlive
int handleAreYouAlive(msg_t msg){
	type(msg) = I_AM_ALIVE;
	if (_verbose) fprintf (stdout, "ARE_YOU_ALIVE received, sending I_AM_ALIVE\n");
	strncpy(ip(msg), ips(msg), IPLONG * sizeof(char));
	return (sendMessageWithAdd(msg));
}