Exemplo n.º 1
0
void HUD_InitHud()
{
	switch (gameinfo.gametype)
	{
	case GAME_Heretic:
	case GAME_Hexen:
		healthpic = TexMan.FindTexture("ARTIPTN2");
		HudFont=FFont::FindFont("HUDFONT_RAVEN");
		break;

	case GAME_Strife:
		healthpic = TexMan.FindTexture("I_MDKT");
		HudFont=BigFont;	// Strife doesn't have anything nice so use the standard font
		break;

	default:
		healthpic = TexMan.FindTexture("MEDIA0");
		berserkpic = TexMan.FindTexture("PSTRA0");
		HudFont=FFont::FindFont("HUDFONT_DOOM");
		break;
	}

	IndexFont = V_GetFont("INDEXFONT");

	if (HudFont == NULL) HudFont = BigFont;
	if (IndexFont == NULL) IndexFont = ConFont;	// Emergency fallback

	invgems[0] = TexMan.FindTexture("INVGEML1");
	invgems[1] = TexMan.FindTexture("INVGEML2");
	invgems[2] = TexMan.FindTexture("INVGEMR1");
	invgems[3] = TexMan.FindTexture("INVGEMR2");

	fragpic = TexMan.FindTexture("HU_FRAGS");	// Sadly, I don't have anything usable for this. :(

	KeyTypes.Clear();
	UnassignedKeyTypes.Clear();

	statspace = SmallFont->StringWidth("Ac:");



	// Now read custom icon overrides
	int lump, lastlump = 0;

	while ((lump = Wads.FindLump ("ALTHUDCF", &lastlump)) != -1)
	{
		FScanner sc(lump);
		while (sc.GetString())
		{
			if (sc.Compare("Health"))
			{
				sc.MustGetString();
				FTextureID tex = TexMan.CheckForTexture(sc.String, FTexture::TEX_MiscPatch);
				if (tex.isValid()) healthpic = TexMan[tex];
			}
			else if (sc.Compare("Berserk"))
			{
				sc.MustGetString();
				FTextureID tex = TexMan.CheckForTexture(sc.String, FTexture::TEX_MiscPatch);
				if (tex.isValid()) berserkpic = TexMan[tex];
			}
			else
			{
				const PClass * ti = PClass::FindClass(sc.String);
				if (!ti)
				{
					Printf("Unknown item class '%s' in ALTHUDCF\n", sc.String);
				}
				else if (!ti->IsDescendantOf(RUNTIME_CLASS(AInventory)))
				{
					Printf("Invalid item class '%s' in ALTHUDCF\n", sc.String);
					ti=NULL;
				}
				sc.MustGetString();
				FTextureID tex;

				if (!sc.Compare("0") && !sc.Compare("NULL") && !sc.Compare(""))
				{
					tex = TexMan.CheckForTexture(sc.String, FTexture::TEX_MiscPatch);
				}
				else tex.SetInvalid();

				if (ti) SetHUDIcon(const_cast<PClass*>(ti), tex);
			}
		}
	}
}
Exemplo n.º 2
0
void Model::forward_a_step() {

  int K = 0;
  for( auto itm = passing_map.rbegin(); itm != passing_map.rend(); itm ++) {

    auto ing = itm->second;

    for (auto il = ing->begin(); il != ing->end(); il++) {
        if ( ! (*il)->valid) continue;
	//
	Location *l = com->get_a_location((*il)->label);
    
        if ( K % 500 == 0)
          cout << "  K = " << K << ", " << l->name << endl;
        K ++;

	for ( vector <EDGE>::const_iterator it = l->outgoing.begin(); 
	      it != l->outgoing.end(); it++) {
            
            if ( ! (*il)->valid) break;

	    Location *tmp = com->get_a_location(it->dest);
            
            if( ci) {
              if ( (l->signature & (unsigned)pow(2,N-1)) == 0 && (tmp->signature & (unsigned)pow(2, N-1)) != 0) {
                if ( constrain_release1(l)) {
                  continue;
                }
                if ( count(l->signature, N) != cpus) continue;
                if ( constrain_release2(*il)) {
                  continue;
                }
              }
              else if ( (l->signature & (unsigned)pow(2,N-1)) != 0 && (tmp->signature & (unsigned)pow(2,N-1))==0
                  && !tmp->is_bad)
                continue;
            }

            if (bp) {

              // now, let's consider the busy period while tk is waiting
              if ( (l->signature & (unsigned)pow(2,N-1)) != 0 && count(tmp->signature,N) > count(l->signature,N)
                  && count(l->signature,N)>cpus) {
                int ti = 0;
                for (int h = 1; h < N; h++)
                  if ( (l->signature & (unsigned)pow(2,h-1)) == 0 && (tmp->signature & (unsigned)pow(2, h-1)) != 0) {
                    ti = h;
                    break;
                  }
                //cout << "before judgement " << (*il)->label << "-" << tmp->name << endl;
                if ( forward_release(*il, ti)) {
                  //cout << (*il)->label << "-" << tmp->name << endl;
                  continue;
                }
              }

            }

	    NNC_Polyhedron poly = (*il)->cvx;
            guard_cvx(*it, poly);
	    if( poly.is_empty()) continue;
	    update_cvx(*it, poly);
      
            invar_cvx(tmp, poly);
	    if( poly.is_empty()) continue;
            poly.time_elapse_assign(tmp->time_elapse);
            invar_cvx(tmp, poly);
            
	    if( poly.is_empty()) continue;

	    if( type==FAST_REACH && tmp->is_bad) {

		pair_sc sc(it->dest,poly, known_param_list, tmp->signature);
		//sc.pre = passing[k].state;
		//next.push_back(sc);
		cout << "The target is reached. Fast saving ...\n";
		//fast_save();
		throw 0;
	    }


	    auto sc = make_shared<pair_sc>(it->dest, poly, known_param_list, tmp->signature);
            if ( (l->signature & (unsigned)pow(2,N-1)) == 0 && (tmp->signature & (unsigned)pow(2, N-1)) != 0)
              sc->tk_new = true;

            if (contained_in(passing_map, sc, op, true)) continue;
            if (contained_in(next_map, sc, true, false)) continue;
            if (contained_in(passed_map, sc, op, false)) continue;
            (*il)->add_a_child(sc);
            insert_into(next_map, sc);
            sc->prior = (*il);
        }
    }
  }
}
Exemplo n.º 3
0
SQLRETURN SQL_API SQLCancel(SQLHSTMT StatementHandle)
{
    o::SQLCancel sc(StatementHandle);
    return sc();
}
void SETcom::SerializeCommon(bool w, CONFIGFILE & c)
{
	//  menu
	Param(c,w, "game.start_in_main", startInMain);
	Param(c,w, "game.in_menu", inMenu);				Param(c,w, "game.in_main", isMain);
	
	//  misc
	Param(c,w, "misc.autostart", autostart);		Param(c,w, "misc.ogredialog", ogre_dialog);
	Param(c,w, "misc.escquit", escquit);
	
	Param(c,w, "misc.language", language);			Param(c,w, "misc.mouse_capture", mouse_capture);
	Param(c,w, "misc.screenshot_png", screen_png);

	//  video
	Param(c,w, "video.windowx", windowx);			Param(c,w, "video.windowy", windowy);
	Param(c,w, "video.fullscreen", fullscreen);		Param(c,w, "video.vsync", vsync);

	Param(c,w, "video.fsaa", fsaa);
	Param(c,w, "video.buffer", buffer);				Param(c,w, "video.rendersystem", rendersystem);

	Param(c,w, "video.limit_fps", limit_fps);
	Param(c,w, "video.limit_fps_val", limit_fps_val);	Param(c,w, "video.limit_sleep", limit_sleep);


	//  graphics  ----
	Param(c,w, "graph_detail.preset", preset);
	Param(c,w, "graph_shadow.shader_mode", shader_mode);	Param(c,w, "graph_shadow.lightmap_size", lightmap_size);
	
	Param(c,w, "graph_detail.anisotropy", anisotropy);
	Param(c,w, "graph_detail.tex_filter", tex_filt);		Param(c,w, "graph_detail.tex_size", tex_size);
	Param(c,w, "graph_detail.ter_mtr", ter_mtr);			Param(c,w, "graph_detail.ter_tripl", ter_tripl);
	
	Param(c,w, "graph_detail.view_dist", view_distance);	Param(c,w, "graph_detail.ter_detail", terdetail);
	Param(c,w, "graph_detail.ter_dist", terdist);			Param(c,w, "graph_detail.road_dist", road_dist);
	
	//  water
	Param(c,w, "graph_reflect.water_reflect", water_reflect); Param(c,w, "graph_reflect.water_refract", water_refract);
	Param(c,w, "graph_reflect.water_rttsize", water_rttsize);
	
	//  shadow
	Param(c,w, "graph_shadow.dist", shadow_dist);			Param(c,w, "graph_shadow.size", shadow_size);
	Param(c,w, "graph_shadow.count",shadow_count);			Param(c,w, "graph_shadow.type", shadow_type);

	//  veget
	Param(c,w, "graph_veget.grass", grass);
	Param(c,w, "graph_veget.trees_dist", trees_dist);		Param(c,w, "graph_veget.grass_dist", grass_dist);
	Param(c,w, "graph_veget.use_imposters", use_imposters); Param(c,w, "graph_veget.imposters_only", imposters_only);


	//  hud
	Param(c,w, "hud_show.fps", show_fps);

	//  gui tracks  ---
	Param(c,w, "gui_tracks.view", tracks_view);		Param(c,w, "gui_tracks.filter", tracks_filter);
	Param(c,w, "gui_tracks.sort", tracks_sort);		Param(c,w, "gui_tracks.sortup", tracks_sortup);

	//  columns, filters
	std::string s;
	int i,v,ii,a;
	
	if (w)	//  write
		for (v=0; v < 2; ++v)
		{
			s = "";  ii = COL_VIS;
			for (i=0; i < ii; ++i)
			{
				s += iToStr(col_vis[v][i]);
				if (i < ii-1)  s += " ";
			}
			Param(c,w, "gui_tracks.columns"+iToStr(v), s);

			s = "";  ii = COL_FIL;
			for (i=0; i < ii; ++i)
			{
				s += iToStr(col_fil[v][i]);
				if (i < ii-1)  s += " ";
			}
			Param(c,w, "gui_tracks.filters"+iToStr(v), s);
		}
	else	//  read
		for (v=0; v < 2; ++v)
		{
			if (Param(c,w, "gui_tracks.columns"+iToStr(v), s))
			{	std::stringstream sc(s);
				for (i=0; i < COL_VIS; ++i)
				{	sc >> a;  col_vis[v][i] = a > 0;  }
			}

			if (Param(c,w, "gui_tracks.filters"+iToStr(v), s))
			{	std::stringstream sf(s);
				for (i=0; i < COL_FIL; ++i)
				{	sf >> a;  col_fil[v][i] = a;  }
		}	}
Exemplo n.º 5
0
CEC_PartFile_Tag::CEC_PartFile_Tag(const CPartFile *file, EC_DETAIL_LEVEL detail_level, CValueMap *valuemap)
:
CEC_SharedFile_Tag(file, detail_level, valuemap, EC_TAG_PARTFILE)
{
	AddTag(EC_TAG_PARTFILE_STATUS, file->GetStatus(), valuemap);
	AddTag(EC_TAG_PARTFILE_STOPPED, file->IsStopped(), valuemap);

	AddTag(EC_TAG_PARTFILE_SOURCE_COUNT, file->GetSourceCount(), valuemap);
	AddTag(EC_TAG_PARTFILE_SOURCE_COUNT_NOT_CURRENT, file->GetNotCurrentSourcesCount(), valuemap);
	AddTag(EC_TAG_PARTFILE_SOURCE_COUNT_XFER, file->GetTransferingSrcCount(), valuemap);
	AddTag(EC_TAG_PARTFILE_SOURCE_COUNT_A4AF, file->GetSrcA4AFCount(), valuemap);
		
	if ( (file->GetTransferingSrcCount() > 0) || (detail_level != EC_DETAIL_UPDATE) || valuemap) {
		
		AddTag(EC_TAG_PARTFILE_SIZE_XFER, file->GetTransferred(), valuemap);
		AddTag(EC_TAG_PARTFILE_SIZE_DONE, file->GetCompletedSize(), valuemap);
		AddTag(EC_TAG_PARTFILE_SPEED, (uint64_t)(file->GetKBpsDown()*1024), valuemap);
	}
	
	AddTag(EC_TAG_PARTFILE_PRIO, (file->IsAutoDownPriority() ? 
		file->GetDownPriority() + 10 : file->GetDownPriority()), valuemap);

	AddTag(EC_TAG_PARTFILE_CAT, file->GetCategory(), valuemap);
	AddTag(EC_TAG_PARTFILE_LAST_SEEN_COMP, file->lastseencomplete, valuemap);
	AddTag(EC_TAG_PARTFILE_LAST_RECV, file->GetLastChangeDatetime(), valuemap);
	AddTag(EC_TAG_PARTFILE_DOWNLOAD_ACTIVE, file->GetDlActiveTime(), valuemap);
	AddTag(EC_TAG_PARTFILE_AVAILABLE_PARTS, file->GetAvailablePartCount(), valuemap);

	AddTag(EC_TAG_PARTFILE_LOST_CORRUPTION, file->GetLostDueToCorruption(), valuemap);
	AddTag(EC_TAG_PARTFILE_GAINED_COMPRESSION, file->GetGainDueToCompression(), valuemap);
	AddTag(EC_TAG_PARTFILE_SAVED_ICH, file->TotalPacketsSavedDueToICH(), valuemap);
	AddTag(EC_TAG_PARTFILE_A4AFAUTO, file->IsA4AFAuto(), valuemap);

	// Tag for comments
	CECEmptyTag sc(EC_TAG_PARTFILE_COMMENTS);

	FileRatingList list;
	file->GetRatingAndComments(list);
	for (FileRatingList::const_iterator it = list.begin(); it != list.end(); ++it) {
		// Tag children are evaluated by index, not by name
		sc.AddTag(CECTag(EC_TAG_PARTFILE_COMMENTS, it->UserName));
		sc.AddTag(CECTag(EC_TAG_PARTFILE_COMMENTS, it->FileName));
		sc.AddTag(CECTag(EC_TAG_PARTFILE_COMMENTS, (uint64) it->Rating));
		sc.AddTag(CECTag(EC_TAG_PARTFILE_COMMENTS, it->Comment));
	}
	AddTag(sc, valuemap);

	if (detail_level == EC_DETAIL_UPDATE) {
		return;
	}

	AddTag(EC_TAG_PARTFILE_PARTMETID, file->GetPartMetNumber(), valuemap);

	// A4AF sources
	CECEmptyTag a4afTag(EC_TAG_PARTFILE_A4AF_SOURCES);
	const CKnownFile::SourceSet& a4afSources = file->GetA4AFList();
	for (CKnownFile::SourceSet::const_iterator it = a4afSources.begin(); it != a4afSources.end(); it++) {
		a4afTag.AddTag(CECTag(EC_TAG_ECID, it->ECID()));
	}
	AddTag(a4afTag, valuemap);
}
Exemplo n.º 6
0
void numToChar(long int n , char s[])
{
if(n == 0) sc(s,db[0]); else while(n != 0)(n >= 0 && n <= 19)?(sc(s,db[n]),(n >9) ? (n = n/100) :(n = n /10)):(n >=20 && n <= 99)?(n%10 == 0 )?(sc(s,tens[n/10-2]),n = n /100):(sc(s,tens[n/10-2]),sc(s,db[n%10]),n = n /100 ):((n >= 100 && n <=999)?(n%100 == 0 )?(sc(s,db[n/100]),sc(s,"hundred"),n = n/1000 ):(sc(s,db[n/100]),sc(s,"hundred"),n = n %100 ):((n >= 1000 && n <=99999)?(n % 1000 == 0)?(n2s(n/1000,s),sc(s,"thousand"),n = n/100000):(n2s(n/1000,s),sc(s,"thousand"),n = n%1000):((n >= 100000 && n <= 9999999)?(n%100000 == 0)?(n2s(n/100000,s),sc(s,"lakh"),n = n/10000000):(n2s(n/100000,s),sc(s,"lakh"),n = n%100000):((n >=10000000)?(n % 10000000 == 0)?(n2s(n/10000000,s),sc(s,"crore"),n = n/1000000000):(n2s(n/10000000,s),sc(s,"crore"),n = n%10000000):1))));
}
Exemplo n.º 7
0
void M_ParseMenuDefs()
{
	int lump, lastlump = 0;

	OptionSettings.mTitleColor = V_FindFontColor(gameinfo.mTitleColor);
	OptionSettings.mFontColor = V_FindFontColor(gameinfo.mFontColor);
	OptionSettings.mFontColorValue = V_FindFontColor(gameinfo.mFontColorValue);
	OptionSettings.mFontColorMore = V_FindFontColor(gameinfo.mFontColorMore);
	OptionSettings.mFontColorHeader = V_FindFontColor(gameinfo.mFontColorHeader);
	OptionSettings.mFontColorHighlight = V_FindFontColor(gameinfo.mFontColorHighlight);
	OptionSettings.mFontColorSelection = V_FindFontColor(gameinfo.mFontColorSelection);
	DefaultListMenuSettings.Reset();
	DefaultOptionMenuSettings.Reset();

	atterm(	DeinitMenus);
	DeinitMenus();
	while ((lump = Wads.FindLump ("MENUDEF", &lastlump)) != -1)
	{
		FScanner sc(lump);

		sc.SetCMode(true);
		while (sc.GetString())
		{
			if (sc.Compare("LISTMENU"))
			{
				ParseListMenu(sc);
			}
			else if (sc.Compare("DEFAULTLISTMENU"))
			{
				ParseListMenuBody(sc, &DefaultListMenuSettings);
				if (DefaultListMenuSettings.mItems.Size() > 0)
				{
					I_FatalError("You cannot add menu items to the menu default settings.");
				}
			}
			else if (sc.Compare("OPTIONVALUE"))
			{
				ParseOptionValue(sc);
			}
			else if (sc.Compare("OPTIONSTRING"))
			{
				ParseOptionString(sc);
			}
			else if (sc.Compare("OPTIONMENUSETTINGS"))
			{
				ParseOptionSettings(sc);
			}
			else if (sc.Compare("OPTIONMENU"))
			{
				ParseOptionMenu(sc);
			}
			else if (sc.Compare("DEFAULTOPTIONMENU"))
			{
				ParseOptionMenuBody(sc, &DefaultOptionMenuSettings);
				if (DefaultOptionMenuSettings.mItems.Size() > 0)
				{
					I_FatalError("You cannot add menu items to the menu default settings.");
				}
			}
			else
			{
				sc.ScriptError("Unknown keyword '%s'", sc.String);
			}
		}
	}
}
Exemplo n.º 8
0
void NodeImporter::importSubmarineCableEdges(BaseTopology_Ptr base_topo) {
    // add submarine cables waypoints
    std::unique_ptr<SubmarineCable> sc(new SubmarineCable(_dbFilename));

    unsigned int skipped = 0;

    int lastLinkID = -1;
    GeographicPositionTuple posFirst;
    GeographicPositionTuple posLast;
    std::vector<GeographicNode_Ptr> edgePositions;

    while (sc->hasNext()) {
        SubmarineCableEdge edge = sc->getNext();

        if (edge.coord1 == edge.coord2) {
            ++skipped;
            continue;
        }

        if(edge.linkID != lastLinkID) {
            for(GeographicNode_Ptr n1 : edgePositions) {
                bool n1OK = fabs(fabs(n1->lon()) - 180.0) < 1.0;

                for(GeographicNode_Ptr n2 : edgePositions) {
                    if(n1 == n2 || n2->id() < n1->id())
                        continue;

                    bool n2OK = fabs(fabs(n2->lon()) - 180.0) < 1.0;

                    if(n1OK && n2OK && GeometricHelpers::sphericalDistToKM(GeometricHelpers::sphericalDist(n1, n2)) < 4) {
                        Graph::Node u;
                        Graph::Node v;

                        u = base_topo->getGraph()->nodeFromId(n1->id());
                        v = base_topo->getGraph()->nodeFromId(n2->id());

                        if(lemon::findEdge(*base_topo->getGraph(), u, v) != lemon::INVALID)
                            continue;

                        GeographicEdge_Ptr edge_ptr(new SeaCableEdge);
                        assert(u != v);
                        base_topo->addEdge(u, v, edge_ptr);
                        BOOST_LOG_TRIVIAL(info) << "Add extra edge on link:" << edge.linkID << " (" << n1->id() << "," << n2->id() << ")";
                    }
                }
            }
            edgePositions.clear();
            lastLinkID = edge.linkID;
        }

        GeographicPositionTuple c1 = std::make_pair(edge.coord1.first, edge.coord1.second);
        GeographicPositionTuple c2 = std::make_pair(edge.coord2.first, edge.coord2.second);

        if (_fallbackProjection.find(c1) != _fallbackProjection.end())
            c1 = _fallbackProjection.at(c1);
        if (_fallbackProjection.find(c2) != _fallbackProjection.end())
            c2 = _fallbackProjection.at(c2);
        if (c1 == c2) {
            ++skipped;
            continue;
        }

        GeographicNode_Ptr c1N(new GeographicNode(500, edge.coord1.first, edge.coord1.second));
        GeographicNode_Ptr c2N(new GeographicNode(500, edge.coord2.first, edge.coord2.second));

        GeographicNode_Ptr n1 = findNearest(c1N);
        GeographicNode_Ptr n2 = findNearest(c2N);

        edgePositions.push_back(n1);
        edgePositions.push_back(n2);

        Graph::Node u;
        Graph::Node v;

        u = base_topo->getGraph()->nodeFromId(n1->id());
        v = base_topo->getGraph()->nodeFromId(n2->id());

        GeographicEdge_Ptr edge_ptr(new SeaCableEdge);
        assert(u != v);
        base_topo->addEdge(u, v, edge_ptr);
    }

    BOOST_LOG_TRIVIAL(info) << "SubmarineCables: Skipped " << skipped
                            << " edge entries due to mapping to same Coordinate or invalid database info.";
}
Exemplo n.º 9
0
void TestAuthenticatedSymmetricCipher(TestData &v, const NameValuePairs &overrideParameters)
{
	std::string type = GetRequiredDatum(v, "AlgorithmType");
	std::string name = GetRequiredDatum(v, "Name");
	std::string test = GetRequiredDatum(v, "Test");
	std::string key = GetDecodedDatum(v, "Key");

	std::string plaintext = GetOptionalDecodedDatum(v, "Plaintext");
	std::string ciphertext = GetOptionalDecodedDatum(v, "Ciphertext");
	std::string header = GetOptionalDecodedDatum(v, "Header");
	std::string footer = GetOptionalDecodedDatum(v, "Footer");
	std::string mac = GetOptionalDecodedDatum(v, "MAC");

	TestDataNameValuePairs testDataPairs(v);
	CombinedNameValuePairs pairs(overrideParameters, testDataPairs);

	if (test == "Encrypt" || test == "EncryptXorDigest" || test == "NotVerify")
	{
		member_ptr<AuthenticatedSymmetricCipher> asc1, asc2;
		asc1.reset(ObjectFactoryRegistry<AuthenticatedSymmetricCipher, ENCRYPTION>::Registry().CreateObject(name.c_str()));
		asc2.reset(ObjectFactoryRegistry<AuthenticatedSymmetricCipher, DECRYPTION>::Registry().CreateObject(name.c_str()));
		asc1->SetKey((const byte *)key.data(), key.size(), pairs);
		asc2->SetKey((const byte *)key.data(), key.size(), pairs);

		std::string encrypted, decrypted;
		AuthenticatedEncryptionFilter ef(*asc1, new StringSink(encrypted));
		bool macAtBegin = !mac.empty() && !GlobalRNG().GenerateBit();	// test both ways randomly
		AuthenticatedDecryptionFilter df(*asc2, new StringSink(decrypted), macAtBegin ? AuthenticatedDecryptionFilter::MAC_AT_BEGIN : 0);

		if (asc1->NeedsPrespecifiedDataLengths())
		{
			asc1->SpecifyDataLengths(header.size(), plaintext.size(), footer.size());
			asc2->SpecifyDataLengths(header.size(), plaintext.size(), footer.size());
		}

		StringStore sh(header), sp(plaintext), sc(ciphertext), sf(footer), sm(mac);

		if (macAtBegin)
			RandomizedTransfer(sm, df, true);
		sh.CopyTo(df, LWORD_MAX, AAD_CHANNEL);
		RandomizedTransfer(sc, df, true);
		sf.CopyTo(df, LWORD_MAX, AAD_CHANNEL);
		if (!macAtBegin)
			RandomizedTransfer(sm, df, true);
		df.MessageEnd();

		RandomizedTransfer(sh, ef, true, AAD_CHANNEL);
		RandomizedTransfer(sp, ef, true);
		RandomizedTransfer(sf, ef, true, AAD_CHANNEL);
		ef.MessageEnd();

		if (test == "Encrypt" && encrypted != ciphertext+mac)
		{
			std::cout << "incorrectly encrypted: ";
			StringSource xx(encrypted, false, new HexEncoder(new FileSink(std::cout)));
			xx.Pump(2048); xx.Flush(false);
			std::cout << "\n";
			SignalTestFailure();
		}
		if (test == "Encrypt" && decrypted != plaintext)
		{
			std::cout << "incorrectly decrypted: ";
			StringSource xx(decrypted, false, new HexEncoder(new FileSink(std::cout)));
			xx.Pump(256); xx.Flush(false);
			std::cout << "\n";
			SignalTestFailure();
		}

		if (ciphertext.size()+mac.size()-plaintext.size() != asc1->DigestSize())
		{
			std::cout << "bad MAC size\n";
			SignalTestFailure();
		}
		if (df.GetLastResult() != (test == "Encrypt"))
		{
			std::cout << "MAC incorrectly verified\n";
			SignalTestFailure();
		}
	}
	else
	{
		std::cout << "unexpected test name\n";
		SignalTestError();
	}
}
Exemplo n.º 10
0
constexpr int zc () { return sc () - 1; }
Exemplo n.º 11
0
int main() {
  krpc::Client conn = krpc::connect("Vessel Name");
  SpaceCenter sc(&conn);
  SpaceCenter::Vessel vessel = sc.active_vessel();
  std::cout << vessel.name() << std::endl;
}
ompl::base::StateStoragePtr ompl_interface::ConstraintsLibrary::constructConstraintApproximation(const ModelBasedPlanningContextPtr &pcontext,
                                                                                                 const moveit_msgs::Constraints &constr_sampling,
                                                                                                 const moveit_msgs::Constraints &constr_hard,
                                                                                                 const ConstraintStateStorageOrderFn &order,
                                                                                                 unsigned int samples, unsigned int edges_per_sample,
                                                                                                 ConstraintApproximationConstructionResults &result)
{
  // state storage structure
  ConstraintApproximationStateStorage *cass = new ConstraintApproximationStateStorage(pcontext->getOMPLStateSpace());
  ob::StateStoragePtr sstor(cass);
  
  // construct a sampler for the sampling constraints
  kinematic_constraints::KinematicConstraintSet kset(pcontext->getRobotModel(), robot_state::TransformsConstPtr(new robot_state::Transforms(pcontext->getRobotModel()->getModelFrame())));
  kset.add(constr_hard);

  const robot_state::RobotState &default_state = pcontext->getCompleteInitialRobotState();
  
  int nthreads = 0;
  unsigned int attempts = 0;
  
  double bounds_val = std::numeric_limits<double>::max() / 2.0 - 1.0;
  pcontext->getOMPLStateSpace()->setPlanningVolume(-bounds_val, bounds_val, -bounds_val, bounds_val, -bounds_val, bounds_val);
  pcontext->getOMPLStateSpace()->setup();
  
  // construct the constrained states
#pragma omp parallel
  { 
#pragma omp master
    {
	nthreads = omp_get_num_threads();    
    }
    
    robot_state::RobotState kstate(default_state);
    const constraint_samplers::ConstraintSamplerManagerPtr &csmng = pcontext->getConstraintSamplerManager();
    ConstrainedSampler *csmp = NULL;
    if (csmng)
    {
      constraint_samplers::ConstraintSamplerPtr cs = csmng->selectSampler(pcontext->getPlanningScene(), pcontext->getJointModelGroup()->getName(), constr_sampling);
      if (cs)
        csmp = new ConstrainedSampler(pcontext.get(), cs);
    }
    
    ob::StateSamplerPtr ss(csmp ? ob::StateSamplerPtr(csmp) : pcontext->getOMPLStateSpace()->allocDefaultStateSampler());
    
    ompl::base::ScopedState<> temp(pcontext->getOMPLStateSpace());
    int done = -1;
    bool slow_warn = false;
    ompl::time::point start = ompl::time::now();
    while (sstor->size() < samples)
    {
      ++attempts;
#pragma omp master
      {      
	int done_now = 100 * sstor->size() / samples;
	if (done != done_now)
	{
	  done = done_now;
	  logInform("%d%% complete (kept %0.1lf%% sampled states)", done, 100.0 * (double)sstor->size() / (double)attempts);
	}

	if (!slow_warn && attempts > 10 && attempts > sstor->size() * 100)
	{
	  slow_warn = true;
	  logWarn("Computation of valid state database is very slow...");
	}
      }

      if (attempts > samples && sstor->size() == 0)
      {
	logError("Unable to generate any samples");
	break;
      }
      
      ss->sampleUniform(temp.get());
      pcontext->getOMPLStateSpace()->copyToRobotState(kstate, temp.get());
      if (kset.decide(kstate).satisfied)
      {
#pragma omp critical
	{
	  if (sstor->size() < samples)
	  {
	    temp->as<ModelBasedStateSpace::StateType>()->tag = sstor->size();
	    sstor->addState(temp.get());
	  }
	}
      }
    }
#pragma omp master
    {
      result.state_sampling_time = ompl::time::seconds(ompl::time::now() - start);
      logInform("Generated %u states in %lf seconds", (unsigned int)sstor->size(), result.state_sampling_time); 
      if (csmp)
      {
        result.sampling_success_rate = csmp->getConstrainedSamplingRate();
        logInform("Constrained sampling rate: %lf", result.sampling_success_rate);
      }
    }
  }
  if (order)
  {
    logInform("Sorting states...");
    sstor->sort(order);
  }
  
  if (edges_per_sample > 0)
  {
    logInform("Computing graph connections (max %u edges per sample) ...", edges_per_sample);
    
    ompl::tools::SelfConfig sc(pcontext->getOMPLSimpleSetup().getSpaceInformation());
    double range = 0.0;
    sc.configurePlannerRange(range);
    
    // construct connexions
    const ob::StateSpacePtr &space = pcontext->getOMPLSimpleSetup().getStateSpace();
    std::vector<robot_state::RobotState> kstates(nthreads, default_state);
    const std::vector<const ompl::base::State*> &states = sstor->getStates();
    std::vector<ompl::base::ScopedState<> > temps(nthreads, ompl::base::ScopedState<>(space));
    
    ompl::time::point start = ompl::time::now();
    int good = 0;
    int done = -1;
    
#pragma omp parallel for schedule(dynamic) 
    for (std::size_t j = 0 ; j < sstor->size() ; ++j)
    {
      int threadid = omp_get_thread_num();
      robot_state::RobotState &kstate = kstates[threadid];
      robot_state::JointStateGroup *jsg = kstate.getJointStateGroup(pcontext->getJointModelGroup()->getName());
      ompl::base::State *temp = temps[threadid].get();
      int done_now = 100 * j / sstor->size();
      if (done != done_now)
      {
	done = done_now;
        logInform("%d%% complete", done);
      }
      
      for (std::size_t i = j + 1 ; i < sstor->size() ; ++i)
      {
	double d = space->distance(states[j], states[i]);

        if (d > range * 3.0 || d < range / 100.0)
          continue;
        
        space->interpolate(states[j], states[i], 0.5, temp);
        pcontext->getOMPLStateSpace()->copyToRobotState(kstate, temp);
        if (kset.decide(kstate).satisfied)
        {
	  space->interpolate(states[j], states[i], 0.25, temp);
	  pcontext->getOMPLStateSpace()->copyToRobotState(kstate, temp);
	  if (kset.decide(kstate).satisfied)
	  {
            space->interpolate(states[j], states[i], 0.75, temp);
            pcontext->getOMPLStateSpace()->copyToRobotState(kstate, temp);
            if (kset.decide(kstate).satisfied)
            {
#pragma omp critical
              {
                cass->getMetadata(i).push_back(j);
                cass->getMetadata(j).push_back(i);
                good++;
              }
              if (cass->getMetadata(j).size() >= edges_per_sample)
                break;
            }
	  }
        }
      }
    }
    result.state_connection_time = ompl::time::seconds(ompl::time::now() - start);
    logInform("Computed possible connexions in %lf seconds. Added %d connexions", result.state_connection_time, good);
  }
  
  return sstor;
}
Exemplo n.º 13
0
int main (int argc, char **argv)
{
Q330 q330;
Q330_ADDR addr;

    init(argc, argv, &q330);

    switch (q330.cmd.code) {

      case Q330_CMD_REBOOT:
        boot(&q330);
        break;

      case Q330_CMD_SAVE:
        save(&q330);
        break;

      case Q330_CMD_SAVEBOOT:
        save(&q330);
        sleep(5);
        boot(&q330);
        break;

      case Q330_CMD_RESYNC:
        resync(&q330);
        break;

      case Q330_CMD_GPS_ON:
        gpsON(&q330);
        break;

      case Q330_CMD_GPS_OFF:
        gpsOFF(&q330);
        break;

      case Q330_CMD_GPS_COLD:
        gpsColdStart(&q330);
        break;

      case Q330_CMD_GPS_CNF:
        gpsCnf(&q330);
        break;

      case Q330_CMD_GPS_ID:
        gpsId(&q330);
        break;

      case Q330_CMD_CAL_START:
        calStart(&q330);
        break;

      case Q330_CMD_CAL_STOP:
        calStop(&q330);
        break;

      case Q330_CMD_IFCONFIG:
        ifconfig(&q330);
        break;

      case Q330_CMD_STATUS:
        status(&q330);
        break;

      case Q330_CMD_FIX:
        fix(&q330);
        break;

      case Q330_CMD_GLOB:
        glob(&q330);
        break;

      case Q330_CMD_SC:
        sc(&q330);
        break;

      case Q330_CMD_PULSE:
        pulse(&q330);
        break;

      case Q330_CMD_AMASS:
        amass(&q330);
        break;

      case Q330_CMD_DCP:
        dcp(&q330);
        break;

      case Q330_CMD_SPP:
        spp(&q330);
        break;

      case Q330_CMD_MAN:
        man(&q330);
        break;

      case Q330_CMD_CO:
        checkout(&q330);
        break;

      default:
        fprintf(stderr, "ERROR: command '%s' is unsupported\n", q330.cmd.name);
        break;

    }

    if (q330.qdp != NULL) qdpDeregister(q330.qdp, TRUE);
}
Exemplo n.º 14
0
void NETWORK_Construct( USHORT usPort, bool bAllocateLANSocket )
{
	char			szString[128];
	ULONG			ulArg;
	USHORT			usNewPort;
	bool			bSuccess;

	// Initialize the Huffman buffer.
	HUFFMAN_Construct( );

#ifdef __WIN32__
	// [BB] Linux doesn't know WSADATA, so this may not be moved outside the ifdef.
	WSADATA			WSAData;
	if ( WSAStartup( 0x0101, &WSAData ))
		network_Error( "Winsock initialization failed!\n" );

	Printf( "Winsock initialization succeeded!\n" );
#endif

	ULONG ulInAddr = INADDR_ANY;
	const char* pszIPAddress = Args->CheckValue( "-useip" );
	// [BB] An IP was specfied. Check if it's valid and if it is, try to bind our socket to it.
	if ( pszIPAddress )
	{
		ULONG requestedIP = inet_addr( pszIPAddress );
		if ( requestedIP == INADDR_NONE )
		{
			sprintf( szString, "NETWORK_Construct: %s is not a valid IP address\n", pszIPAddress );
			network_Error( szString );
		}
		else
			ulInAddr = requestedIP;
	}

	g_usLocalPort = usPort;

	// Allocate a socket, and attempt to bind it to the given port.
	g_NetworkSocket = network_AllocateSocket( );
	// [BB] If we can't allocate a socket, sending / receiving net packets won't work.
	if ( g_NetworkSocket == INVALID_SOCKET )
		network_Error( "NETWORK_Construct: Couldn't allocate socket. You will not be able to host or join servers.\n" );
	else if ( network_BindSocketToPort( g_NetworkSocket, ulInAddr, g_usLocalPort, false ) == false )
	{
		bSuccess = true;
		bool bSuccessIP = true;
		usNewPort = g_usLocalPort;
		while ( network_BindSocketToPort( g_NetworkSocket, ulInAddr, ++usNewPort, false ) == false )
		{
			// Didn't find an available port. Oh well...
			if ( usNewPort == g_usLocalPort )
			{
				// [BB] We couldn't use the specified IP, so just try any.
				if ( ulInAddr != INADDR_ANY )
				{
					ulInAddr = INADDR_ANY;
					bSuccessIP = false;
					continue;
				}
				bSuccess = false;
				break;
			}
		}

		if ( bSuccess == false )
		{
			sprintf( szString, "NETWORK_Construct: Couldn't bind socket to port: %d\n", g_usLocalPort );
			network_Error( szString );
		}
		else if ( bSuccessIP == false )
		{
			sprintf( szString, "NETWORK_Construct: Couldn't bind socket to IP %s, using the default IP instead:\n", pszIPAddress );
			network_Error( szString );
		}
		else
		{
			Printf( "NETWORK_Construct: Couldn't bind to %d. Binding to %d instead...\n", g_usLocalPort, usNewPort );
			g_usLocalPort = usNewPort;
		}
	}

	ulArg = true;
	if ( ioctlsocket( g_NetworkSocket, FIONBIO, &ulArg ) == -1 )
		printf( "network_AllocateSocket: ioctl FIONBIO: %s", strerror( errno ));

	// If we're not starting a server, setup a socket to listen for LAN servers.
	if ( bAllocateLANSocket )
	{
		g_LANSocket = network_AllocateSocket( );
		if ( network_BindSocketToPort( g_LANSocket, ulInAddr, DEFAULT_BROADCAST_PORT, true ) == false )
		{
			sprintf( szString, "network_BindSocketToPort: Couldn't bind LAN socket to port: %d. You will not be able to see LAN servers in the browser.", DEFAULT_BROADCAST_PORT );
			network_Error( szString );
			// [BB] The socket won't work in this case, make sure not to use it.
			g_bLANSocketInvalid = true;
		}

		if ( ioctlsocket( g_LANSocket, FIONBIO, &ulArg ) == -1 )
			printf( "network_AllocateSocket: ioctl FIONBIO: %s", strerror( errno ));
	}

	// Init our read buffer.
	// [BB] Vortex Cortex pointed us to the fact that the smallest huffman code is only 3 bits
	// and it turns into 8 bits when it's decompressed. Thus we need to allocate a buffer that
	// can hold the biggest possible size we may get after decompressing (aka Huffman decoding)
	// the incoming UDP packet.
	NETWORK_InitBuffer( &g_NetworkMessage, ((MAX_UDP_PACKET * 8) / 3 + 1), BUFFERTYPE_READ );
	NETWORK_ClearBuffer( &g_NetworkMessage );

	// [BB] Get and save our local IP.
	if ( ( ulInAddr == INADDR_ANY ) || ( pszIPAddress == NULL ) )
		g_LocalAddress = NETWORK_GetLocalAddress( );
	// [BB] We are using a specified IP, so we don't need to figure out what IP we have, but just use the specified one.
	else
	{
		NETWORK_StringToAddress ( pszIPAddress, &g_LocalAddress );
		g_LocalAddress.usPort = htons ( NETWORK_GetLocalPort() );
	}

	// Print out our local IP address.
	Printf( "IP address %s\n", NETWORK_AddressToString( g_LocalAddress ));

	// If hosting, update the server GUI.
	if( NETWORK_GetState() == NETSTATE_SERVER )
		SERVERCONSOLE_UpdateIP( g_LocalAddress );

	// [BB] Initialize the checksum of the non-map lumps that need to be authenticated when connecting a new player.
	std::vector<std::string>	lumpsToAuthenticate;
	std::vector<LumpAuthenticationMode>	lumpsToAuthenticateMode;

	lumpsToAuthenticate.push_back( "COLORMAP" );
	lumpsToAuthenticateMode.push_back( LAST_LUMP );
	lumpsToAuthenticate.push_back( "PLAYPAL" );
	lumpsToAuthenticateMode.push_back( LAST_LUMP );
	lumpsToAuthenticate.push_back( "HTICDEFS" );
	lumpsToAuthenticateMode.push_back( ALL_LUMPS );
	lumpsToAuthenticate.push_back( "HEXNDEFS" );
	lumpsToAuthenticateMode.push_back( ALL_LUMPS );
	lumpsToAuthenticate.push_back( "STRFDEFS" );
	lumpsToAuthenticateMode.push_back( ALL_LUMPS );
	lumpsToAuthenticate.push_back( "DOOMDEFS" );
	lumpsToAuthenticateMode.push_back( ALL_LUMPS );
	lumpsToAuthenticate.push_back( "GLDEFS" );
	lumpsToAuthenticateMode.push_back( ALL_LUMPS );
	lumpsToAuthenticate.push_back( "DECORATE" );
	lumpsToAuthenticateMode.push_back( ALL_LUMPS );
	lumpsToAuthenticate.push_back( "LOADACS" );
	lumpsToAuthenticateMode.push_back( ALL_LUMPS );
	lumpsToAuthenticate.push_back( "DEHACKED" );
	lumpsToAuthenticateMode.push_back( ALL_LUMPS );
	lumpsToAuthenticate.push_back( "GAMEMODE" );
	lumpsToAuthenticateMode.push_back( ALL_LUMPS );

	FString checksum, longChecksum;
	bool noProtectedLumpsAutoloaded = true;

	// [BB] All precompiled ACS libraries need to be authenticated. The only way to find all of them
	// at this point is to parse all LOADACS lumps.
	{
		int lump, lastlump = 0;
		while ((lump = Wads.FindLump ("LOADACS", &lastlump)) != -1)
		{
			FScanner sc(lump);
			while (sc.GetString())
			{
				NETWORK_AddLumpForAuthentication ( Wads.CheckNumForName (sc.String, ns_acslibrary) );
			}
		}
	}

	// [BB] First check the lumps that were marked for authentication while initializing. This
	// includes for example those lumps included by DECORATE lumps. It's much easier to mark those
	// lumps while the engine parses the DECORATE code than trying to find all included lumps from
	// the DECORATE lumps directly.
	for ( unsigned int i = 0; i < g_LumpNumsToAuthenticate.Size(); ++i )
	{
		if ( !network_GenerateLumpMD5HashAndWarnIfNeeded( g_LumpNumsToAuthenticate[i], Wads.GetLumpFullName (g_LumpNumsToAuthenticate[i]), checksum ) )
			noProtectedLumpsAutoloaded = false;
		longChecksum += checksum;
	}

	for ( unsigned int i = 0; i < lumpsToAuthenticate.size(); i++ )
	{
		switch ( lumpsToAuthenticateMode[i] ){
			case LAST_LUMP:
				int lump;
				lump = Wads.CheckNumForName(lumpsToAuthenticate[i].c_str());
				// [BB] Possibly we find the COLORMAP lump only in the colormaps name space.
				if ( ( lump == -1 ) && ( lumpsToAuthenticate[i].compare ( "COLORMAP" ) == 0 ) )
					lump = Wads.CheckNumForName("COLORMAP", ns_colormaps);
				if ( lump == -1 )
				{
					Printf ( PRINT_BOLD, "Warning: Can't find lump %s for authentication!\n", lumpsToAuthenticate[i].c_str() );
					continue;
				}
				if ( !network_GenerateLumpMD5HashAndWarnIfNeeded( lump, lumpsToAuthenticate[i].c_str(), checksum ) )
					noProtectedLumpsAutoloaded = false;

				// [BB] To make Doom and Freedoom network compatible, substitue the Freedoom PLAYPAL/COLORMAP hash
				// by the corresponding Doom hash.
				// 4804c7f34b5285c334a7913dd98fae16 Doom PLAYPAL hash
				// 061a4c0f80aa8029f2c1bc12dc2e261e Doom COLORMAP hash
				// 2e01ae6258f2a0fdad32125537efe1af Freedoom PLAYPAL hash
				// bb535e66cae508e3833a5d2de974267b Freedoom COLORMAP hash
				if ( ( stricmp ( lumpsToAuthenticate[i].c_str(), "PLAYPAL" ) == 0 ) && ( stricmp ( checksum.GetChars(), "2e01ae6258f2a0fdad32125537efe1af" ) == 0 ) )
					checksum = "4804c7f34b5285c334a7913dd98fae16";
				else if ( ( stricmp ( lumpsToAuthenticate[i].c_str(), "COLORMAP" ) == 0 ) && ( stricmp ( checksum.GetChars(), "bb535e66cae508e3833a5d2de974267b" ) == 0 ) )
					checksum = "061a4c0f80aa8029f2c1bc12dc2e261e";

				longChecksum += checksum;
				break;

			case ALL_LUMPS:
				int workingLump, lastLump;

				lastLump = 0;
				while ((workingLump = Wads.FindLump(lumpsToAuthenticate[i].c_str(), &lastLump)) != -1)
				{
					if ( !network_GenerateLumpMD5HashAndWarnIfNeeded( workingLump, lumpsToAuthenticate[i].c_str(), checksum ) )
						noProtectedLumpsAutoloaded = false;
					longChecksum += checksum;
				}
				break;
		}
	}
	CMD5Checksum::GetMD5( reinterpret_cast<const BYTE *>(longChecksum.GetChars()), longChecksum.Len(), g_lumpsAuthenticationChecksum );

	// [BB] Warn the user about problematic auto-loaded files.
	if ( noProtectedLumpsAutoloaded == false )
	{
		Printf ( PRINT_BOLD, "Warning: Above auto-loaded files contain protected lumps.\n" );
		if ( Args->CheckParm( "-host" ) )
			Printf ( PRINT_BOLD, "Clients without these files can't connect to this server.\n" );
		else
			Printf ( PRINT_BOLD, "You can't connect to servers without these files.\n" );
	}

	// [BB] Initialize the actor network class indices.
	for ( unsigned int i = 0; i < PClass::m_Types.Size(); i++ )
	{
		PClass* cls = PClass::m_Types[i];
		if ( (cls->IsDescendantOf(RUNTIME_CLASS(AActor)))
		     // [BB] The server only binaries don't know DynamicLight and derived classes.
		     && !(cls->IsDescendantOf(PClass::FindClass("DynamicLight"))) )
			cls->ActorNetworkIndex = 1 + g_ActorNetworkIndexClassPointerMap.Push ( cls );
		else
			cls->ActorNetworkIndex = 0;
	}

	// [RC/BB] Init the list of PWADs.
	network_InitPWADList( );

	// Call NETWORK_Destruct() when Skulltag closes.
	atterm( NETWORK_Destruct );

	Printf( "UDP Initialized.\n" );
}
Exemplo n.º 15
0
void FStringTable::LoadLanguage (int lumpnum, DWORD code, bool exactMatch, int passnum)
{
	static bool errordone = false;
	const DWORD orMask = exactMatch ? 0 : MAKE_ID(0,0,0xff,0);
	DWORD inCode = 0;
	StringEntry *entry, **pentry;
	DWORD bucket;
	int cmpval;
	bool skip = true;

	code |= orMask;

	FScanner sc(lumpnum);
	sc.SetCMode (true);
	while (sc.GetString ())
	{
		if (sc.Compare ("["))
		{ // Process language identifiers
			bool donot = false;
			bool forceskip = false;
			skip = true;
			sc.MustGetString ();
			do
			{
				size_t len = sc.StringLen;
				if (len != 2 && len != 3)
				{
					if (len == 1 && sc.String[0] == '~')
					{
						donot = true;
						sc.MustGetString ();
						continue;
					}
					if (len == 1 && sc.String[0] == '*')
					{
						inCode = MAKE_ID('*',0,0,0);
					}
					else if (len == 7 && stricmp (sc.String, "default") == 0)
					{
						inCode = MAKE_ID('*','*',0,0);
					}
					else
					{
						sc.ScriptError ("The language code must be 2 or 3 characters long.\n'%s' is %lu characters long.",
							sc.String, len);
					}
				}
				else
				{
					inCode = MAKE_ID(tolower(sc.String[0]), tolower(sc.String[1]), tolower(sc.String[2]), 0);
				}
				if ((inCode | orMask) == code)
				{
					if (donot)
					{
						forceskip = true;
						donot = false;
					}
					else
					{
						skip = false;
					}
				}
				sc.MustGetString ();
			} while (!sc.Compare ("]"));
			if (donot)
			{
				sc.ScriptError ("You must specify a language after ~");
			}
			skip |= forceskip;
		}
		else
		{ // Process string definitions.
			if (inCode == 0)
			{
				// LANGUAGE lump is bad. We need to check if this is an old binary
				// lump and if so just skip it to allow old WADs to run which contain
				// such a lump.
				if (!sc.isText())
				{
					if (!errordone) Printf("Skipping binary 'LANGUAGE' lump.\n"); 
					errordone = true;
					return;
				}
				sc.ScriptError ("Found a string without a language specified.");
			}

			bool savedskip = skip;
			if (sc.Compare("$"))
			{
				sc.MustGetStringName("ifgame");
				sc.MustGetStringName("(");
				sc.MustGetString();
				skip |= !sc.Compare(GameTypeName());
				sc.MustGetStringName(")");
				sc.MustGetString();

			}

			if (skip)
			{ // We're not interested in this language, so skip the string.
				sc.MustGetStringName ("=");
				sc.MustGetString ();
				do
				{
					sc.MustGetString ();
				} 
				while (!sc.Compare (";"));
				skip = savedskip;
				continue;
			}

			FString strName (sc.String);
			sc.MustGetStringName ("=");
			sc.MustGetString ();
			FString strText (sc.String, ProcessEscapes (sc.String));
			sc.MustGetString ();
			while (!sc.Compare (";"))
			{
				ProcessEscapes (sc.String);
				strText += sc.String;
				sc.MustGetString ();
			}

			// Does this string exist? If so, should we overwrite it?
			bucket = MakeKey (strName.GetChars()) & (HASH_SIZE-1);
			pentry = &Buckets[bucket];
			entry = *pentry;
			cmpval = 1;
			while (entry != NULL)
			{
				cmpval = stricmp (entry->Name, strName.GetChars());
				if (cmpval >= 0)
					break;
				pentry = &entry->Next;
				entry = *pentry;
			}
			if (cmpval == 0 && entry->PassNum >= passnum)
			{
				*pentry = entry->Next;
				M_Free (entry);
				entry = NULL;
			}
			if (entry == NULL || cmpval > 0)
			{
				entry = (StringEntry *)M_Malloc (sizeof(*entry) + strText.Len() + strName.Len() + 2);
				entry->Next = *pentry;
				*pentry = entry;
				strcpy (entry->String, strText.GetChars());
				strcpy (entry->Name = entry->String + strText.Len() + 1, strName.GetChars());
				entry->PassNum = passnum;
			}
		}
	}
}
Exemplo n.º 16
0
static UniValue submitblock(const JSONRPCRequest& request)
{
    // We allow 2 arguments for compliance with BIP22. Argument 2 is ignored.
    if (request.fHelp || request.params.size() < 1 || request.params.size() > 2) {
        throw std::runtime_error(
            "submitblock \"hexdata\"  ( \"dummy\" )\n"
            "\nAttempts to submit new block to network.\n"
            "See https://en.bitcoin.it/wiki/BIP_0022 for full specification.\n"

            "\nArguments\n"
            "1. \"hexdata\"        (string, required) the hex-encoded block data to submit\n"
            "2. \"dummy\"          (optional) dummy value, for compatibility with BIP22. This value is ignored.\n"
            "\nResult:\n"
            "\nExamples:\n"
            + HelpExampleCli("submitblock", "\"mydata\"")
            + HelpExampleRpc("submitblock", "\"mydata\"")
        );
    }

    std::shared_ptr<CBlock> blockptr = std::make_shared<CBlock>();
    CBlock& block = *blockptr;
    if (!DecodeHexBlk(block, request.params[0].get_str())) {
        throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block decode failed");
    }

    if (block.vtx.empty() || !block.vtx[0]->IsCoinBase()) {
        throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block does not start with a coinbase");
    }

    uint256 hash = block.GetHash();
    {
        LOCK(cs_main);
        const CBlockIndex* pindex = LookupBlockIndex(hash);
        if (pindex) {
            if (pindex->IsValid(BLOCK_VALID_SCRIPTS)) {
                return "duplicate";
            }
            if (pindex->nStatus & BLOCK_FAILED_MASK) {
                return "duplicate-invalid";
            }
        }
    }

    {
        LOCK(cs_main);
        const CBlockIndex* pindex = LookupBlockIndex(block.hashPrevBlock);
        if (pindex) {
            UpdateUncommittedBlockStructures(block, pindex, Params().GetConsensus());
        }
    }

    bool new_block;
    submitblock_StateCatcher sc(block.GetHash());
    RegisterValidationInterface(&sc);
    bool accepted = ProcessNewBlock(Params(), blockptr, /* fForceProcessing */ true, /* fNewBlock */ &new_block);
    UnregisterValidationInterface(&sc);
    if (!new_block) {
        if (!accepted) {
            // TODO Maybe pass down fNewBlock to AcceptBlockHeader, so it is properly set to true in this case?
            return "invalid";
        }
        return "duplicate";
    }
    if (!sc.found) {
        return "inconclusive";
    }
    return BIP22ValidationResult(sc.state);
}
Exemplo n.º 17
0
int main(int argc, char **real_argv, char **envv)
{
	CAP *cap;
	unsigned char **argv = (unsigned char **)real_argv;
	struct stat sbuf;
	unsigned char *s;
	unsigned char *t;
	long time_rc;
	unsigned char *run;
#ifdef __MSDOS__
	unsigned char *rundir;
#endif
	SCRN *n;
	int opened = 0;
	int omid;
	int backopt;
	int c;

	init_bufs();

	for (c = 1; argv[c] != NULL; ++c) {
		if (0 == zcmp((unsigned char*)argv[c], USTR "-nosys")) {
			read_sys_configs = 0;
		} else if (0 == zcmp((unsigned char*)argv[c], USTR "-nouser")) {
			read_user_configs = 0;
		} else {
			argv[--c] = argv[0];
			argv += c;
			argc -= c;
			break;
		}
	}

	if (read_user_configs) {
		s = (unsigned char *)getenv("HOME");
		if (s) {
			s = vsncpy(NULL, 0, sz(s));
			s = vsncpy(sv(s), sc("/.joe-p37/only.rc"));
			if (!stat((char*)s, &sbuf)) read_sys_configs = 0;
			vsrm(s);
		}
	}

	joe_locale();

	mainenv = (unsigned char **)envv;

#ifdef __MSDOS__
	_fmode = O_BINARY;
	zcpy(stdbuf, argv[0]);
	joesep(stdbuf);
	run = namprt(stdbuf);
	rundir = dirprt(stdbuf);
	for (c = 0; run[c]; ++c)
		if (run[c] == '.') {
			run = vstrunc(run, c);
			break;
		}
#else
	run = namprt(argv[0]);
#endif

	env_lines = 0;
	if ((s = (unsigned char *)getenv("LINES")) != NULL &&
	    sscanf((char *)s, "%d", &env_lines) != 1)
		env_lines = 0;
	env_columns = 0;
	if ((s = (unsigned char *)getenv("COLUMNS")) != NULL &&
	    sscanf((char *)s, "%d", &env_columns) != 1)
		env_columns = 0;
	if ((s = (unsigned char *)getenv("BAUD")) != NULL)
		sscanf((char *)s, "%u", (unsigned *)&Baud);
	if (getenv("DOPADDING"))
		dopadding = 1;
	if (getenv("NOXON"))
		noxon = 1;
	if ((s = (unsigned char *)getenv("JOETERM")) != NULL)
		joeterm = s;

#ifndef __MSDOS__
	if (!(cap = my_getcap(NULL, 9600, NULL, NULL))) {
		fprintf(stderr, (char *)joe_gettext(_("Couldn't load termcap/terminfo entry\n")));
		return 1;
	}
#endif

#ifdef __MSDOS__

	s = vsncpy(NULL, 0, sv(run));
	s = vsncpy(sv(s), sc("rc"));
	c = procrc(cap, s);
	if (c == 0)
		goto donerc;
	if (c == 1) {
		unsigned char buf[8];

		fprintf(stderr, (char *)joe_gettext(_("There were errors in '%s'.  Use it anyway?")), s);
		fflush(stderr);
		if (NULL == fgets(buf, 8, stdin) || yn_checks(yes_key, buf))
			goto donerc;
	}

	vsrm(s);
	s = vsncpy(NULL, 0, sv(rundir));
	s = vsncpy(sv(s), sv(run));
	s = vsncpy(sv(s), sc("rc"));
	c = procrc(cap, s);
	if (c != 0 && c != 1) {
		/* If built-in *fancyjoerc not present, process builtin *joerc,
		 * which is always present.
		 */
		s = vstrunc(s, 0);
		s = vsncpy(sv(s), sc("*joerc"));
		c = procrc(cap, s);
	}
	if (c == 0)
		goto donerc;
	if (c == 1) {
		unsigned char buf[8];

		fprintf(stderr, (char *)joe_gettext(_("There were errors in '%s'.  Use it anyway?")), s);
		fflush(stderr);
		if (NULL == fgets(buf, 8, stdin) || yn_checks(yes_key, buf))
			goto donerc;
	}
#else

	/* Name of system joerc file.  Try to find one with matching language... */
	
	/* Try full language: like joerc.de_DE */
	time_rc = 0;
        if (!read_sys_configs) { t = NULL; goto skip_joerc; }
        t = vsncpy(NULL, 0, sc(JOERC));
	t = vsncpy(sv(t), sv(run));
	t = vsncpy(sv(t), sc("rc."));
	t = vsncpy(sv(t), sz(locale_msgs));
	if (!stat((char *)t,&sbuf))
		time_rc = sbuf.st_mtime;
	else {
		/* Try generic language: like joerc.de */
		if (locale_msgs[0] && locale_msgs[1] && locale_msgs[2]=='_') {
			vsrm(t);
			t = vsncpy(NULL, 0, sc(JOERC));
			t = vsncpy(sv(t), sv(run));
			t = vsncpy(sv(t), sc("rc."));
			t = vsncpy(sv(t), locale_msgs, 2);
			if (!stat((char *)t,&sbuf))
				time_rc = sbuf.st_mtime;
			else
				goto nope;
		} else {
			nope:
			vsrm(t);
			/* Try Joe's bad english */
			t = vsncpy(NULL, 0, sc(JOERC));
			t = vsncpy(sv(t), sv(run));
			t = vsncpy(sv(t), sc("rc"));
			if (!stat((char *)t,&sbuf))
				time_rc = sbuf.st_mtime;
			else {
				/* If built-in *fancyjoerc not present, process builtin *joerc,
				 * which is always present.
				 */
				t = vstrunc(s, 0);
				t = vsncpy(sv(s), sc("*joerc"));
				time_rc = stat((char *)t,&sbuf) ? 0 : sbuf.st_mtime;
			}
		}
	}
	skip_joerc:

	/* User's joerc file */
	s = (unsigned char *)getenv("HOME");
	if (s && !read_sys_configs) {
		if (read_user_configs) {  /* TODO(pts): Don't read /dev/null */
			s = vsncpy(NULL, 0, sz(s));
			s = vsncpy(sv(s), sc("/.joe-p37/rc"));
		} else {
			s = vsncpy(NULL, 0, sc("/dev/null/missing"));
		}
		goto process_user_rc;
	} else if (!read_user_configs) {
		s = vsncpy(NULL, 0, sc("/dev/null/missing"));
		goto process_user_rc;
	} else if (s) {
		unsigned char buf[8];

		s = vsncpy(NULL, 0, sz(s));
		s = vsncpy(sv(s), sc("/."));
		s = vsncpy(sv(s), sv(run));
		s = vsncpy(sv(s), sc("rc"));

		if (!stat((char *)s,&sbuf)) {
			if (sbuf.st_mtime < time_rc) {
				fprintf(stderr,(char *)joe_gettext(_("Warning: %s is newer than your %s.\n")),t,s);
				fprintf(stderr,(char *)joe_gettext(_("You should update or delete %s\n")),s);
				fprintf(stderr,(char *)joe_gettext(_("Hit enter to continue with %s ")),t);
				fflush(stderr);
				(void)!fgets((char *)buf, 8, stdin);
				goto use_sys;
			}
		}

	      process_user_rc:
		c = procrc(cap, s);
		if (c == 0) {
			vsrm(t);
			goto donerc;
		}
		if (c == 1) {
			fprintf(stderr,(char *)joe_gettext(_("There were errors in '%s'.  Use it anyway (y,n)? ")), s);
			fflush(stderr);
			if (NULL == fgets((char *)buf, 8, stdin) || ynchecks(yes_key, buf)) {
				vsrm(t);
				goto donerc;
			}
		}
	}

	use_sys:
	vsrm(s);
	s = t;
	c = s ? procrc(cap, s) : -1;
	if (c == 0)
		goto donerc;
	if (c == 1) {
		unsigned char buf[8];

		fprintf(stderr,(char *)joe_gettext(_("There were errors in '%s'.  Use it anyway (y,n)? ")), s);
		fflush(stderr);
		if (NULL == fgets((char *)buf, 8, stdin) || ynchecks(yes_key, buf))
			goto donerc;
	}

	/* Try built-in *fancyjoerc, e.g. "*joe-p37rc" */
	vsrm(s);
	s = vsncpy(NULL, 0, sc("*"));
	s = vsncpy(sv(s), sv(run));
	s = vsncpy(sv(s), sc("rc"));
	c = procrc(cap, s);
	if (c != 0 && c != 1) {
		/* If built-in *fancyjoerc not present, process builtin "*joerc",
		 * which is always present.
		 */
		s = vstrunc(s, 0);
		s = vsncpy(sv(s), sc("*joerc"));
		c = procrc(cap, s);
	}
	if (c == 0)
		goto donerc;
	if (c == 1) {
		unsigned char buf[8];

		fprintf(stderr,(char *)joe_gettext(_("There were errors in '%s'.  Use it anyway (y,n)? ")), s);
		fflush(stderr);
		if (NULL == fgets((char *)buf, 8, stdin) || ynchecks(yes_key, buf))
			goto donerc;
	}
#endif

	fprintf(stderr,(char *)joe_gettext(_("Couldn't open '%s'\n")), s);
	vsrm(s);
	return 1;

	donerc:
	vsrm(s);

	if (validate_rc()) {
		fprintf(stderr,(char *)joe_gettext(_("rc file has no :main key binding section or no bindings.  Bye.\n")));
		return 1;
	}


	if (!isatty(fileno(stdin)))
		idleout = 0;

	for (c = 1; argv[c]; ++c) {
		if (argv[c][0] == '-') {
			if (argv[c][1])
				switch (glopt(argv[c] + 1, argv[c + 1], NULL, 1)) {
				case 0:
					fprintf(stderr,(char *)joe_gettext(_("Unknown option '%s'\n")), argv[c]);
					break;
				case 1:
					break;
				case 2:
					++c;
					break;
			} else
				idleout = 0;
		}
	}
	if (!dspasis) {  /* Open all files as ASCII by default if `joe --asis' is specified. This is to avoid writing control characters to the UTF-8 terminal. */
		fdefault.charmap = pdefault.charmap = find_charmap(USTR "ascii");
		fdefault.map_name = pdefault.map_name = USTR "ascii";
	}


	/* initialize mouse support */
	if (xmouse && (s=(unsigned char *)getenv("TERM")) && strstr((char *)s,"xterm"))
		usexmouse=1;

	if (!(n = nopen(cap)))
		return 1;
	maint = screate(n);
	vmem = vtmp();

	startup_log = bfind_scratch_incref(USTR "* Startup Log *");
	startup_log->internal = 1;

	load_state();

	/* It would be better if this ran uedit() to load files */

	/* The business with backopt is to load the file first, then apply file
	 * local options afterwords */

	/* orphan is not compatible with exemac()- macros need a window to exist */
	for (c = 1, backopt = 0; argv[c]; ++c)
		if (argv[c][0] == '+' && argv[c][1]>='0' && argv[c][1]<='9') {
			if (!backopt)
				backopt = c;
		} else if (argv[c][0] == '-' && argv[c][1]) {
			if (!backopt)
				backopt = c;
			if (glopt(argv[c] + 1, argv[c + 1], NULL, 0) == 2)
				++c;
		} else {
			B *b = bfind_incref(argv[c]);
			BW *bw = NULL;
			int er = berror;

			/* This is too annoying */
			/* set_current_dir(argv[c],1); */

			setup_history(&filehist);
			append_history(filehist,sz(argv[c]));

			/* wmktw_takeref() inserts the window before maint->curwin */
			if (!orphan || !opened) {
				bw = wmktw_takeref(maint, b);
				if (er)
					msgnwt(bw->parent, joe_gettext(msgs[-er]));
			} else {
				long line;
				b->orphan = 1;
				b->oldcur = pdup(b->bof, USTR "main");
				pline(b->oldcur, get_file_pos(b->name));
				line = b->oldcur->line - (maint->h - 1) / 2;
				if (line < 0)
					line = 0;
				b->oldtop = pdup(b->oldcur, USTR "main");
				pline(b->oldtop, line);
				p_goto_bol(b->oldtop);
			}
			if (bw) {
				long lnum = 0;

				bw->o.readonly = bw->b->rdonly;
				if (backopt) {
					while (backopt != c) {
						if (argv[backopt][0] == '+') {
							sscanf((char *)(argv[backopt] + 1), "%ld", &lnum);
							++backopt;
						} else {
							if (glopt(argv[backopt] + 1, argv[backopt + 1], &bw->o, 0) == 2)
								backopt += 2;
							else
								backopt += 1;
							lazy_opts(bw->b, &bw->o);
						}
					}
				}
				bw->b->o = bw->o;
				bw->b->rdonly = bw->o.readonly;
				/* Put cursor in window, so macros work properly */
				maint->curwin = bw->parent;
				/* Execute macro */
				if (er == -1 && bw->o.mnew)
					exmacro(bw->o.mnew,1);
				if (er == 0 && bw->o.mold)
					exmacro(bw->o.mold,1);
				/* Hmm... window might not exist any more... depends on what macro does... */
				if (lnum > 0)
					pline(bw->cursor, lnum - 1);
				else
					pline(bw->cursor, get_file_pos(bw->b->name));
				p_goto_bol(bw->cursor);
				/* Go back to first window so windows are in same order as command line  */
				if (opened)
					wnext(maint);
				
			}
			opened = 1;
			backopt = 0;
		}

	

	if (opened) {
		wshowall(maint);
		omid = mid;
		mid = 1;
		dofollows();
		mid = omid;
	} else {
		BW *bw = wmktw_takeref(maint, bfind_incref(USTR ""));

		if (bw->o.mnew)
			exmacro(bw->o.mnew,1);
	}
	maint->curwin = maint->topwin;

	if (startup_log->eof->byte) {
		BW *bw = wmktw_takeref(maint, startup_log);
		startup_log = NULL;
		maint->curwin = bw->parent;
		wshowall(maint);
		uparserr(bw);
	}

	if (help) {
		help_on(maint);
	}
	if (!nonotice) {
		joe_snprintf_3(msgbuf,JOE_MSGBUFSIZE,joe_gettext(_("\\i** Joe's Own Editor v%s ** (%s) ** Copyright %s 2008 **\\i")),VERSION,locale_map->name,(locale_map->type ? "©" : "(C)"));

		msgnw(((BASE *)lastw(maint)->object)->parent, msgbuf);
	}

	if (!idleout) {
		if (!isatty(fileno(stdin)) && modify_logic(maint->curwin->object, ((BW *)maint->curwin->object)->b)) {
			/* Start shell going in first window */
			unsigned char **a;
			unsigned char *cmd;

			a = vamk(10);
			cmd = vsncpy(NULL, 0, sc("/bin/sh"));
			a = vaadd(a, cmd);
			cmd = vsncpy(NULL, 0, sc("-c"));
			a = vaadd(a, cmd);
			cmd = vsncpy(NULL, 0, sc("/bin/cat"));
			a = vaadd(a, cmd);
			
			cstart (maint->curwin->object, USTR "/bin/sh", a, NULL, NULL, 0, 1);
		}
	}

	edloop(0);

	save_state();

	/* Delete all buffer so left over locks get eliminated */
	brmall();

	vclose(vmem);
	nclose(n);

	if (exmsg)
		fprintf(stderr, "\n%s\n", exmsg);
	return 0;
}
Exemplo n.º 18
0
//1.6: KWDocument::loadOasis
bool KWOdfLoader::load(KoOdfReadStore &odfStore)
{
    //debugWords << "========================> KWOdfLoader::load START";

    QPointer<KoUpdater> updater;
    QPointer<KoUpdater> loadUpdater;
    if (m_document->progressUpdater()) {
        updater = m_document->progressUpdater()->startSubtask(1, "KWOdfLoader::load");
        loadUpdater = m_document->progressUpdater()->startSubtask(5, "KWOdfLoader::loadOdf");
        updater->setProgress(0);
        loadUpdater->setProgress(0);
    }

    KoXmlElement content = odfStore.contentDoc().documentElement();
    KoXmlElement realBody(KoXml::namedItemNS(content, KoXmlNS::office, "body"));
    if (realBody.isNull()) {
        errorWords << "No office:body found!" << endl;
        m_document->setErrorMessage(i18n("Invalid OASIS OpenDocument file. No office:body tag found."));
        return false;
    }

    KoXmlElement body = KoXml::namedItemNS(realBody, KoXmlNS::office, "text");
    if (body.isNull()) {
        errorWords << "No office:text found!" << endl;
        KoXmlElement childElem;
        QString localName;
        forEachElement(childElem, realBody)
            localName = childElem.localName();
        if (localName.isEmpty())
            m_document->setErrorMessage(i18n("Invalid OASIS OpenDocument file. No tag found inside office:body."));
        else
            m_document->setErrorMessage(i18n("This is not a word processing document, but %1. Please try opening it with the appropriate application.", KoDocument::tagNameToDocumentType(localName)));
        return false;
    }

    // Load attributes from the office:text.  These are text:global and text:use-soft-page-breaks.
    QString textGlobal = body.attributeNS(KoXmlNS::text, "global");
    bool isTextGlobal = (textGlobal == "true");
    if (isTextGlobal) {
        m_document->setIsMasterDocument(true);
    }
    // FIXME: text:use-soft-page-breaks

    if (updater) updater->setProgress(20);

    KoOdfLoadingContext odfContext(odfStore.styles(), odfStore.store(), QLatin1String("calligrawords/styles/"));
    KoShapeLoadingContext sc(odfContext, m_document->resourceManager());
    sc.setDocumentRdf(m_document->documentRdf());

    // Load user defined variable declarations
    if (KoVariableManager *variableManager = m_document->inlineTextObjectManager()->variableManager()) {
        variableManager->loadOdf(body);
    }

    // Load all styles before the corresponding paragraphs try to use them!
    KWOdfSharedLoadingData *sharedData = new KWOdfSharedLoadingData(this);
    sc.addSharedData(KOTEXT_SHARED_LOADING_ID, sharedData);
    KoStyleManager *styleManager = m_document->resourceManager()->resource(KoText::StyleManager).value<KoStyleManager*>();
    Q_ASSERT(styleManager);
    sharedData->loadOdfStyles(sc, styleManager);

    if (updater) updater->setProgress(40);

    loadMasterPageStyles(sc);

    // add page background frame set
    KWFrameSet *pageBackgroundFrameSet = new KWFrameSet(Words::BackgroundFrameSet);
    m_document->addFrameSet(pageBackgroundFrameSet);

#if 0 //1.6:
    KWOasisLoader oasisLoader(this);
    // <text:page-sequence> oasis extension for DTP (2003-10-27 post by Daniel)
    m_processingType = (!KoXml::namedItemNS(body, KoXmlNS::text, "page-sequence").isNull()) ? DTP : WP;
    m_hasTOC = false;
    m_tabStop = MM_TO_POINT(15);
    const KoXmlElement *defaultParagStyle = styles.defaultStyle("paragraph");
    if (defaultParagStyle) {
        KoStyleStack stack;
        stack.push(*defaultParagStyle);
        stack.setTypeProperties("paragraph");
        QString tabStopVal = stack.property(KoXmlNS::style, "tab-stop-distance");
        if (!tabStopVal.isEmpty()) m_tabStop = KoUnit::parseValue(tabStopVal);
    }
    m_initialEditing = 0;
    // TODO MAILMERGE
    // Variable settings
    // By default display real variable value
    if (!isReadWrite())
        m_varColl->variableSetting()->setDisplayFieldCode(false);
#endif

    // Load all styles before the corresponding paragraphs try to use them!
#if 0 //1.6:
    if (m_frameStyleColl->loadOasisStyles(context) == 0) {
        // no styles loaded -> load default styles
        loadDefaultFrameStyleTemplates();
    }
    if (m_tableStyleColl->loadOasisStyles(context, *m_styleColl, *m_frameStyleColl) == 0) {
        // no styles loaded -> load default styles
        loadDefaultTableStyleTemplates();
    }
    static_cast<KWVariableSettings *>(m_varColl->variableSetting())->loadNoteConfiguration(styles.officeStyle());
    loadDefaultTableTemplates();
//#else
    /*
    // We always needs at least one valid default paragraph style
    KoParagraphStyle *defaultParagraphStyle = m_document->styleManager()->defaultParagraphStyle();
    //const KoXmlElement *defaultParagraphStyle = context.stylesReader().defaultStyle("paragraph");
    //if(! defaultParagraphStyle) {
    KoParagraphStyle *parastyle = new KoParagraphStyle();
    parastyle->setName("Standard");
    m_document->styleManager()->add(parastyle);
    context.styleStack().setTypeProperties("paragraph"); // load all style attributes from "style:paragraph-properties"
    parastyle->loadOasis(context.styleStack()); // load the KoParagraphStyle from the stylestack
    KoCharacterStyle *charstyle = parastyle->characterStyle();
    context.styleStack().setTypeProperties("text"); // load all style attributes from "style:text-properties"
    charstyle->loadOasis(context.styleStack()); // load the KoCharacterStyle from the stylestack
    //}
    */
#endif

    // load text:page-sequence
    KoXmlElement pageSequence = KoXml::namedItemNS(body, KoXmlNS::text, "page-sequence");
    if (! pageSequence.isNull()) {
        KWPageManager *pageManager = m_document->pageManager();
        KoXmlElement page;
        forEachElement(page, pageSequence) {
            if (page.namespaceURI() == KoXmlNS::text && page.localName() == "page") {
                QString master = page.attributeNS(KoXmlNS::text, "master-page-name", QString());
                pageManager->appendPage(pageManager->pageStyle(master));
            }
        }
    }
Exemplo n.º 19
0
int main(int argc, char **real_argv, char **envv)
{
	CAP *cap;
	unsigned char **argv = (unsigned char **)real_argv;
	struct stat sbuf;
	unsigned char *s;
	unsigned char *t;
	long time_rc;
	unsigned char *run;
#ifdef __MSDOS__
	unsigned char *rundir;
#endif
	SCRN *n;
	int opened = 0;
	int omid;
	int backopt;
	int c;

	joe_locale();

	mainenv = (unsigned char **)envv;
	
	vmem = vtmp();
	startup_log = bfind_scratch(USTR "* Startup Log *");
	startup_log->internal = 1;

#ifdef __MSDOS__
	_fmode = O_BINARY;
	zlcpy(stdbuf, sizeof(stdbuf), argv[0]);
	joesep(stdbuf);
	run = namprt(stdbuf);
	rundir = dirprt(stdbuf);
	for (c = 0; run[c]; ++c)
		if (run[c] == '.') {
			run = vstrunc(run, c);
			break;
		}
#else
	run = namprt(argv[0]);
#endif

	if ((s = (unsigned char *)getenv("LINES")) != NULL)
		sscanf((char *)s, "%d", &lines);
	if ((s = (unsigned char *)getenv("COLUMNS")) != NULL)
		sscanf((char *)s, "%d", &columns);
	if ((s = (unsigned char *)getenv("BAUD")) != NULL)
		sscanf((char *)s, "%u", (unsigned *)&Baud);
	if (getenv("DOPADDING"))
		dopadding = 1;
	if (getenv("NOXON"))
		noxon = 1;
	if ((s = (unsigned char *)getenv("JOETERM")) != NULL)
		joeterm = s;

#ifndef __MSDOS__
	if (!(cap = my_getcap(NULL, 9600, NULL, NULL))) {
		logerror_0((char *)joe_gettext(_("Couldn't load termcap/terminfo entry\n")));
		goto exit_errors;
	}
#endif

#ifdef __MSDOS__

	s = vsncpy(NULL, 0, sv(run));
	s = vsncpy(sv(s), sc("rc"));
	c = procrc(cap, s);
	if (c == 0)
		goto donerc;
	if (c == 1) {
		logerror_1((char *)joe_gettext(_("There were errors in '%s'.  Falling back on default.\n")), s);
	}

	vsrm(s);
	s = vsncpy(NULL, 0, sv(rundir));
	s = vsncpy(sv(s), sv(run));
	s = vsncpy(sv(s), sc("rc"));
	c = procrc(cap, s);
	if (c == 0)
		goto donerc;
	if (c == 1) {
		logerror_1((char *)joe_gettext(_("There were errors in '%s'.  Falling back on default.\n")), s);
	}
#else

	/* Name of system joerc file.  Try to find one with matching language... */
	
	/* Try full language: like joerc.de_DE */
	t = vsncpy(NULL, 0, sc(JOERC));
	t = vsncpy(sv(t), sv(run));
	t = vsncpy(sv(t), sc("rc."));
	t = vsncpy(sv(t), sz(locale_msgs));
	if (!stat((char *)t,&sbuf))
		time_rc = sbuf.st_mtime;
	else {
		/* Try generic language: like joerc.de */
		if (locale_msgs[0] && locale_msgs[1] && locale_msgs[2]=='_') {
			vsrm(t);
			t = vsncpy(NULL, 0, sc(JOERC));
			t = vsncpy(sv(t), sv(run));
			t = vsncpy(sv(t), sc("rc."));
			t = vsncpy(sv(t), locale_msgs, 2);
			if (!stat((char *)t,&sbuf))
				time_rc = sbuf.st_mtime;
			else
				goto nope;
		} else {
			nope:
			vsrm(t);
			/* Try Joe's bad english */
			t = vsncpy(NULL, 0, sc(JOERC));
			t = vsncpy(sv(t), sv(run));
			t = vsncpy(sv(t), sc("rc"));
			if (!stat((char *)t,&sbuf))
				time_rc = sbuf.st_mtime;
			else
				time_rc = 0;
		}
	}

	/* User's joerc file */
	s = (unsigned char *)getenv("HOME");
	if (s) {
		s = vsncpy(NULL, 0, sz(s));
		s = vsncpy(sv(s), sc("/."));
		s = vsncpy(sv(s), sv(run));
		s = vsncpy(sv(s), sc("rc"));

		if (!stat((char *)s,&sbuf)) {
			if (sbuf.st_mtime < time_rc) {
				logmessage_2((char *)joe_gettext(_("Warning: %s is newer than your %s.\n")),t,s);
			}
		}

		c = procrc(cap, s);
		if (c == 0) {
			vsrm(t);
			goto donerc;
		}
		if (c == 1) {
			logerror_1((char *)joe_gettext(_("There were errors in '%s'.  Falling back on default.\n")), s);
		}
	}

	vsrm(s);
	s = t;
	c = procrc(cap, s);
	if (c == 0)
		goto donerc;
	if (c == 1) {
		logerror_1((char *)joe_gettext(_("There were errors in '%s'.  Falling back on default.\n")), s);
	}

	/* Try built-in joerc */
	s = vsncpy(NULL, 0, sc("*"));
	s = vsncpy(sv(s), sv(run));
	s = vsncpy(sv(s), sc("rc"));
	c = procrc(cap, s);
	if (c != 0 && c != 1) {
		/* If *fancyjoerc not present, use *joerc which is always there */
		s = vstrunc(s, 0);
		s = vsncpy(sv(s),sc("*joerc"));
		c = procrc(cap, s);
	}
	if (c == 0)
		goto donerc;
	if (c == 1) {
		logerror_1((char *)joe_gettext(_("There were errors in '%s'.  Falling back on default.\n")), s);
	}
#endif

	logerror_1((char *)joe_gettext(_("Couldn't open '%s'\n")), s);
	goto exit_errors;
	return 1;

	donerc:

	if (validate_rc()) {
		logerror_0((char *)joe_gettext(_("rc file has no :main key binding section or no bindings.  Bye.\n")));
		goto exit_errors;
	}

	{
		unsigned char buf[10];
		int x;
		zlcpy(buf, sizeof(buf), USTR "\"`\"	`  ");
		type_backtick = mparse(0, buf, &x, 0);
	}

	shell_kbd = mkkbd(kmap_getcontext(USTR "shell"));

	if (!isatty(fileno(stdin)))
		idleout = 0;

	for (c = 1; argv[c]; ++c) {
		if (argv[c][0] == '-') {
			if (argv[c][1])
				switch (glopt(argv[c] + 1, argv[c + 1], NULL, 1)) {
				case 0:
					logerror_1((char *)joe_gettext(_("Unknown option '%s'\n")), argv[c]);
					break;
				case 1:
					break;
				case 2:
					++c;
					break;
			} else
				idleout = 0;
		}
	}

	/* initialize mouse support */
	if (xmouse && (s=(unsigned char *)getenv("TERM")) && strstr((char *)s,"xterm"))
		usexmouse=1;

	if (!(n = nopen(cap)))
		goto exit_errors;
	maint = screate(n);

	load_state();

	/* It would be better if this ran uedit() to load files */

	/* The business with backopt is to load the file first, then apply file
	 * local options afterwords */

	/* orphan is not compatible with exemac()- macros need a window to exist */
	for (c = 1, backopt = 0; argv[c]; ++c)
		if (argv[c][0] == '+' && argv[c][1]>='0' && argv[c][1]<='9') {
			if (!backopt)
				backopt = c;
		} else if (argv[c][0] == '-' && argv[c][1]) {
			if (!backopt)
				backopt = c;
			if (glopt(argv[c] + 1, argv[c + 1], NULL, 0) == 2)
				++c;
		} else {
			B *b = bfind(argv[c]);
			BW *bw = NULL;
			int er = berror;

			/* This is too annoying */
			/* set_current_dir(argv[c],1); */

			setup_history(&filehist);
			append_history(filehist,sz(argv[c]));

			/* wmktw inserts the window before maint->curwin */
			if (!orphan || !opened) {
				bw = wmktw(maint, b);
				if (er)
					msgnwt(bw->parent, joe_gettext(msgs[-er]));
			} else {
				long line;
				b->orphan = 1;
				b->oldcur = pdup(b->bof, USTR "main");
				pline(b->oldcur, get_file_pos(b->name));
				p_goto_bol(b->oldcur);
				line = b->oldcur->line - (maint->h - 1) / 2;
				if (line < 0)
					line = 0;
				b->oldtop = pdup(b->oldcur, USTR "main");
				pline(b->oldtop, line);
				p_goto_bol(b->oldtop);
			}
			if (bw) {
				long lnum = 0;

				bw->o.readonly = bw->b->rdonly;
				if (backopt) {
					while (backopt != c) {
						if (argv[backopt][0] == '+') {
							sscanf((char *)(argv[backopt] + 1), "%ld", &lnum);
							++backopt;
						} else {
							if (glopt(argv[backopt] + 1, argv[backopt + 1], &bw->o, 0) == 2)
								backopt += 2;
							else
								backopt += 1;
							lazy_opts(bw->b, &bw->o);
						}
					}
				}
				bw->b->o = bw->o;
				bw->b->rdonly = bw->o.readonly;
				/* Put cursor in window, so macros work properly */
				maint->curwin = bw->parent;
				/* Execute macro */
				if (er == -1 && bw->o.mnew)
					exmacro(bw->o.mnew,1);
				if (er == 0 && bw->o.mold)
					exmacro(bw->o.mold,1);
				/* Hmm... window might not exist any more... depends on what macro does... */
				if (lnum > 0)
					pline(bw->cursor, lnum - 1);
				else
					pline(bw->cursor, get_file_pos(bw->b->name));
				p_goto_bol(bw->cursor);
				/* Go back to first window so windows are in same order as command line  */
				if (opened)
					wnext(maint);
				
			}
			opened = 1;
			backopt = 0;
		}

	

	if (opened) {
		wshowall(maint);
		omid = mid;
		mid = 1;
		dofollows();
		mid = omid;
	} else {
		BW *bw = wmktw(maint, bfind(USTR ""));

		if (bw->o.mnew)
			exmacro(bw->o.mnew,1);
	}
	maint->curwin = maint->topwin;

	if (logerrors) {
		B *copied = bcpy(startup_log->bof, startup_log->eof);
		BW *bw = wmktw(maint, copied);
		copied->name = zdup(startup_log->name);
		copied->internal = 1;
		maint->curwin = bw->parent;
		wshowall(maint);
	}

	if (help) {
		help_on(maint);
	}
	if (!nonotice) {
		joe_snprintf_3(msgbuf,JOE_MSGBUFSIZE,joe_gettext(_("\\i** Joe's Own Editor v%s ** (%s) ** Copyright %s 2015 **\\i")),VERSION,locale_map->name,(locale_map->type ? "©" : "(C)"));

		msgnw(((BASE *)lastw(maint)->object)->parent, msgbuf);
	}

	if (!idleout) {
		if (!isatty(fileno(stdin)) && modify_logic(maint->curwin->object, ((BW *)maint->curwin->object)->b)) {
			/* Start shell going in first window */
			unsigned char **a;
			unsigned char *cmd;

			a = vamk(10);
			cmd = vsncpy(NULL, 0, sc("/bin/sh"));
			a = vaadd(a, cmd);
			cmd = vsncpy(NULL, 0, sc("-c"));
			a = vaadd(a, cmd);
			cmd = vsncpy(NULL, 0, sc("/bin/cat"));
			a = vaadd(a, cmd);
			
			cstart (maint->curwin->object, USTR "/bin/sh", a, NULL, NULL, 0, 1, NULL, 0);
		}
	}

	edloop(0);

	save_state();

	/* Delete all buffer so left over locks get eliminated */
	brmall();

	vclose(vmem);
	nclose(n);

	if  (noexmsg) {
		if (notite)
			fprintf(stderr, "\n");
	} else {
		if (exmsg)
			fprintf(stderr, "\n%s\n", exmsg);
		else if (notite)
			fprintf(stderr, "\n");
	}

	return 0;

exit_errors:

	/* Write out error log to console if we are exiting with errors. */
	if (startup_log && startup_log->eof->byte)
		bsavefd(startup_log->bof, 2, startup_log->eof->byte);
	
	return 1;
}
Exemplo n.º 20
0
void TBLayout::OnProcess()
{
	SizeConstraints sc(GetRect().w, GetRect().h);
	ValidateLayout(sc);
}
Exemplo n.º 21
0
void RefactoringEngine::DoFindReferences(const wxString& symname, const wxFileName& fn, int line, int pos, const wxFileList_t& files, bool onlyDefiniteMatches)
{
    // Clear previous results
    Clear();
    
    if ( ! m_storage.IsCacheReady() ) {
        m_storage.InitializeCache( files );
        return;
    }
    
    // Container for the results found in the 'files'
    CppTokensMap tokensMap;

    // Load the file and get a state map + the text from the scanner
    CppWordScanner scanner(fn.GetFullPath());

    // get the current file states
    TextStatesPtr states = scanner.states();
    if(!states)
        return;

    // Attempt to understand the expression that the caret is currently located at (using line:pos:file)
    RefactorSource rs;
    if(!DoResolveWord(states, fn, pos + symname.Len(), line, symname, &rs))
        return;

    wxFileList_t modifiedFilesList = m_storage.FilterUpToDateFiles( files );
    clProgressDlg* prgDlg = NULL;
    if ( !modifiedFilesList.empty() ) {
        prgDlg = CreateProgressDialog(_("Updating cache..."), files.size());
        // Search the provided input files for the symbol to rename and prepare
        // a CppTokensMap
        for (size_t i=0; i<modifiedFilesList.size(); i++) {
            wxFileName curfile = modifiedFilesList.at(i);

            wxString msg;
            msg << _("Caching file: ") << curfile.GetFullName();
            // update the progress bar
            if (!prgDlg->Update(i, msg)) {
                prgDlg->Destroy();
                Clear();
                return;
            }

            // Scan only valid C / C++ files
            switch(FileExtManager::GetType(curfile.GetFullName())) {
            case FileExtManager::TypeHeader:
            case FileExtManager::TypeSourceC:
            case FileExtManager::TypeSourceCpp: {
                // load matches for a give symbol
                m_storage.Match(symname, curfile.GetFullPath(), tokensMap);
            }
            break;
            default:
                break;
            }
        }
        prgDlg->Destroy();
    }
    // load all tokens, first we need to parse the workspace files...
    CppToken::List_t tokens = m_storage.GetTokens(symname, files);
    if (tokens.empty())
        return;

    // sort the tokens
    tokens.sort();

    RefactorSource target;
    std::list<CppToken>::iterator iter = tokens.begin();
    int counter(0);

    TextStatesPtr statesPtr(NULL);
    wxString      statesPtrFileName;
    prgDlg = CreateProgressDialog(_("Stage 2/2: Parsing matches..."), (int) tokens.size());

    for (; iter != tokens.end(); ++iter) {

        // TODO :: send an event here to report our progress
        wxFileName f( iter->getFilename() );
        wxString   msg;
        msg << _("Parsing expression ") << counter << wxT("/") << tokens.size() << _(" in file: ") << f.GetFullName();
        if ( !prgDlg->Update(counter, msg) ) {
            // user clicked 'Cancel'
            Clear();
            prgDlg->Destroy();
            return;
        }

        counter++;
        // reset the result
        target.Reset();

        if(!statesPtr || statesPtrFileName != iter->getFilename() ) {
            // Create new statesPtr
            CppWordScanner sc(iter->getFilename());
            statesPtr         = sc.states();
            statesPtrFileName = iter->getFilename();
        }

        if(!statesPtr)
            continue;

        if (DoResolveWord(statesPtr, wxFileName( iter->getFilename() ), iter->getOffset(), iter->getLineNumber(), symname, &target)) {

            // set the line number
            if(statesPtr->states.size() > iter->getOffset())
                iter->setLineNumber( statesPtr->states[iter->getOffset()].lineNo );

            if (target.name == rs.name && target.scope == rs.scope) {
                // full match
                m_candidates.push_back( *iter );

            } else if (target.name == rs.scope && !rs.isClass) {
                // source is function, and target is class
                m_candidates.push_back( *iter );

            } else if (target.name == rs.name && rs.isClass) {
                // source is class, and target is ctor
                m_candidates.push_back( *iter );

            } else if (!onlyDefiniteMatches) {
                // add it to the possible match list
                m_possibleCandidates.push_back( *iter );
            }
        } else if( !onlyDefiniteMatches) {
            // resolved word failed, add it to the possible list
            m_possibleCandidates.push_back( *iter );
        }
    }

    prgDlg->Destroy();
}
Exemplo n.º 22
0
void TBLayout::OnResized(int old_w, int old_h)
{
	InvalidateLayout(INVALIDATE_LAYOUT_TARGET_ONLY);
	SizeConstraints sc(GetRect().w, GetRect().h);
	ValidateLayout(sc);
}
Exemplo n.º 23
0
    virtual void on_draw()
    {
        typedef agg::pixfmt_bgr24 pixfmt;
        typedef agg::renderer_base<pixfmt> renderer_base;
        typedef agg::renderer_scanline_aa_solid<renderer_base> renderer_solid;

        pixfmt pixf(rbuf_window());
        renderer_base rb(pixf);
        renderer_solid rs(rb);

        rb.clear(agg::rgba(1.0, 1.0, 1.0));

        agg::trans_affine src_mtx;
        src_mtx *= agg::trans_affine_translation(-initial_width()/2, -initial_height()/2);
        src_mtx *= agg::trans_affine_rotation(10.0 * agg::pi / 180.0);
        src_mtx *= agg::trans_affine_translation(initial_width()/2, initial_height()/2);
        src_mtx *= trans_affine_resizing();

        agg::trans_affine img_mtx = src_mtx;
        img_mtx.invert();

        typedef agg::span_allocator<agg::rgba8> span_alloc;

        unsigned i;

        unsigned char brightness_alpha_array[agg::span_conv_brightness_alpha_rgb8::array_size];
        for(i = 0; i < agg::span_conv_brightness_alpha_rgb8::array_size; i++)
        {
            brightness_alpha_array[i] = 
                agg::int8u(m_alpha.value(double(i) / 
                         double(agg::span_conv_brightness_alpha_rgb8::array_size)) * 255.0);
        }
        agg::span_conv_brightness_alpha_rgb8 color_alpha(brightness_alpha_array);


        typedef agg::span_interpolator_linear<> interpolator_type; 
        typedef agg::span_image_filter_rgb_bilinear<agg::rgba8,
                                                    agg::order_bgr,
                                                    interpolator_type> span_gen;
        typedef agg::span_converter<span_gen,
                                    agg::span_conv_brightness_alpha_rgb8> span_conv;

        typedef agg::renderer_scanline_aa<renderer_base, span_conv> renderer;

        span_alloc sa;
        interpolator_type interpolator(img_mtx);
        span_gen sg(sa, rbuf_img(0), agg::rgba(1,1,1,0), interpolator);
        span_conv sc(sg, color_alpha);
        renderer ri(rb, sc);

        agg::ellipse ell;
        agg::rasterizer_scanline_aa<> ras;
        agg::scanline_u8 sl;

        
        for(i = 0; i < 50; i++)
        {
            ell.init(m_x[i], m_y[i], m_rx[i], m_ry[i], 50);
            rs.color(m_colors[i]);
            ras.add_path(ell);
            agg::render_scanlines(ras, sl, rs);
        }


        ell.init(initial_width()  / 2.0, 
                 initial_height() / 2.0, 
                 initial_width()  / 1.9, 
                 initial_height() / 1.9, 200);


        agg::conv_transform<agg::ellipse> tr(ell, src_mtx);


        ras.add_path(tr);
        agg::render_scanlines(ras, sl, ri);

        agg::render_ctrl(ras, sl, rs, m_alpha);
    }
Exemplo n.º 24
0
UniValue submitblock(const JSONRPCRequest& request)
{
    if (request.fHelp || request.params.size() < 1 || request.params.size() > 2) {
        throw std::runtime_error(
            "submitblock \"hexdata\" ( \"jsonparametersobject\" )\n"
            "\nAttempts to submit new block to network.\n"
            "The 'jsonparametersobject' parameter is currently ignored.\n"
            "See https://en.bitcoin.it/wiki/BIP_0022 for full specification.\n"

            "\nArguments:\n"
            "1. \"hexdata\"        (string, required) the hex-encoded block data to submit\n"
            "2. \"parameters\"     (string, optional) object of optional parameters\n"
            "    {\n"
            "      \"workid\" : \"id\"    (string, optional) if the server provided a workid, it MUST be included with submissions\n"
            "    }\n"
            "\nResult:\n"
            "\nExamples:\n"
            + HelpExampleCli("submitblock", "\"mydata\"")
            + HelpExampleRpc("submitblock", "\"mydata\"")
        );
    }

    std::shared_ptr<CBlock> blockptr = std::make_shared<CBlock>();
    CBlock& block = *blockptr;
    if (!DecodeHexBlk(block, request.params[0].get_str())) {
        throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block decode failed");
    }

    if (block.vtx.empty() || !block.vtx[0]->IsCoinBase()) {
        throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block does not start with a coinbase");
    }

    uint256 hash = block.GetHash();
    bool fBlockPresent = false;
    {
        LOCK(cs_main);
        BlockMap::iterator mi = mapBlockIndex.find(hash);
        if (mi != mapBlockIndex.end()) {
            CBlockIndex *pindex = mi->second;
            if (pindex->IsValid(BLOCK_VALID_SCRIPTS)) {
                return "duplicate";
            }
            if (pindex->nStatus & BLOCK_FAILED_MASK) {
                return "duplicate-invalid";
            }
            // Otherwise, we might only have the header - process the block before returning
            fBlockPresent = true;
        }
    }

    submitblock_StateCatcher sc(block.GetHash());
    RegisterValidationInterface(&sc);
    bool fAccepted = ProcessNewBlock(Params(), blockptr, true, NULL);
    UnregisterValidationInterface(&sc);
    if (fBlockPresent) {
        if (fAccepted && !sc.found) {
            return "duplicate-inconclusive";
        }
        return "duplicate";
    }
    if (!sc.found) {
        return "inconclusive";
    }
    return BIP22ValidationResult(sc.state);
}
Exemplo n.º 25
0
UniValue submitblock(const JSONRPCRequest& request)
{
    // We allow 2 arguments for compliance with BIP22. Argument 2 is ignored.
    if (request.fHelp || request.params.size() < 1 || request.params.size() > 2) {
        throw std::runtime_error(
            "submitblock \"hexdata\"  ( \"dummy\" )\n"
            "\nAttempts to submit new block to network.\n"
            "See https://en.bitcoin.it/wiki/BIP_0022 for full specification.\n"

            "\nArguments\n"
            "1. \"hexdata\"        (string, required) the hex-encoded block data to submit\n"
            "2. \"dummy\"          (optional) dummy value, for compatibility with BIP22. This value is ignored.\n"
            "\nResult:\n"
            "\nExamples:\n"
            + HelpExampleCli("submitblock", "\"mydata\"")
            + HelpExampleRpc("submitblock", "\"mydata\"")
        );
    }

    std::shared_ptr<CBlock> blockptr = std::make_shared<CBlock>();
    CBlock& block = *blockptr;
    if (!DecodeHexBlk(block, request.params[0].get_str())) {
        throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block decode failed");
    }

    if (block.vtx.empty() || !block.vtx[0]->IsCoinBase()) {
        throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block does not start with a coinbase");
    }

    uint256 hash = block.GetHash();
    bool fBlockPresent = false;
    {
        LOCK(cs_main);
        BlockMap::iterator mi = mapBlockIndex.find(hash);
        if (mi != mapBlockIndex.end()) {
            CBlockIndex *pindex = mi->second;
            if (pindex->IsValid(BLOCK_VALID_SCRIPTS)) {
                return "duplicate";
            }
            if (pindex->nStatus & BLOCK_FAILED_MASK) {
                return "duplicate-invalid";
            }
            // Otherwise, we might only have the header - process the block before returning
            fBlockPresent = true;
        }
    }

    {
        LOCK(cs_main);
        BlockMap::iterator mi = mapBlockIndex.find(block.hashPrevBlock);
        if (mi != mapBlockIndex.end()) {
            UpdateUncommittedBlockStructures(block, mi->second, Params().GetConsensus());
        }
    }

    submitblock_StateCatcher sc(block.GetHash());
    RegisterValidationInterface(&sc);
    bool fAccepted = ProcessNewBlock(Params(), blockptr, true, nullptr);
    UnregisterValidationInterface(&sc);
    if (fBlockPresent) {
        if (fAccepted && !sc.found) {
            return "duplicate-inconclusive";
        }
        return "duplicate";
    }
    if (!sc.found) {
        return "inconclusive";
    }
    return BIP22ValidationResult(sc.state);
}
Exemplo n.º 26
0
SignatureWidget::SignatureWidget( const DigiDocSignature &signature, unsigned int signnum, QWidget *parent )
:	QLabel( parent )
,	num( signnum )
,	s( signature )
{
	setObjectName( QString("signatureWidget%1").arg(signnum) );
	setSizePolicy( QSizePolicy::Ignored, QSizePolicy::Preferred );
	setWordWrap( true );
	setTextInteractionFlags( Qt::LinksAccessibleByKeyboard|Qt::LinksAccessibleByMouse );
	connect( this, SIGNAL(linkActivated(QString)), SLOT(link(QString)) );

	const SslCertificate cert = s.cert();
	QString accessibility, content, tooltip;
	QTextStream sa( &accessibility );
	QTextStream sc( &content );
	QTextStream st( &tooltip );

	if( cert.type() & SslCertificate::TempelType )
		sc << "<img src=\":/images/ico_stamp_blue_16.png\">";
	else
		sc << "<img src=\":/images/ico_person_blue_16.png\">";
	sc << "<b>" << Qt::escape( cert.toString( cert.showCN() ? "CN" : "GN SN" ) ) << "</b>";

	if( !s.location().isEmpty() )
	{
		sa << " " << tr("Location") << " " << s.location();
		sc << "<br />" << Qt::escape( s.location() );
		st << Qt::escape( s.location() ) << "<br />";
	}
	if( !s.role().isEmpty() )
	{
		sa << " " << tr("Role") << " " << s.role();
		sc << "<br />" << Qt::escape( s.role() );
		st << Qt::escape( s.role() ) << "<br />";
	}
	DateTime date( s.dateTime().toLocalTime() );
	if( !date.isNull() )
	{
		sa << " " << tr("Signed on") << " "
			<< date.formatDate( "dd. MMMM yyyy" ) << " "
			<< tr("time") << " "
			<< date.toString( "hh:mm" );
		sc << "<br />" << tr("Signed on") << " "
			<< date.formatDate( "dd. MMMM yyyy" ) << " "
			<< tr("time") << " "
			<< date.toString( "hh:mm" );
		st << tr("Signed on") << " "
			<< date.formatDate( "dd. MMMM yyyy" ) << " "
			<< tr("time") << " "
			<< date.toString( "hh:mm" );
	}
	setToolTip( tooltip );

	sa << " " << tr("Signature is") << " ";
	sc << "<table width=\"100%\" cellpadding=\"0\" cellspacing=\"0\"><tr>";
	sc << "<td>" << tr("Signature is") << " ";
	switch( s.validate() )
	{
	case DigiDocSignature::Valid:
		sa << tr("valid");
		sc << "<font color=\"green\">" << tr("valid");
		break;
	case DigiDocSignature::Warning:
		sa << tr("valid") << " (" << tr("Warnings") << ")";
		sc << "<font color=\"green\">" << tr("valid") << "</font> <font>(" << tr("Warnings") << ")";
		break;
	case DigiDocSignature::Test:
		sa << tr("valid") << " (" << tr("Test signature") << ")";
		sc << "<font color=\"green\">" << tr("valid") << "</font> <font>(" << tr("Test signature") << ")";
		break;
	case DigiDocSignature::Invalid:
		sa << tr("not valid");
		sc << "<font color=\"red\">" << tr("not valid");
		break;
	case DigiDocSignature::Unknown:
		sa << tr("unknown");
		sc << "<font color=\"red\">" << tr("unknown");
		break;
	}
	sc << "</font>";
	sc << "</td><td align=\"right\">";
	sc << "<a href=\"details\" style=\"color: #509B00\" title=\"" << tr("Show details") << "\">" << tr("Show details") << "</a>";
	sc << "</td></tr><tr><td></td>";
	sc << "<td align=\"right\">";
	if( s.parent()->isSupported() )
		sc << "<a href=\"remove\" style=\"color: #509B00\" title=\"" << tr("Remove") << "\">" << tr("Remove") << "</a>";
	sc << "</td></tr></table>";

	setText( content );
	setAccessibleName( tr("Signature") + " " + cert.toString( cert.showCN() ? "CN" : "GN SN" ) );
	setAccessibleDescription( accessibility );
}
Exemplo n.º 27
0
void R_InitSkins (void)
{
	FSoundID playersoundrefs[NUMSKINSOUNDS];
	spritedef_t temp;
	int sndlumps[NUMSKINSOUNDS];
	char key[65];
	DWORD intname, crouchname;
	size_t i;
	int j, k, base;
	int lastlump;
	int aliasid;
	bool remove;
	PClassPlayerPawn *basetype, *transtype;

	key[sizeof(key)-1] = 0;
	i = PlayerClasses.Size () - 1;
	lastlump = 0;

	for (j = 0; j < NUMSKINSOUNDS; ++j)
	{
		playersoundrefs[j] = skinsoundnames[j][1];
	}

	while ((base = Wads.FindLump ("S_SKIN", &lastlump, true)) != -1)
	{
		// The player sprite has 23 frames. This means that the S_SKIN
		// marker needs a minimum of 23 lumps after it.
		if (base >= Wads.GetNumLumps() - 23 || base == -1)
			continue;

		i++;
		for (j = 0; j < NUMSKINSOUNDS; j++)
			sndlumps[j] = -1;
		skins[i].namespc = Wads.GetLumpNamespace (base);

		FScanner sc(base);
		intname = 0;
		crouchname = 0;

		remove = false;
		basetype = NULL;
		transtype = NULL;

		// Data is stored as "key = data".
		while (sc.GetString ())
		{
			strncpy (key, sc.String, sizeof(key)-1);
			if (!sc.GetString() || sc.String[0] != '=')
			{
				Printf (PRINT_BOLD, "Bad format for skin %d: %s\n", (int)i, key);
				break;
			}
			sc.GetString ();
			if (0 == stricmp (key, "name"))
			{
				strncpy (skins[i].name, sc.String, 16);
				for (j = 0; (size_t)j < i; j++)
				{
					if (stricmp (skins[i].name, skins[j].name) == 0)
					{
						mysnprintf (skins[i].name, countof(skins[i].name), "skin%d", (int)i);
						Printf (PRINT_BOLD, "Skin %s duplicated as %s\n",
							skins[j].name, skins[i].name);
						break;
					}
				}
			}
			else if (0 == stricmp (key, "sprite"))
			{
				for (j = 3; j >= 0; j--)
					sc.String[j] = toupper (sc.String[j]);
				intname = *((DWORD *)sc.String);
			}
			else if (0 == stricmp (key, "crouchsprite"))
			{
				for (j = 3; j >= 0; j--)
					sc.String[j] = toupper (sc.String[j]);
				crouchname = *((DWORD *)sc.String);
			}
			else if (0 == stricmp (key, "face"))
			{
				for (j = 2; j >= 0; j--)
					skins[i].face[j] = toupper (sc.String[j]);
				skins[i].face[3] = '\0';
			}
			else if (0 == stricmp (key, "gender"))
			{
				skins[i].gender = D_GenderToInt (sc.String);
			}
			else if (0 == stricmp (key, "scale"))
			{
				skins[i].Scale.X = clamp(atof (sc.String), 1./65536, 256.);
				skins[i].Scale.Y = skins[i].Scale.X;
			}
			else if (0 == stricmp (key, "game"))
			{
				if (gameinfo.gametype == GAME_Heretic)
					basetype = dyn_cast<PClassPlayerPawn>(PClass::FindActor(NAME_HereticPlayer));
				else if (gameinfo.gametype == GAME_Strife)
					basetype = dyn_cast<PClassPlayerPawn>(PClass::FindActor(NAME_StrifePlayer));
				else
					basetype = dyn_cast<PClassPlayerPawn>(PClass::FindActor(NAME_DoomPlayer));

				transtype = basetype;

				if (stricmp (sc.String, "heretic") == 0)
				{
					if (gameinfo.gametype & GAME_DoomChex)
					{
						transtype = dyn_cast<PClassPlayerPawn>(PClass::FindActor(NAME_HereticPlayer));
						skins[i].othergame = true;
					}
					else if (gameinfo.gametype != GAME_Heretic)
					{
						remove = true;
					}
				}
				else if (stricmp (sc.String, "strife") == 0)
				{
					if (gameinfo.gametype != GAME_Strife)
					{
						remove = true;
					}
				}
				else
				{
					if (gameinfo.gametype == GAME_Heretic)
					{
						transtype = dyn_cast<PClassPlayerPawn>(PClass::FindActor(NAME_DoomPlayer));
						skins[i].othergame = true;
					}
					else if (!(gameinfo.gametype & GAME_DoomChex))
					{
						remove = true;
					}
				}

				if (remove)
					break;
			}
			else if (0 == stricmp (key, "class"))
			{ // [GRB] Define the skin for a specific player class
				int pclass = D_PlayerClassToInt (sc.String);

				if (pclass < 0)
				{
					remove = true;
					break;
				}

				basetype = transtype = PlayerClasses[pclass].Type;
			}
			else if (key[0] == '*')
			{ // Player sound replacment (ZDoom extension)
				int lump = Wads.CheckNumForName (sc.String, skins[i].namespc);
				if (lump == -1)
				{
					lump = Wads.CheckNumForFullName (sc.String, true, ns_sounds);
				}
				if (lump != -1)
				{
					if (stricmp (key, "*pain") == 0)
					{ // Replace all pain sounds in one go
						aliasid = S_AddPlayerSound (skins[i].name, skins[i].gender,
							playersoundrefs[0], lump, true);
						for (int l = 3; l > 0; --l)
						{
							S_AddPlayerSoundExisting (skins[i].name, skins[i].gender,
								playersoundrefs[l], aliasid, true);
						}
					}
					else
					{
						int sndref = S_FindSoundNoHash (key);
						if (sndref != 0)
						{
							S_AddPlayerSound (skins[i].name, skins[i].gender, sndref, lump, true);
						}
					}
				}
			}
			else
			{
				for (j = 0; j < NUMSKINSOUNDS; j++)
				{
					if (stricmp (key, skinsoundnames[j][0]) == 0)
					{
						sndlumps[j] = Wads.CheckNumForName (sc.String, skins[i].namespc);
						if (sndlumps[j] == -1)
						{ // Replacement not found, try finding it in the global namespace
							sndlumps[j] = Wads.CheckNumForFullName (sc.String, true, ns_sounds);
						}
					}
				}
				//if (j == 8)
				//	Printf ("Funny info for skin %i: %s = %s\n", i, key, sc.String);
			}
		}

		// [GRB] Assume Doom skin by default
		if (!remove && basetype == NULL)
		{
			if (gameinfo.gametype & GAME_DoomChex)
			{
				basetype = transtype = dyn_cast<PClassPlayerPawn>(PClass::FindActor(NAME_DoomPlayer));
			}
			else if (gameinfo.gametype == GAME_Heretic)
			{
				basetype = dyn_cast<PClassPlayerPawn>(PClass::FindActor(NAME_HereticPlayer));
				transtype = dyn_cast<PClassPlayerPawn>(PClass::FindActor(NAME_DoomPlayer));
				skins[i].othergame = true;
			}
			else
			{
				remove = true;
			}
		}

		if (!remove)
		{
			skins[i].range0start = transtype->ColorRangeStart;
			skins[i].range0end = transtype->ColorRangeEnd;

			remove = true;
			for (j = 0; j < (int)PlayerClasses.Size (); j++)
			{
				PClassPlayerPawn *type = PlayerClasses[j].Type;

				if (type->IsDescendantOf (basetype) &&
					GetDefaultByType(type)->SpawnState->sprite == GetDefaultByType(basetype)->SpawnState->sprite &&
					type->ColorRangeStart == basetype->ColorRangeStart &&
					type->ColorRangeEnd == basetype->ColorRangeEnd)
				{
					PlayerClasses[j].Skins.Push ((int)i);
					remove = false;
				}
			}
		}

		if (!remove)
		{
			if (skins[i].name[0] == 0)
				mysnprintf (skins[i].name, countof(skins[i].name), "skin%d", (int)i);

			// Now collect the sprite frames for this skin. If the sprite name was not
			// specified, use whatever immediately follows the specifier lump.
			if (intname == 0)
			{
				char name[9];
				Wads.GetLumpName (name, base+1);
				memcpy(&intname, name, 4);
			}

			int basens = Wads.GetLumpNamespace(base);

			for(int spr = 0; spr<2; spr++)
			{
				spriteframewithrotate sprtemp[MAX_SPRITE_FRAMES];
				memset (sprtemp, 0xFFFF, sizeof(sprtemp));
				for (k = 0; k < MAX_SPRITE_FRAMES; ++k)
				{
					sprtemp[k].Flip = 0;
					sprtemp[k].Voxel = NULL;
				}
				int maxframe = -1;

				if (spr == 1)
				{
					if (crouchname !=0 && crouchname != intname)
					{
						intname = crouchname;
					}
					else
					{
						skins[i].crouchsprite = -1;
						break;
					}
				}

				for (k = base + 1; Wads.GetLumpNamespace(k) == basens; k++)
				{
					char lname[9];
					DWORD lnameint;
					Wads.GetLumpName (lname, k);
					memcpy(&lnameint, lname, 4);
					if (lnameint == intname)
					{
						FTextureID picnum = TexMan.CreateTexture(k, FTexture::TEX_SkinSprite);
						bool res = R_InstallSpriteLump (picnum, lname[4] - 'A', lname[5], false, sprtemp, maxframe);

						if (lname[6] && res)
							R_InstallSpriteLump (picnum, lname[6] - 'A', lname[7], true, sprtemp, maxframe);
					}
				}

				if (spr == 0 && maxframe <= 0)
				{
					Printf (PRINT_BOLD, "Skin %s (#%d) has no frames. Removing.\n", skins[i].name, (int)i);
					remove = true;
					break;
				}

				Wads.GetLumpName (temp.name, base+1);
				temp.name[4] = 0;
				int sprno = (int)sprites.Push (temp);
				if (spr==0)	skins[i].sprite = sprno;
				else skins[i].crouchsprite = sprno;
				R_InstallSprite (sprno, sprtemp, maxframe);
			}
		}

		if (remove)
		{
			if (i < numskins-1)
				memmove (&skins[i], &skins[i+1], sizeof(skins[0])*(numskins-i-1));
			i--;
			continue;
		}

		// Register any sounds this skin provides
		aliasid = 0;
		for (j = 0; j < NUMSKINSOUNDS; j++)
		{
			if (sndlumps[j] != -1)
			{
				if (j == 0 || sndlumps[j] != sndlumps[j-1])
				{
					aliasid = S_AddPlayerSound (skins[i].name, skins[i].gender,
						playersoundrefs[j], sndlumps[j], true);
				}
				else
				{
					S_AddPlayerSoundExisting (skins[i].name, skins[i].gender,
						playersoundrefs[j], aliasid, true);
				}
			}
		}

		// Make sure face prefix is a full 3 chars
		if (skins[i].face[1] == 0 || skins[i].face[2] == 0)
		{
			skins[i].face[0] = 0;
		}
	}

	if (numskins > PlayerClasses.Size ())
	{ // The sound table may have changed, so rehash it.
		S_HashSounds ();
		S_ShrinkPlayerSoundLists ();
	}
}
Exemplo n.º 28
0
static float SmoothCurve(float x, float a)
{
	float r = a * x / (2 * a * x - a - x + 1);
	r = (r - 0.5f) * 2;
	return sc(r) * 0.5f + 0.5f;
}
Exemplo n.º 29
0
void ParseCompatibility()
{
	TArray<FMD5Holder> md5array;
	FMD5Holder md5;
	FCompatValues flags;
	int i, x;
	unsigned int j;

	BCompatMap.Clear();
	CompatParams.Clear();

	// The contents of this file are not cumulative, as it should not
	// be present in user-distributed maps.
	FScanner sc(Wads.GetNumForFullName("compatibility.txt"));

	while (sc.GetString())	// Get MD5 signature
	{
		do
		{
			if (strlen(sc.String) != 32)
			{
				sc.ScriptError("MD5 signature must be exactly 32 characters long");
			}
			for (i = 0; i < 32; ++i)
			{
				if (sc.String[i] >= '0' && sc.String[i] <= '9')
				{
					x = sc.String[i] - '0';
				}
				else
				{
					sc.String[i] |= 'a' ^ 'A';
					if (sc.String[i] >= 'a' && sc.String[i] <= 'f')
					{
						x = sc.String[i] - 'a' + 10;
					}
					else
					{
						x = 0;
						sc.ScriptError("MD5 signature must be a hexadecimal value");
					}
				}
				if (!(i & 1))
				{
					md5.Bytes[i / 2] = x << 4;
				}
				else
				{
					md5.Bytes[i / 2] |= x;
				}
			}
			md5array.Push(md5);
			sc.MustGetString();
		} while (!sc.Compare("{"));
		memset(flags.CompatFlags, 0, sizeof(flags.CompatFlags));
		flags.ExtCommandIndex = ~0u;
		while (sc.GetString())
		{
			if ((i = sc.MatchString(&Options[0].Name, sizeof(*Options))) >= 0)
			{
				flags.CompatFlags[Options[i].WhichSlot] |= Options[i].CompatFlags;
			}
			else if (sc.Compare("clearlineflags"))
			{
				if (flags.ExtCommandIndex == ~0u) flags.ExtCommandIndex = CompatParams.Size();
				CompatParams.Push(CP_CLEARFLAGS);
				sc.MustGetNumber();
				CompatParams.Push(sc.Number);
				sc.MustGetNumber();
				CompatParams.Push(sc.Number);
			}
			else if (sc.Compare("setlineflags"))
			{
				if (flags.ExtCommandIndex == ~0u) flags.ExtCommandIndex = CompatParams.Size();
				CompatParams.Push(CP_SETFLAGS);
				sc.MustGetNumber();
				CompatParams.Push(sc.Number);
				sc.MustGetNumber();
				CompatParams.Push(sc.Number);
			}
			else if (sc.Compare("setlinespecial"))
			{
				if (flags.ExtCommandIndex == ~0u) flags.ExtCommandIndex = CompatParams.Size();
				CompatParams.Push(CP_SETSPECIAL);
				sc.MustGetNumber();
				CompatParams.Push(sc.Number);

				sc.MustGetString();
				CompatParams.Push(P_FindLineSpecial(sc.String, NULL, NULL));
				for (int i = 0; i < 5; i++)
				{
					sc.MustGetNumber();
					CompatParams.Push(sc.Number);
				}
			}
			else if (sc.Compare("clearlinespecial"))
			{
				if (flags.ExtCommandIndex == ~0u) flags.ExtCommandIndex = CompatParams.Size();
				CompatParams.Push(CP_CLEARSPECIAL);
				sc.MustGetNumber();
				CompatParams.Push(sc.Number);
			}
			else if (sc.Compare("setactivation"))
			{
				if (flags.ExtCommandIndex == ~0u) flags.ExtCommandIndex = CompatParams.Size();
				CompatParams.Push(CP_SETACTIVATION);
				sc.MustGetNumber();
				CompatParams.Push(sc.Number);
				sc.MustGetNumber();
				CompatParams.Push(sc.Number);
			}
			else if (sc.Compare("sectorflooroffset"))
			{
				if (flags.ExtCommandIndex == ~0u) flags.ExtCommandIndex = CompatParams.Size();
				CompatParams.Push(CP_SECTORFLOOROFFSET);
				sc.MustGetNumber();
				CompatParams.Push(sc.Number);
				sc.MustGetFloat();
				CompatParams.Push(int(sc.Float*65536.));
			}
			else if (sc.Compare("setsectorspecial"))
			{
				if (flags.ExtCommandIndex == ~0u) flags.ExtCommandIndex = CompatParams.Size();
				CompatParams.Push(CP_SETSECTORSPECIAL);
				sc.MustGetNumber();
				CompatParams.Push(sc.Number);
				sc.MustGetNumber();
				CompatParams.Push(sc.Number);
			}
			else if (sc.Compare("setwallyscale"))
			{
				if (flags.ExtCommandIndex == ~0u) flags.ExtCommandIndex = CompatParams.Size();
				CompatParams.Push(CP_SETWALLYSCALE);
				sc.MustGetNumber();
				CompatParams.Push(sc.Number);
				sc.MustGetString();
				CompatParams.Push(sc.MustMatchString(LineSides));
				sc.MustGetString();
				CompatParams.Push(sc.MustMatchString(WallTiers));
				sc.MustGetFloat();
				CompatParams.Push(int(sc.Float*65536.));
			}
			else if (sc.Compare("setthingz"))
			{
				if (flags.ExtCommandIndex == ~0u) flags.ExtCommandIndex = CompatParams.Size();
				CompatParams.Push(CP_SETTHINGZ);
				sc.MustGetNumber();
				CompatParams.Push(sc.Number);
				sc.MustGetFloat();
				CompatParams.Push(int(sc.Float*256));	// do not use full fixed here so that it can eventually handle larger levels
			}
			else if (sc.Compare("setsectortag"))
			{
				if (flags.ExtCommandIndex == ~0u) flags.ExtCommandIndex = CompatParams.Size();
				CompatParams.Push(CP_SETTAG);
				sc.MustGetNumber();
				CompatParams.Push(sc.Number);
				sc.MustGetNumber();
				CompatParams.Push(sc.Number);
			}
			else if (sc.Compare("setthingflags"))
			{
				if (flags.ExtCommandIndex == ~0u) flags.ExtCommandIndex = CompatParams.Size();
				CompatParams.Push(CP_SETTHINGFLAGS);
				sc.MustGetNumber();
				CompatParams.Push(sc.Number);
				sc.MustGetNumber();
				CompatParams.Push(sc.Number);
			}
			else 
			{
				sc.UnGet();
				break;
			}
		}
		if (flags.ExtCommandIndex != ~0u) 
		{
			CompatParams.Push(CP_END);
		}
		sc.MustGetStringName("}");
		for (j = 0; j < md5array.Size(); ++j)
		{
			BCompatMap[md5array[j]] = flags;
		}
		md5array.Clear();
	}
}
Exemplo n.º 30
0
int main(int argc, char **argv) {
    odsupercomponent::SuperComponent sc(argc, argv);
    return sc.runModule();
}