// static
bool MixedContentChecker::shouldBlockFetch(LocalFrame* frame, WebURLRequest::RequestContext requestContext, WebURLRequest::FrameType frameType, ResourceRequest::RedirectStatus redirectStatus, const KURL& url, MixedContentChecker::ReportingStatus reportingStatus)
{
    Frame* effectiveFrame = effectiveFrameForFrameType(frame, frameType);
    Frame* mixedFrame = inWhichFrameIsContentMixed(effectiveFrame, frameType, url);
    if (!mixedFrame)
        return false;

    MixedContentChecker::count(mixedFrame, requestContext);
    if (ContentSecurityPolicy* policy = frame->securityContext()->contentSecurityPolicy())
        policy->reportMixedContent(url, redirectStatus);

    Settings* settings = mixedFrame->settings();
    // Use the current local frame's client; the embedder doesn't
    // distinguish mixed content signals from different frames on the
    // same page.
    FrameLoaderClient* client = frame->loader().client();
    SecurityOrigin* securityOrigin = mixedFrame->securityContext()->getSecurityOrigin();
    bool allowed = false;

    // If we're in strict mode, we'll automagically fail everything, and intentionally skip
    // the client checks in order to prevent degrading the site's security UI.
    bool strictMode = mixedFrame->securityContext()->getInsecureRequestPolicy() & kBlockAllMixedContent || settings->strictMixedContentChecking();

    WebMixedContent::ContextType contextType = WebMixedContent::contextTypeFromRequestContext(requestContext, settings->strictMixedContentCheckingForPlugin());

    // If we're loading the main resource of a subframe, we need to take a close look at the loaded URL.
    // If we're dealing with a CORS-enabled scheme, then block mixed frames as active content. Otherwise,
    // treat frames as passive content.
    //
    // FIXME: Remove this temporary hack once we have a reasonable API for launching external applications
    // via URLs. http://crbug.com/318788 and https://crbug.com/393481
    if (frameType == WebURLRequest::FrameTypeNested && !SchemeRegistry::shouldTreatURLSchemeAsCORSEnabled(url.protocol()))
        contextType = WebMixedContent::ContextType::OptionallyBlockable;

    switch (contextType) {
    case WebMixedContent::ContextType::OptionallyBlockable:
        allowed = !strictMode && client->allowDisplayingInsecureContent(settings && settings->allowDisplayOfInsecureContent(), url);
        if (allowed)
            client->didDisplayInsecureContent();
        break;

    case WebMixedContent::ContextType::Blockable: {
        // Strictly block subresources that are mixed with respect to
        // their subframes, unless all insecure content is allowed. This
        // is to avoid the following situation: https://a.com embeds
        // https://b.com, which loads a script over insecure HTTP. The
        // user opts to allow the insecure content, thinking that they are
        // allowing an insecure script to run on https://a.com and not
        // realizing that they are in fact allowing an insecure script on
        // https://b.com.
        if (!settings->allowRunningOfInsecureContent() && requestIsSubframeSubresource(effectiveFrame, frameType) && isMixedContent(frame->securityContext()->getSecurityOrigin(), url)) {
            UseCounter::count(mixedFrame, UseCounter::BlockableMixedContentInSubframeBlocked);
            allowed = false;
            break;
        }

        bool shouldAskEmbedder = !strictMode && settings && (!settings->strictlyBlockBlockableMixedContent() || settings->allowRunningOfInsecureContent());
        allowed = shouldAskEmbedder && client->allowRunningInsecureContent(settings && settings->allowRunningOfInsecureContent(), securityOrigin, url);
        if (allowed) {
            client->didRunInsecureContent(securityOrigin, url);
            UseCounter::count(mixedFrame, UseCounter::MixedContentBlockableAllowed);
        }
        break;
    }

    case WebMixedContent::ContextType::ShouldBeBlockable:
        allowed = !strictMode;
        if (allowed)
            client->didDisplayInsecureContent();
        break;
    case WebMixedContent::ContextType::NotMixedContent:
        NOTREACHED();
        break;
    };

    if (reportingStatus == SendReport)
        logToConsoleAboutFetch(frame, mainResourceUrlForFrame(mixedFrame), url, requestContext, allowed);
    return !allowed;
}
Ejemplo n.º 2
0
void main()
{
	/*settings.setOption("MarkExecute", "menuKey", "F3");
	settings.setOption("MarkExecute", "markKey", "X");
	settings.setOption("MarkExecute", "executeKey", "E");
	settings.setOption("MarkExecute", "markAllOnHold", "true");
	settings.setOption("MarkExecute", "targetsLimit", "5");
	settings.setOption("MarkExecute", "killCam", "Random");*/

	settings.load("MarkExecute.ini");
	if (settings.getOptions().size() == 0)
	{
		settings.setOption("MarkExecute", "menuKey", "F3");
		settings.setOption("MarkExecute", "markKey", "X");
		settings.setOption("MarkExecute", "executeKey", "E");
		settings.setOption("MarkExecute", "markAllOnHold", "true");
		settings.setOption("MarkExecute", "targetsLimit", "5");
		settings.setOption("MarkExecute", "killCam", "Random");

		settings.save();
	}

	targetsLimit = parseTargetsLimit(settings.getOption("targetsLimit"));
	
	createMenu();

	InitEyeX();
	
	Ped playerPed;
	GRAPHICS::REQUEST_STREAMED_TEXTURE_DICT("GolfPutting", true);

	Vector3 markerPosition;

	bool doublePressState = false;
	bool menuState = false;
	DWORD inputWait = 0;
	DWORD holdTime = 0;
	DWORD doublePressTime1 = 0;
	DWORD doublePressTime2 = 0;
	while (true)
	{
		playerPed = PLAYER::GET_PLAYER_PED(0);

		if (menuState) menu.draw();

		if (IsKeyCombinationDown(settings.getOption("menuKey")) && inputWait < GetTickCount())
		{
			menuState = !menuState;
			inputWait = GetTickCount() + 500;
		}

		if (PLAYER::IS_PLAYER_FREE_AIMING(0))
		{
			if (
				markButtonUp &&
				(IsKeyCombinationDown(settings.getOption("markKey")) || IsControllerButtonPressed(XINPUT_GAMEPAD_A)) &&
				inputWait < GetTickCount()
			)
			{
				markButtonUp = false;
				inputWait = GetTickCount() + 100;

				Entity pedTarget;

				if (PLAYER::GET_PLAYER_TARGET_ENTITY(PLAYER::PLAYER_ID(), &pedTarget) || PLAYER::_GET_AIMED_ENTITY(PLAYER::PLAYER_ID(), &pedTarget))
				{
					if (!isPedMarked(pedTarget))
					{
						markTargetPed(pedTarget);
					} else {
						unmarkTargetPed(pedTarget);
					}
				}
			}
		} else {
			if(settings.getOptionBool("markAllOnHold"))
			{
				if (IsKeyCombinationDown(settings.getOption("markKey")) || IsControllerButtonPressed(XINPUT_GAMEPAD_B))
				{
					if(holdTime == 0) holdTime = GetTickCount();
					
					if(holdTime + 1000 < GetTickCount())
					{
						markButtonUp = false;

						const int arrSize = MAX_TARGETS_LIMIT * 2 + 2;
						int foundPeds[arrSize];
						foundPeds[0] = targetsLimit;

						int count = PED::GET_PED_NEARBY_PEDS(playerPed, foundPeds, -1);
						if (count > MAX_TARGETS_LIMIT) count = MAX_TARGETS_LIMIT;
						for (int i = 0; i < count; ++i)
						{
							int offsettedID = i * 2 + 2;
							
							if (ENTITY::DOES_ENTITY_EXIST(foundPeds[offsettedID]))
							{
								Ped targetPed = foundPeds[offsettedID];
								markTargetPed(targetPed);
							}
						}
						
						holdTime = 0;
					}
				} else {
					holdTime = 0;
				}
			} else {
				holdTime = 0;
			}

			if (markButtonUp && (IsKeyCombinationDown(settings.getOption("markKey")) || IsControllerButtonPressed(XINPUT_GAMEPAD_A)))
			{
				markButtonUp = false;

				Vector3 lookScreenPos;

				if (getScreenCoords(&lookScreenPos))
				{
					const int arrSize = CAMERA_MARK_PEDS_LIMIT * 2 + 2;
					int foundPeds[arrSize];
					foundPeds[0] = CAMERA_MARK_PEDS_LIMIT;

					int count = PED::GET_PED_NEARBY_PEDS(playerPed, foundPeds, 100);
					if (count > CAMERA_MARK_PEDS_LIMIT) count = CAMERA_MARK_PEDS_LIMIT;
					for (int i = 0; i < count; ++i)
					{
						int offsettedID = i * 2 + 2;

						if (ENTITY::DOES_ENTITY_EXIST(foundPeds[offsettedID]))
						{
							Ped targetPed = foundPeds[offsettedID];
							Vector3 targetPedPos = ENTITY::GET_ENTITY_COORDS(targetPed, true);

							float targetPedScreenPosX, targetPedScreenPosY;
							GRAPHICS::_WORLD3D_TO_SCREEN2D(targetPedPos.x, targetPedPos.y, targetPedPos.z, &targetPedScreenPosX, &targetPedScreenPosY);

							Vector3 targetPedScreenPos;
							targetPedScreenPos.x = targetPedScreenPosX;
							targetPedScreenPos.y = targetPedScreenPosY;

							/*DWORD test = GetTickCount();
							while (true)
							{
							if (test + 2000 < GetTickCount()) break;
							showMessage(to_string(lookScreenPos.x) + ", " + to_string(lookScreenPos.y) + " - " + to_string(targetPedScreenPos.x) + ", " + to_string(targetPedScreenPos.y));
							WAIT(0);
							}*/

							if (getDistanceBetweenPoints(lookScreenPos, targetPedScreenPos) < 0.1)
							{
								if (!isPedMarked(targetPed))
								{
									markTargetPed(targetPed);
								} else
								{
									unmarkTargetPed(targetPed);
								}
								break;
							}
						}
					}
				}
			}
		}

		if (IsKeyCombinationJustUp(settings.getOption("markKey")) || IsControllerButtonJustPressed(XINPUT_GAMEPAD_A))
		{
			markButtonUp = true;
		}

		if (
			(IsKeyCombinationDown(settings.getOption("executeKey")) || doublePressState) &&
			(pedTargets.size() > 0 && !PED::IS_PED_IN_ANY_VEHICLE(playerPed, 0) && inputWait < GetTickCount())
		)
		{
			inputWait = GetTickCount() + 500;
			
			// Wlaczenie wlasnych kamer, ustawienie punku startowego do przejsc kamery
			
			//Any camera = CAM::GET_RENDERING_CAM();
			Vector3 gameplayCamPos = CAM::GET_GAMEPLAY_CAM_COORD();
			Vector3 gameplayCamRot = CAM::GET_GAMEPLAY_CAM_ROT(2);
			float gameplayCamFov = CAM::GET_GAMEPLAY_CAM_FOV();

			
			Any camera = CAM::CREATE_CAM_WITH_PARAMS("DEFAULT_SCRIPT_CAMERA", gameplayCamPos.x, gameplayCamPos.y, gameplayCamPos.z, gameplayCamRot.x, gameplayCamRot.y, gameplayCamRot.z, gameplayCamFov, 1, 0);
			CAM::SET_CAM_ACTIVE(camera, 1);

			CAM::RENDER_SCRIPT_CAMS(1, 0, 3000, 1, 0);
			
			// Potrzebne informacje
			Vector3 playerPosition = ENTITY::GET_ENTITY_COORDS(playerPed, 1);
			Hash playerWeapon;
			WEAPON::GET_CURRENT_PED_WEAPON(playerPed, &playerWeapon, true);

			// Tymczasowe odebranie kontroli
			PLAYER::SET_PLAYER_CONTROL(0, FALSE, 0);
			AI::CLEAR_PED_TASKS(playerPed);

			DWORD maxCheckTime = GetTickCount() + 500;
			while (true)
			{
				if (maxCheckTime < GetTickCount() || (!AI::IS_PED_RUNNING(playerPed) && !AI::IS_PED_SPRINTING(playerPed)))
				{
					break;
				}

				WAIT(0);
			}

			int i = 0;
			DWORD time = GetTickCount();
			for (auto &ped : pedTargets)
			{
				// Wybranie kamery zabojstwa
				string killCamName = settings.getOption("killCam");
				KillCam* killCam = new KillCam();

				if (killCamName == "Random")
				{
					int randomCam = rand() % 4 + 1;
					
					if (randomCam == 1) killCamName = "CloseUp";
					else if (randomCam == 2) killCamName = "Simple";
					else if (randomCam == 3) killCamName = "SimpleFast";
					else killCamName = "CloseUp";
				}

				if (killCamName == "CloseUp") killCam = new CloseUpKillCam(&playerPed, &ped, &camera);
				else if (killCamName == "Simple") killCam = new SimpleKillCam(&playerPed, &ped, &camera);
				else if (killCamName == "SimpleFast") killCam = new SimpleFastKillCam(&playerPed, &ped, &camera);
				else if (killCamName == "TopDown") killCam = new TopDownKillCam(&playerPed, &ped, &camera);
				//

				AI::TASK_SHOOT_AT_ENTITY(playerPed, ped, 700, 5);

				//Vector3 pedPosition = ENTITY::GET_ENTITY_COORDS(ped, true);

				//AI::TASK_TURN_PED_TO_FACE_ENTITY(playerPed, ped, 1500);
				//AI::TASK_SHOOT_AT_COORD(playerPed, pedPosition.x, pedPosition.y, pedPosition.z, 100, 6);

				Vector3 targetPedPos = ENTITY::GET_ENTITY_COORDS(ped, 1);
				DWORD timeToKill = 0;
				bool camStillPlaying = false;
				time = GetTickCount();
				while (true)
				{
					if (timeToKill == 0)
					{
						if (playerWeapon == GAMEPLAY::GET_HASH_KEY("WEAPON_RPG") || playerWeapon == GAMEPLAY::GET_HASH_KEY("WEAPON_HOMINGLAUNCHER") || playerWeapon == GAMEPLAY::GET_HASH_KEY("WEAPON_GRENADELAUNCHER"))
						{
							if (GAMEPLAY::IS_PROJECTILE_IN_AREA(targetPedPos.x - 9.0f, targetPedPos.y - 9.0f, targetPedPos.z - 9.0f, targetPedPos.x + 9.0f, targetPedPos.y + 9.0f, targetPedPos.z + 9.0f, 1))
							{
								killCam->killHeadsUp();
								timeToKill = GetTickCount();
							}
						}

						else if (PED::IS_PED_SHOOTING(playerPed))
						{
							killCam->killHeadsUp();
							timeToKill = GetTickCount();
						}
					}

					if (timeToKill != 0 && timeToKill != -1 && timeToKill + 150 < GetTickCount())
					{
						PED::EXPLODE_PED_HEAD(ped, playerWeapon);
						timeToKill = -1;
					}

					camStillPlaying = killCam->play();

					if (time + 1000 < GetTickCount() && (!camStillPlaying || time + 4000 < GetTickCount()))
					{
						ENTITY::SET_ENTITY_AS_NO_LONGER_NEEDED(&ped);
						reloadWeapon();

						break;
					}
					
					WAIT(0);
				}
				
				GAMEPLAY::SET_TIME_SCALE(1.0);

				CAM::DESTROY_CAM(camera, 0);
				camera = killCam->getCustomCam();

				//delete &killCam;
				
				if(i < pedTargets.size() - 1) WAIT(getReloadDelay(playerWeapon));

				i++;
			}

			//CAM::SET_CAM_ACTIVE(camera, 0);
			CAM::RENDER_SCRIPT_CAMS(0, 0, 3000, 1, 0);
			
			CAM::DESTROY_CAM(camera, 0);

			PLAYER::SET_PLAYER_CONTROL(0, TRUE, 0);
			pedTargets.clear();
			
			doublePressState = false;
		}
		
		// Controller double-press
		if (IsControllerButtonPressed(XINPUT_GAMEPAD_A))
		{
			if (doublePressTime2 != 0 && doublePressTime2 - doublePressTime1 < 150)
			{
				doublePressState = true;
			} else
			{
				doublePressTime1 = GetTickCount();
				doublePressTime2 = 0;
				doublePressState = false;
			}
		}

		if (!IsControllerButtonPressed(XINPUT_GAMEPAD_A) && doublePressTime1 != 0)
		{
			doublePressTime2 = GetTickCount();
		}
		//

		if (GRAPHICS::HAS_STREAMED_TEXTURE_DICT_LOADED("GolfPutting"))
		{
			for (auto &ped : pedTargets)
			{
				if (!PED::_IS_PED_DEAD(ped, 1))
				{
					markerPosition = ENTITY::GET_ENTITY_COORDS(ped, true);
					GRAPHICS::DRAW_MARKER(3, markerPosition.x, markerPosition.y, markerPosition.z + 1.1, 0.0, 0.0, 0.0, 0.0, 90.0, 0.0, 0.5, 0.5, 0.5, 153, 0, 0, 200, true, true, 2, false, "GolfPutting", "PuttingMarker", 0);
				} else
				{
					unmarkTargetPed(ped);
				}
			}
		}

		WAIT(0);
	}
}
Ejemplo n.º 3
0
CTTToeView::CTTToeView()
{ 	
	aiThread = nullptr;
	handleInitialized = false;

	fieldStyles.push_back(FieldStyle(DSI_FIELD_BACKGROUND_SETS, DSI_FIELD_FRAME_SETS, DSI_CELL_USER_SETS, DSI_CELL_AI_SETS, DSI_CELL_EMPTY_SETS));
	fieldStyles.push_back(FieldStyle(DSI_FIELD_BACKGROUND_SETS_2, DSI_FIELD_FRAME_SETS_2, DSI_CELL_USER_SETS_2, DSI_CELL_AI_SETS_2, DSI_CELL_EMPTY_SETS_2));

	settings.emptyIndex = DSI_CELL_EMPTY_SETS;
	settings.xIndex = DSI_CELL_USER_SETS;
	settings.oIndex = DSI_CELL_AI_SETS;

	settings.showtrack = true;
	settings.convex = false;
	settings.distCellHalf = 1;
	settings.distSub = 0;
	settings.backgroundIndex = DSI_BACKGROUND_SETS;
	settings.fieldBackgroundIndex = DSI_FIELD_BACKGROUND_SETS;
	settings.fieldSize = 20;
	settings.fieldULX = 20;
	settings.fieldULY = 20;
	settings.frameExists = true;
	settings.frameColPos = DSI_FIELD_FRAME_SETS;
	settings.frameMargin = 2;
	settings.frameWidth = 1;
	settings.grow = false;
	settings.numOfSubCells = 1;
	settings.posnum = 12;
	settings.separatingLinesExist = true;
	settings.separatingLineWidth = 1;
	settings.separatingLineIndex = DSI_FIELD_FRAME_SETS; 
	int* sizes = new int[12];
	settings.subCellSizes = sizes;
	settings.setSizes(1, 16);
	settings.fieldStyleInd = 0;

	settings.cellMonochrome = false;

	settingsVector.push_back(settings);

	Settings settings2 = settings;
	settings2.fieldStyleInd = 1;

	settingsVector.push_back(settings2);

	Settings settings3 = settings;
	settings3.setSizes(1,5);
	settings3.numOfSubCells = 3;

	settingsVector.push_back(settings3);

	Settings settings4 = settings3;
	settings4.fieldStyleInd = 1;

	settingsVector.push_back(settings4);

	Settings settings5 = settings;
	settings5.grow = true;

	settingsVector.push_back(settings5);

	Settings settings6 = settings5;
	settings6.fieldStyleInd = 1;

	settingsVector.push_back(settings6);

	Settings settings7 = settings;
	settings7.numOfSubCells = 3;
	settings7.setSizes(1,5);
	settings7.grow = true;

	settingsVector.push_back(settings7);

    Settings settings8 = settings;
	settings8.fieldSize = 19;
	settings8.numOfSubCells = 16;
	settings8.setSizes(1,1);

	settingsVector.push_back(settings8);

    Settings settings9 = settings;

	settings9.fieldBackgroundIndex = DSI_BACKGROUND_SETS;
	settings9.frameExists = false;
	settings9.separatingLinesExist = false;
	settings9.fieldStyleInd = 1;

	settingsVector.push_back(settings9);

    Settings settings10 = settings9;
	
	settings10.distCellHalf = 0;

	settingsVector.push_back(settings10);

	Settings settings11 = settings10;
	
	settings11.grow = true;

	settingsVector.push_back(settings11);

	GlobalSettings::settingsInd = 0;
	GlobalSettings::aiSettings.winCombLength = 5;
    GlobalSettings::aiSettings.randDif = 30.0;
	GlobalSettings::aiSettings.level.depth = 7;
	GlobalSettings::aiSettings.level.baseSelNum = 10;
	GlobalSettings::aiSettings.level.selNum = 5;

	GlobalSettings::aiSettings.coeficients.push_back(0.0);
	GlobalSettings::aiSettings.coeficients.push_back(10000000000.0);
	GlobalSettings::aiSettings.coeficients.push_back(100000000.0);
	GlobalSettings::aiSettings.coeficients.push_back(1000000.0);
	GlobalSettings::aiSettings.coeficients.push_back(10000.0);
	GlobalSettings::aiSettings.coeficients.push_back(10.0);

	field = new Field();
	field->initialize(&settings, Point(settings.fieldULX, settings.fieldULY, 0), &DS);
	field->rateField->fld = field;	
	objectsToDelete.push_back(field);
	//field->setMode(Field::MODE_MOVE);

	Graphics::drawSets = &DS;

	Clr backgroundClr(255,255,255);

	GlobalSettings::backgroundClr = backgroundClr;
	GlobalSettings::menuWidth = 200;

	initializeControls();
	initializeDrawSet();

	GlobalSettings::gameLevel = 4;

	gameLevels.push_back(GameLevel(1,1,1));
	gameLevels.push_back(GameLevel(3,15,9));	
	gameLevels.push_back(GameLevel(5,10,5));
	gameLevels.push_back(GameLevel(5,15,9));
	gameLevels.push_back(GameLevel(7,10,5));
	gameLevels.push_back(GameLevel(7,15,9));
	gameLevels.push_back(GameLevel(9,10,5));

	srand((unsigned int)time(0));
}
Ejemplo n.º 4
0
int main( int argc, char* args[] ) 
{
	
	if (InitSDL())
	{
		WindowSurface screen(800,600);
		MusicHandler musicHandler;
		SoundEffectsHandler sfxHandler;
		Graphics graphics;
		Sounds sounds;
		Settings setting;
		Maps levels;
		GlobalSettings gSettings;
		GameStateManager gameStates(&setting);
		SettingSaverLoader ssl;
		ssl.LoadSettings(gSettings);
		long Timer = clock();//For Frame Independent Movement
		bool gameRunning=true;
		FPS fps(30);
		SDL_Event sEvent;
		musicHandler.SetNewMusic(&sounds.titleScreen);	
		sfxHandler.AddSoundEffect(&sounds.death);
		sfxHandler.AddSoundEffect(&sounds.bell);
		sfxHandler.AddSoundEffect(&sounds.damage);
		sfxHandler.AddSoundEffect(&sounds.enemyDeath);
		gameStates.NewState(GSIntro);

		int introCount=0; float logoPositionY = 0;

		Surface surface; surface.LoadImage("Images/icon.png", 255, 255, 0);
		SDL_WM_SetIcon(surface, NULL);
		screen.SetCaption("A Rat's Tale");

		EnemyHandler enemies;
		Map map(&graphics.tileSheet, 50, 50, "Map/map1.txt");
		levels.count++;

		map.AddTile('A', 0, 0);
		map.AddTile('B', 50, 0);
		map.AddTile('C', 100, 0);
		map.AddTile('D', 0, 50);
		map.AddTile('E', 50, 50);
		map.AddTile('F', 100, 50);
		map.AddTile('G', 0, 100);
		map.AddTile('H', 50, 100);
		map.AddTile('I', 100, 100);
		map.AddTile('J', 0, 150);
		map.AddTile('K', 50, 150);
		map.AddTile('L', 100, 150);
		map.AddTile('M', 150, 0);
		map.AddTile('N', 150, 50);
		map.AddTile('O', 150, 100);

		map.AddTile('P', 200, 0);
		map.AddTile('Q', 250, 0);
		map.AddTile('R', 200, 50);
		map.AddTile('S', 250, 50);
		map.AddTile('T', 200, 100);
		map.AddTile('U', 250, 100);
		map.AddTile('V', 150, 150);
		map.AddTile('W', 200, 150);
		map.AddTile('X', 250, 150);
		map.AddTile('Y', 150, 200);
		map.AddTile('Z', 200, 200);
		map.AddTile('(', 250, 200);
		map.AddTile(')', 300, 200);

		map.AddTile('>', 300, 0, 50, 0);
		map.AddTile('<', 300, 50, 0, 50);
		map.AddTile('\\', 300, 100, 50, 0);
		map.AddTile('/', 300, 150, 0, 50);

		map.AddTile('a', 350, 50);
		map.AddTile('b', 400, 50);
		map.AddTile('c', 450, 50);
		map.AddTile('d', 350, 100);
		map.AddTile('e', 400, 100);
		map.AddTile('f', 450, 100);
		map.AddTile('g', 350, 150);
		map.AddTile('h', 400, 150);
		map.AddTile('i', 450, 150);
		map.AddTile('j', 350, 0);
		map.AddTile('k', 400, 0);
		map.AddTile('l', 450, 0);

		map.AddTile('w', 500, 0, 50, 0);
		map.AddTile('v', 500, 50, 0, 50);
		map.AddTile('x', 500, 100, 50, 0);
		map.AddTile('y', 500, 150, 0, 50);
	
		map.AddTile('m', 0, 200, 0, 50);
		map.AddTile('n', 50, 200);
		map.AddTile('o', 100, 200, 50, 0);
	
		map.AddTile('p', 350, 200, TStop);
		map.AddTile('q', 400, 200, TSleft);
		map.AddTile('r', 450, 200, TSright);
		map.AddTile('s', 500, 200, TSbottom);
		
		map.AddTile('u', 200, 250, false, true);
		map.AddTile('z', 50, 250, false, true);
		map.AddTile('@', 150, 250);
		map.AddTile('!', 100, 250);

		Player player(&graphics.player, map.GetSpawnLocation().X, map.GetSpawnLocation().Y, 3, 3, 2);
		player.SetVelocity(200, 300); //If Timer is set in draw of player (50 pixels per second) else (50pixels per frame)
		Menu menu("Main menu", &setting, 255, 255, 255);
		menu.ShowHeader(false);
		menu.SetCenter(true);
		menu.SetVerticalSpace(20);
		menu.AddButtonChild("New game",false,255,255,255, &Settings::OnClickNewGame);
		menu.AddButtonChild("Load game",false,255,255,255, &Settings::OnClickLoadGame);
		menu.AddChild("Options", true);
		menu.GetChild(2)->SetVerticalSpace(20);
		menu.GetChild(2)->AddChild("Graphics",true);
		menu.GetChild(2)->GetChild(0)->AddChild("FPS Setting");
		menu.GetChild(2)->GetChild(0)->AddChild("Resolution");
		menu.GetChild(2)->AddChild("Sounds",true);
		menu.GetChild(2)->GetChild(1)->AddChild("Master Volume");
		menu.GetChild(2)->GetChild(1)->AddSliderChild(256,10,true,155,155,155,&SetNewVolume,&gSettings);
		((SliderMenuItem*)(menu.GetChild(2)->GetChild(1)->GetChild(1)))->SetStatus((int)(gSettings._volume*256));
		menu.GetChild(2)->GetChild(1)->AddChild("SFX-Music");
		menu.GetChild(2)->GetChild(1)->AddSliderChild(256,10,true,30,200,30,&SetNewProportion,&gSettings);
		((SliderMenuItem*)(menu.GetChild(2)->GetChild(1)->GetChild(3)))->SetStatus((int)(gSettings._sfxMusicProportion*256));
		menu.GetChild(2)->AddChild("Keys");
		menu.AddButtonChild("Exit",false,255,255,255, &Settings::OnClickExitGame);

		Menu newLevelMenu("Level completed", &setting);
		newLevelMenu.SetCenter(true);
		newLevelMenu.SetVerticalSpace(20);
		newLevelMenu.AddChild("Congratulations");
		newLevelMenu.AddChild("");
		newLevelMenu.AddChild("What do you want to do?");
		std::vector<std::string> opt; opt.push_back("Main menu"); opt.push_back("Restart"); opt.push_back("Next level");
		newLevelMenu.AddOptionChild(opt, "       ",false,255,255,255,&Settings::NewLevelOptions);

		Menu gameOverMenu("Game Over!", &setting);
		gameOverMenu.SetCenter(true);
		gameOverMenu.SetVerticalSpace(20);
		gameOverMenu.AddChild("Your journey has ended. You want to restart?");
		std::vector<std::string> opts; opts.push_back("Yes"); opts.push_back("No"); opts.push_back("Quit");
		gameOverMenu.AddOptionChild(opts, "    ", false, 255, 255, 255, &Settings::GameOverOptions);

		Menu inGameMenu("Pause",&setting,255,0,0);
		inGameMenu.SetCenter(true);
		inGameMenu.SetVerticalSpace(20);
		inGameMenu.AddButtonChild("Resume" ,true,255,255,255,&Settings::OnClickResume);
		inGameMenu.AddChild("Show statistics" ,true,255,255,255);
			inGameMenu.GetChild(1)->AddChild("Current level: ");
			inGameMenu.GetChild(1)->AddChild("Remaining Lives: ");
			inGameMenu.GetChild(1)->AddChild("Progression: ");
			inGameMenu.GetChild(1)->AddChild("Enemies killed: ");
			inGameMenu.GetChild(1)->AddChild("Game completion: ");
			inGameMenu.GetChild(1)->AddChild("Total distance drawn: ");
		inGameMenu.AddChild("Options", true);
			inGameMenu.GetChild(2)->SetVerticalSpace(20);
			inGameMenu.GetChild(2)->AddChild("Graphics",true);
			inGameMenu.GetChild(2)->GetChild(0)->AddChild("FPS Setting");
			inGameMenu.GetChild(2)->GetChild(0)->AddChild("Resolution");
			inGameMenu.GetChild(2)->AddChild("Sounds",true);
				inGameMenu.GetChild(2)->GetChild(1)->AddChild("Master Volume");
				inGameMenu.GetChild(2)->GetChild(1)->AddSliderChild(256,10,true,155,155,155,&SetNewVolume,&gSettings);
				((SliderMenuItem*)(menu.GetChild(2)->GetChild(1)->GetChild(1)))->SetStatus((int)(gSettings._volume*256));
				inGameMenu.GetChild(2)->GetChild(1)->AddChild("SFX-Music");
				inGameMenu.GetChild(2)->GetChild(1)->AddSliderChild(256,10,true,30,200,30,&SetNewProportion,&gSettings);
				((SliderMenuItem*)(menu.GetChild(2)->GetChild(1)->GetChild(3)))->SetStatus((int)(gSettings._sfxMusicProportion*256));
			inGameMenu.GetChild(2)->AddChild("Keys");
		inGameMenu.AddChild("Quit",true,255,0,0);
			inGameMenu.GetChild(3)->AddButtonChild("Exit to main menu",true,0,255,0, &Settings::OnClickNewGame);
			inGameMenu.GetChild(3)->AddButtonChild("Exit game",true,255,255,255, &Settings::OnClickExitGame);

		int NewLevelID = 0;
		int LevelCounter = 0;
		bool actionButtonPressed = false;
		//((OptionMenuItem*)newLevelMenu.GetChild(3))->GetOption(1)->Enabled = false;

		while (gameRunning)
		{
			while (SDL_PollEvent(&sEvent))
			{
				if (sEvent.type==SDL_QUIT || setting.GetResult() == MRExitGame){
					gameRunning=false;
					setting.Finish();
				}
				if (sEvent.type == SDL_VIDEORESIZE ) {screen.CreateWindowSurface( sEvent.resize.w,sEvent.resize.h);}
				switch(gameStates.CurrentState())
				{
				case GSIntro:
					if (sEvent.type == SDL_KEYDOWN||sEvent.type == SDL_MOUSEBUTTONDOWN)
					{
						logoPositionY=20;
						introCount=256;
						graphics.gameLogo.SetTransparency(256);
					}
				case GSMenuMain:
					if(sEvent.type == SDL_KEYDOWN){
						if(sEvent.key.keysym.sym == SDLK_ESCAPE) 
						{gameStates.BackState();menu.Reset();}
					}
						menu.HandleEvent(sEvent);
						break;
				case GSPause:
					{
						if(sEvent.type == SDL_KEYDOWN){
							if(sEvent.key.keysym.sym == SDLK_ESCAPE) 
							{gameStates.BackState();inGameMenu.Reset();}
						}
						inGameMenu.HandleEvent(sEvent);
						break;
					}
				case GSGame:
					if(sEvent.type == SDL_KEYDOWN) {
						if(sEvent.key.keysym.sym == SDLK_ESCAPE) {gameStates.PushState(GSPause);}
						else if(sEvent.key.keysym.sym == SDLK_s||sEvent.key.keysym.sym == SDLK_DOWN) {actionButtonPressed=true;}
					}
					if(sEvent.type == SDL_KEYUP){
						if(sEvent.key.keysym.sym == SDLK_s||sEvent.key.keysym.sym == SDLK_DOWN)
						{actionButtonPressed=false;}
					}
					player.HandleEvent(sEvent);
					map.HandleEvent(sEvent);
					break;
				case GSMenuNewLevel:
					newLevelMenu.HandleEvent(sEvent);
					break;
				case GSGame_Over:
					gameOverMenu.HandleEvent(sEvent);
					break;
				}
			}

			if(clock() > Timer + 500) Timer = clock();
			if(gameStates.CurrentState() == GSNone) gameStates.PushState(GSMenuMain);
			if(gameStates.CurrentState() == GSGame && player.Health <= 0)
			{
				gameStates.PushState(GSGame_Over);
				sounds.forest.SetVolumeModifier(0.1f);
				sounds.death.Play(false);
			}
			screen.ClearWindow();
			float musicPercentage=2*gSettings._sfxMusicProportion;
			if (musicPercentage>1.0){musicPercentage=1.0;}
			float sfxPercentage=2-2*gSettings._sfxMusicProportion;
			if (sfxPercentage>1.0){sfxPercentage=1.0;}
			musicHandler.SetGlobalVolume((int)(gSettings._volume*musicPercentage*128));
			sfxHandler.SetGlobalVolume((int)(gSettings._volume*sfxPercentage*128));
			switch(gameStates.CurrentState())
			{
			case GSIntro:
				if(introCount > 255){
					logoPositionY -= 5;
					if(logoPositionY <= 20){ logoPositionY = 20; gameStates.NewState(GSMenuMain); }
					Timer = clock();
					graphics.gameLogo.Draw(screen, screen.GetWidth()/2 - graphics.gameLogo.GetWidth()/2, (unsigned int)logoPositionY);
				}
				else {
					graphics.gameLogo.SetTransparency(introCount);
					logoPositionY = (float)screen.GetHeight()/2 - (float)graphics.gameLogo.GetHeight()/2;
					Timer = clock();
					graphics.gameLogo.Draw(screen, screen.GetWidth()/2 - graphics.gameLogo.GetWidth()/2, (unsigned int)logoPositionY);
				}
				introCount+=2;
				break;
			case GSMenuMain:
				if(setting.GetResult() == MRNewGame){
					musicHandler.SetNewMusic(&sounds.forest);
					levels.count = 0;
					LevelCounter = 0;
					map.Reset();
					map.NewMap(levels.levels[0]);
					enemies.PopulateEnemies(&map, &graphics);
					player.Reset(map.GetSpawnLocation(), true);
					gameStates.NewState(GSGame);
					setting.Finish();
				}else if (setting.GetResult()==MRLoadGame)
				{
					Loader load;
					if (load.StartAndCheck("Save1.sav"))
					{
						int newMapId;
						load.LoadCheckpoint(LevelCounter,newMapId);
						if(levels.maxCount <= newMapId || newMapId < 0)	newMapId = 0;
						levels.count = newMapId;
						load.LoadMap(map);
						load.LoadPlayer(player);
						load.Close();
						map.NewMap(levels.levels[newMapId]);
						enemies.PopulateEnemies(&map, &graphics);
						gameStates.NewState(GSGame);
						musicHandler.SetNewMusic(&sounds.forest);
						player.Reset(map.GetSpawnLocation(), false);
					}
					setting.Finish();
				}
				musicHandler.Update();
				Timer = clock();
				graphics.gameLogo.Draw(screen, screen.GetWidth()/2 - graphics.gameLogo.GetWidth()/2, (unsigned int)logoPositionY);
				menu.Open(screen, graphics.another, Point2D(50, logoPositionY + graphics.gameLogo.GetHeight()));
				break;
			case GSPause:
				{
					if(setting.GetResult() == MRResume){
						gameStates.BackState();
						inGameMenu.Reset();
						setting.Finish();
					}else if(setting.GetResult() == MRLoadGame)
					{
						Loader load;
						if (load.StartAndCheck("tempOldSave.sav"))
						{
							int newMapId;
							load.LoadCheckpoint(LevelCounter,newMapId);
							if(levels.maxCount <= newMapId || newMapId < 0)	newMapId = 0;
							levels.count = newMapId;
							load.LoadMap(map);
							load.LoadPlayer(player);
							load.Close();
							map.NewMap(levels.levels[newMapId]);
							enemies.PopulateEnemies(&map, &graphics);
							gameStates.NewState(GSGame);
							musicHandler.SetNewMusic(&sounds.forest);
							player.Reset(map.GetSpawnLocation(), false);
							Saver save;
							save.StartAndOpen();
							save.SaveCheckpoint(LevelCounter,levels.count);
							save.SaveMap(map);
							save.SavePlayer(player);
							save.EndAndClose("Save1.sav");
						}
						if (load.StartAndCheck("tempSave.sav"))
						{
							int newMapId;
							load.LoadCheckpoint(LevelCounter,newMapId);
							if(levels.maxCount <= newMapId || newMapId < 0)	newMapId = 0;
							levels.count = newMapId;
							load.LoadMap(map);
							load.LoadPlayer(player);
							load.Close();
							map.NewMap(levels.levels[newMapId]);
							enemies.PopulateEnemies(&map, &graphics);
							gameStates.NewState(GSGame);
							musicHandler.SetNewMusic(&sounds.forest);
							player.Reset(map.GetSpawnLocation(), false);
							Saver save;
							save.StartAndOpen();
							save.SaveCheckpoint(LevelCounter,levels.count);
							save.SaveMap(map);
							save.SavePlayer(player);
							save.EndAndClose("Save1.sav");
						}
						if (load.StartAndCheck("Save1.sav"))
						{
							int newMapId;
							load.LoadCheckpoint(LevelCounter,newMapId);
							if(levels.maxCount <= newMapId || newMapId < 0)	newMapId = 0;
							levels.count = newMapId;
							load.LoadMap(map);
							load.LoadPlayer(player);
							load.Close();
							map.NewMap(levels.levels[newMapId]);
							enemies.PopulateEnemies(&map, &graphics);
							gameStates.NewState(GSGame);
							musicHandler.SetNewMusic(&sounds.forest);
							player.Reset(map.GetSpawnLocation(), false);
						}
						setting.Finish();
					}else if (setting.GetResult() == MRNewGame)
					{
						gameStates.NewState(GSMenuMain);
						musicHandler.SetNewMusic(&sounds.titleScreen);
						setting.Finish();

					}
					
					musicHandler.Update();

					Timer = clock();
					map.DrawBackground(screen, &graphics);
					map.Draw(screen, LevelCounter);
					player.DrawHealthBar(screen, 1, 5, 5, 100, 20, &graphics.another);
					player.DrawInkBar(screen, 1, 5, 35, 100, 20, &graphics.another);
					inGameMenu.Open(screen, graphics.another, Point2D(0, 50));
					break;
				}

			case GSGame:
				if(gameStates.CurrentState() != GSMenuNewLevel && actionButtonPressed){
					if(map.NewMapEnabled(player.GetBoundR(), NewLevelID))
						gameStates.PushState(GSMenuNewLevel);
					actionButtonPressed=false;
				}
				player.Update(&map, screen.GetWidth(), screen.GetHeight(),sounds, Timer);
				enemies.Update(&map, &player,sounds, Timer);
				map.Update(player.GetBoundR(-map.GetMapPosition().X, -map.GetMapPosition().Y),player.InkPool);
				musicHandler.Update();
				Timer = clock();
				map.DrawBackground(screen, &graphics);
				map.Draw(screen, LevelCounter);
				enemies.Draw(screen, map.GetMapPosition());
				player.Draw(screen, map.GetMapPosition());
				player.DrawHealthBar(screen, 1, 5, 5, 100, 20, &graphics.another);
				player.DrawInkBar(screen, 1, 5, 35, 100, 20, &graphics.another);
				break;

			case GSMenuNewLevel:{
 				if(levels.count > LevelCounter) LevelCounter++;
				if(NewLevelID < 0) levels.count++;
				else if(NewLevelID >= levels.maxCount) levels.count = levels.maxCount-1;
				else levels.count = NewLevelID;

				map.NewMap(levels.levels[levels.count]);
				enemies.PopulateEnemies(&map, &graphics);
				player.Reset(map.GetSpawnLocation(), false);
				gameStates.BackState();
				sounds.bell.Play(false);
				Saver saver;
				saver.StartAndOpen();
				saver.SaveCheckpoint(LevelCounter,levels.count);
				saver.SaveMap(map);
				saver.SavePlayer(player);
				saver.EndAndClose("Save1.sav");
				break;
								}
			case GSGame_Over:
				musicHandler.Update();
				Timer = clock();
				gameOverMenu.Open(screen, graphics.another, Point2D(0, 50));
				if(setting.GetResult() != MRExitGame && setting.GetResult() != MRNone) {
					if(setting.GetResult() == MRMainMenu)
					{
						musicHandler.SetNewMusic(&sounds.titleScreen);
						sounds.forest.SetVolumeModifier(0.4f);
						gameStates.NewState(GSMenuMain);
					}
					else if(setting.GetResult() == MRNewGame){
						levels.count = 1;
						map.NewMap(levels.levels[0]);
						enemies.PopulateEnemies(&map, &graphics);
						player.Reset(map.GetSpawnLocation(), false);
						player.Health  =(float) 100;
						player.InvulnerableTime = 0;
						sounds.forest.SetVolumeModifier(0.4f);
						gameStates.NewState(GSGame);
					}
					setting.Finish();
				}
				break;
			}
			screen.UpdateWindow();
			fps.Delay();
		}
	}
	ClearSDL();
	return 0;
};
Ejemplo n.º 5
0
bool operator !=(Settings &s1, Settings &s2)
{
    return !s1.equals(s2);
}
Ejemplo n.º 6
0
void MediaWindow::on_settings()
{
    Settings *set = new Settings;
    set->show();
}
Ejemplo n.º 7
0
 void onDrawClouds(Atmosphere& atmosphere)
 {
     s_settings.apply(atmosphere);
 }
Ejemplo n.º 8
0
int main(int argc, char *argv[])
{
	Settings *settings = NULL;
	UDPTracker *usi = NULL;
	string config_file;
	int r;

#ifdef WIN32
	WSADATA wsadata;
	WSAStartup(MAKEWORD(2, 2), &wsadata);
#endif

	cout << "UDP Tracker (UDPT) " << VERSION << endl;
	cout << "Copyright 2012,2013 Naim Abda <*****@*****.**>\n\tReleased under the GPLv3 License." << endl;
	cout << "Build Date: " << __DATE__ << endl << endl;

	config_file = "udpt.conf";

	if (argc <= 1)
	{
		_print_usage ();
	}

	settings = new Settings (config_file);

	if (!settings->load())
	{
		const char strDATABASE[] = "database";
		const char strTRACKER[] = "tracker";
		const char strAPISRV [] = "apiserver";
		// set default settings:

		settings->set (strDATABASE, "driver", "sqlite3");
		settings->set (strDATABASE, "file", "tracker.db");

		settings->set (strTRACKER, "port", "6969");		// UDP PORT
		settings->set (strTRACKER, "threads", "5");
		settings->set (strTRACKER, "allow_remotes", "yes");
		settings->set (strTRACKER, "allow_iana_ips", "yes");
		settings->set (strTRACKER, "announce_interval", "1800");
		settings->set (strTRACKER, "cleanup_interval", "120");

		settings->set (strAPISRV, "enable", "1");
		settings->set (strAPISRV, "threads", "1");
		settings->set (strAPISRV, "port", "6969");	// TCP PORT

		settings->save();
		cerr << "Failed to read from '" << config_file.c_str() << "'. Using default settings." << endl;
	}

	usi = new UDPTracker (settings);

	HTTPServer *apiSrv = NULL;
	WebApp *wa = NULL;

	r = usi->start();
	if (r != UDPTracker::START_OK)
	{
		cerr << "Error While trying to start server." << endl;
		switch (r)
		{
		case UDPTracker::START_ESOCKET_FAILED:
			cerr << "Failed to create socket." << endl;
			break;
		case UDPTracker::START_EBIND_FAILED:
			cerr << "Failed to bind socket." << endl;
			break;
		default:
			cerr << "Unknown Error" << endl;
			break;
		}
		goto cleanup;
	}

	_doAPIStart(settings, &wa, &apiSrv, usi->conn);

	cout << "Press Any key to exit." << endl;

	cin.get();

cleanup:
	cout << endl << "Goodbye." << endl;

	delete usi;
	delete settings;
	delete apiSrv;
	delete wa;

#ifdef WIN32
	WSACleanup();
#endif

	return 0;
}
void SelectBackgroundColorDialog::updateLastUsedColors()
{
	XOJ_CHECK_TYPE(SelectBackgroundColorDialog);

	if (this->selected < 0)
	{
		return;
	}

	int lastUsedColors[MAX_LAST_USED_COLORS];

	for (int i = 0; i < MAX_LAST_USED_COLORS; i++)
	{
		lastUsedColors[i] = -1;
	}

	Settings* settings = control->getSettings();
	SElement& el = settings->getCustomElement("lastUsedPageBgColor");

	int count = 0;
	el.getInt("count", count);

	for (int i = 0; i < count && i < MAX_LAST_USED_COLORS; i++)
	{
		int color = -1;
		char* settingName = g_strdup_printf("color%02i", i);
		bool read = el.getInt(settingName, color);
		g_free(settingName);

		if (read)
		{
			lastUsedColors[i] = color;
		}
	}

	int lastUsedColorsNew[MAX_LAST_USED_COLORS];
	int id = 0;

	lastUsedColorsNew[id++] = this->selected;

	for (int i = 0; i < MAX_LAST_USED_COLORS && id < MAX_LAST_USED_COLORS; i++)
	{
		int c = lastUsedColors[i];
		if (c < 0)
		{
			continue;
		}
		// do we already have this color in the list?

		bool found = false;

		for (int x = 0; x < id; x++)
		{
			if (lastUsedColorsNew[x] == c)
			{
				found = true;
				break;
			}
		}
		if (found)
		{
			continue;
		}
		lastUsedColorsNew[id++] = c;
	}

	el.setInt("count", id);
	for (int i = 0; i < id; i++)
	{
		char* settingName = g_strdup_printf("color%02i", i);
		el.setIntHex(settingName, lastUsedColorsNew[i]);
		g_free(settingName);
	}

	settings->customSettingsChanged();
}
CanvasRenderingContext* HTMLCanvasElement::getContext(const String& type, CanvasContextAttributes* attrs)
{
    // A Canvas can either be "2D" or "webgl" but never both. If you request a 2D canvas and the existing
    // context is already 2D, just return that. If the existing context is WebGL, then destroy it
    // before creating a new 2D context. Vice versa when requesting a WebGL canvas. Requesting a
    // context with any other type string will destroy any existing context.

    // FIXME - The code depends on the context not going away once created, to prevent JS from
    // seeing a dangling pointer. So for now we will disallow the context from being changed
    // once it is created.
    if (type == "2d") {
        if (m_context && !m_context->is2d())
            return 0;
        if (!m_context) {
            bool usesDashbardCompatibilityMode = false;
#if ENABLE(DASHBOARD_SUPPORT)
            if (Settings* settings = document()->settings())
                usesDashbardCompatibilityMode = settings->usesDashboardBackwardCompatibilityMode();
#endif
            m_context = adoptPtr(new CanvasRenderingContext2D(this, document()->inQuirksMode(), usesDashbardCompatibilityMode));
#if USE(IOSURFACE_CANVAS_BACKING_STORE) || (ENABLE(ACCELERATED_2D_CANVAS) && USE(ACCELERATED_COMPOSITING)) || PLATFORM(ANDROID)
            if (m_context) {
                // Need to make sure a RenderLayer and compositing layer get created for the Canvas
                setNeedsStyleRecalc(SyntheticStyleChange);
            }
#endif
        }
        return m_context.get();
    }
#if ENABLE(WEBGL)
    Settings* settings = document()->settings();
    if (settings && settings->webGLEnabled()
#if !PLATFORM(CHROMIUM) && !PLATFORM(GTK)
        && settings->acceleratedCompositingEnabled()
#endif
        ) {
        // Accept the legacy "webkit-3d" name as well as the provisional "experimental-webgl" name.
        // Once ratified, we will also accept "webgl" as the context name.
        if ((type == "webkit-3d") ||
            (type == "experimental-webgl")) {
            if (m_context && !m_context->is3d())
                return 0;
            if (!m_context) {
                m_context = WebGLRenderingContext::create(this, static_cast<WebGLContextAttributes*>(attrs));
                if (m_context) {
                    // Need to make sure a RenderLayer and compositing layer get created for the Canvas
                    setNeedsStyleRecalc(SyntheticStyleChange);
#if PLATFORM(ANDROID)
                    document()->registerForDocumentActivationCallbacks(this);
                    document()->registerForDocumentSuspendCallbacks(this);
                    document()->setContainsWebGLContent(true);
#endif
                }
            }
            return m_context.get();
        }
    }
#else
    UNUSED_PARAM(attrs);
#endif
    return 0;
}
Ejemplo n.º 11
0
void CSSFontSelector::addFontFaceRule(const CSSFontFaceRule* fontFaceRule)
{
    // Obtain the font-family property and the src property.  Both must be defined.
    const CSSMutableStyleDeclaration* style = fontFaceRule->style();
    RefPtr<CSSValue> fontFamily = style->getPropertyCSSValue(CSSPropertyFontFamily);
    RefPtr<CSSValue> src = style->getPropertyCSSValue(CSSPropertySrc);
    RefPtr<CSSValue> unicodeRange = style->getPropertyCSSValue(CSSPropertyUnicodeRange);
    if (!fontFamily || !src || !fontFamily->isValueList() || !src->isValueList() || (unicodeRange && !unicodeRange->isValueList()))
        return;

    CSSValueList* familyList = static_cast<CSSValueList*>(fontFamily.get());
    if (!familyList->length())
        return;

    CSSValueList* srcList = static_cast<CSSValueList*>(src.get());
    if (!srcList->length())
        return;

    CSSValueList* rangeList = static_cast<CSSValueList*>(unicodeRange.get());

    unsigned traitsMask = 0;

    if (RefPtr<CSSValue> fontStyle = style->getPropertyCSSValue(CSSPropertyFontStyle)) {
        if (fontStyle->isPrimitiveValue()) {
            RefPtr<CSSValueList> list = CSSValueList::createCommaSeparated();
            list->append(fontStyle);
            fontStyle = list;
        } else if (!fontStyle->isValueList())
            return;

        CSSValueList* styleList = static_cast<CSSValueList*>(fontStyle.get());
        unsigned numStyles = styleList->length();
        if (!numStyles)
            return;

        for (unsigned i = 0; i < numStyles; ++i) {
            switch (static_cast<CSSPrimitiveValue*>(styleList->itemWithoutBoundsCheck(i))->getIdent()) {
                case CSSValueAll:
                    traitsMask |= FontStyleMask;
                    break;
                case CSSValueNormal:
                    traitsMask |= FontStyleNormalMask;
                    break;
                case CSSValueItalic:
                case CSSValueOblique:
                    traitsMask |= FontStyleItalicMask;
                    break;
                default:
                    break;
            }
        }
    } else
        traitsMask |= FontStyleMask;

    if (RefPtr<CSSValue> fontWeight = style->getPropertyCSSValue(CSSPropertyFontWeight)) {
        if (fontWeight->isPrimitiveValue()) {
            RefPtr<CSSValueList> list = CSSValueList::createCommaSeparated();
            list->append(fontWeight);
            fontWeight = list;
        } else if (!fontWeight->isValueList())
            return;

        CSSValueList* weightList = static_cast<CSSValueList*>(fontWeight.get());
        unsigned numWeights = weightList->length();
        if (!numWeights)
            return;

        for (unsigned i = 0; i < numWeights; ++i) {
            switch (static_cast<CSSPrimitiveValue*>(weightList->itemWithoutBoundsCheck(i))->getIdent()) {
                case CSSValueAll:
                    traitsMask |= FontWeightMask;
                    break;
                case CSSValueBolder:
                case CSSValueBold:
                case CSSValue700:
                    traitsMask |= FontWeight700Mask;
                    break;
                case CSSValueNormal:
                case CSSValue400:
                    traitsMask |= FontWeight400Mask;
                    break;
                case CSSValue900:
                    traitsMask |= FontWeight900Mask;
                    break;
                case CSSValue800:
                    traitsMask |= FontWeight800Mask;
                    break;
                case CSSValue600:
                    traitsMask |= FontWeight600Mask;
                    break;
                case CSSValue500:
                    traitsMask |= FontWeight500Mask;
                    break;
                case CSSValue300:
                    traitsMask |= FontWeight300Mask;
                    break;
                case CSSValueLighter:
                case CSSValue200:
                    traitsMask |= FontWeight200Mask;
                    break;
                case CSSValue100:
                    traitsMask |= FontWeight100Mask;
                    break;
                default:
                    break;
            }
        }
    } else
        traitsMask |= FontWeightMask;

    if (RefPtr<CSSValue> fontVariant = style->getPropertyCSSValue(CSSPropertyFontVariant)) {
        if (fontVariant->isPrimitiveValue()) {
            RefPtr<CSSValueList> list = CSSValueList::createCommaSeparated();
            list->append(fontVariant);
            fontVariant = list;
        } else if (!fontVariant->isValueList())
            return;

        CSSValueList* variantList = static_cast<CSSValueList*>(fontVariant.get());
        unsigned numVariants = variantList->length();
        if (!numVariants)
            return;

        for (unsigned i = 0; i < numVariants; ++i) {
            switch (static_cast<CSSPrimitiveValue*>(variantList->itemWithoutBoundsCheck(i))->getIdent()) {
                case CSSValueAll:
                    traitsMask |= FontVariantMask;
                    break;
                case CSSValueNormal:
                    traitsMask |= FontVariantNormalMask;
                    break;
                case CSSValueSmallCaps:
                    traitsMask |= FontVariantSmallCapsMask;
                    break;
                default:
                    break;
            }
        }
    } else
        traitsMask |= FontVariantMask;

    // Each item in the src property's list is a single CSSFontFaceSource. Put them all into a CSSFontFace.
    RefPtr<CSSFontFace> fontFace;

    int srcLength = srcList->length();

    bool foundSVGFont = false;

    for (int i = 0; i < srcLength; i++) {
        // An item in the list either specifies a string (local font name) or a URL (remote font to download).
        CSSFontFaceSrcValue* item = static_cast<CSSFontFaceSrcValue*>(srcList->itemWithoutBoundsCheck(i));
        CSSFontFaceSource* source = 0;

#if ENABLE(SVG_FONTS)
        foundSVGFont = item->isSVGFontFaceSrc() || item->svgFontFaceElement();
#endif
        if (!item->isLocal()) {
            Settings* settings = m_document ? m_document->frame() ? m_document->frame()->settings() : 0 : 0;
            bool allowDownloading = foundSVGFont || (settings && settings->downloadableBinaryFontsEnabled());
            if (allowDownloading && item->isSupportedFormat() && m_document) {
                CachedFont* cachedFont = m_document->cachedResourceLoader()->requestFont(item->resource());
                if (cachedFont) {
                    source = new CSSFontFaceSource(item->resource(), cachedFont);
#if ENABLE(SVG_FONTS)
                    if (foundSVGFont)
                        source->setHasExternalSVGFont(true);
#endif
                }
            }
        } else {
            source = new CSSFontFaceSource(item->resource());
        }

        if (!fontFace)
            fontFace = CSSFontFace::create(static_cast<FontTraitsMask>(traitsMask));

        if (source) {
#if ENABLE(SVG_FONTS)
            source->setSVGFontFaceElement(item->svgFontFaceElement());
#endif
            fontFace->addSource(source);
        }
    }

    ASSERT(fontFace);

    if (fontFace && !fontFace->isValid())
        return;

    if (rangeList) {
        unsigned numRanges = rangeList->length();
        for (unsigned i = 0; i < numRanges; i++) {
            CSSUnicodeRangeValue* range = static_cast<CSSUnicodeRangeValue*>(rangeList->itemWithoutBoundsCheck(i));
            fontFace->addRange(range->from(), range->to());
        }
    }

    // Hash under every single family name.
    int familyLength = familyList->length();
    for (int i = 0; i < familyLength; i++) {
        CSSPrimitiveValue* item = static_cast<CSSPrimitiveValue*>(familyList->itemWithoutBoundsCheck(i));
        String familyName;
        if (item->primitiveType() == CSSPrimitiveValue::CSS_STRING)
            familyName = static_cast<FontFamilyValue*>(item)->familyName();
        else if (item->primitiveType() == CSSPrimitiveValue::CSS_IDENT) {
            // We need to use the raw text for all the generic family types, since @font-face is a way of actually
            // defining what font to use for those types.
            String familyName;
            switch (item->getIdent()) {
                case CSSValueSerif:
                    familyName = "-webkit-serif";
                    break;
                case CSSValueSansSerif:
                    familyName = "-webkit-sans-serif";
                    break;
                case CSSValueCursive:
                    familyName = "-webkit-cursive";
                    break;
                case CSSValueFantasy:
                    familyName = "-webkit-fantasy";
                    break;
                case CSSValueMonospace:
                    familyName = "-webkit-monospace";
                    break;
                default:
                    break;
            }
        }

        if (familyName.isEmpty())
            continue;

        Vector<RefPtr<CSSFontFace> >* familyFontFaces = m_fontFaces.get(familyName);
        if (!familyFontFaces) {
            familyFontFaces = new Vector<RefPtr<CSSFontFace> >;
            m_fontFaces.set(familyName, familyFontFaces);

            ASSERT(!m_locallyInstalledFontFaces.contains(familyName));
            Vector<RefPtr<CSSFontFace> >* familyLocallyInstalledFaces;

            Vector<unsigned> locallyInstalledFontsTraitsMasks;
            fontCache()->getTraitsInFamily(familyName, locallyInstalledFontsTraitsMasks);
            unsigned numLocallyInstalledFaces = locallyInstalledFontsTraitsMasks.size();
            if (numLocallyInstalledFaces) {
                familyLocallyInstalledFaces = new Vector<RefPtr<CSSFontFace> >;
                m_locallyInstalledFontFaces.set(familyName, familyLocallyInstalledFaces);

                for (unsigned i = 0; i < numLocallyInstalledFaces; ++i) {
                    RefPtr<CSSFontFace> locallyInstalledFontFace = CSSFontFace::create(static_cast<FontTraitsMask>(locallyInstalledFontsTraitsMasks[i]), true);
                    locallyInstalledFontFace->addSource(new CSSFontFaceSource(familyName));
                    ASSERT(locallyInstalledFontFace->isValid());
                    familyLocallyInstalledFaces->append(locallyInstalledFontFace);
                }
            }
        }

        familyFontFaces->append(fontFace);
    }
}
Ejemplo n.º 12
0
AvatarUpdate::AvatarUpdate() : GenericThread(),  _lastAvatarUpdate(0) {
    setObjectName("Avatar Update"); // GenericThread::initialize uses this to set the thread name.
    Settings settings;
    const int DEFAULT_TARGET_AVATAR_SIMRATE = 60;
    _targetInterval = USECS_PER_SECOND / settings.value("AvatarUpdateTargetSimrate", DEFAULT_TARGET_AVATAR_SIMRATE).toInt();
}
Ejemplo n.º 13
0
void EncoderLame::loadSettings(){
	// Generate the command line arguments for the current settings
	args.clear();

	Settings *settings = Settings::self();


        // Should we bitswap? I'm unsure about the proper logic for this.
        // KDE3 always swapped on little-endian hosts,
        // while #171065 says we shouldn't always do so.
        // So... let's make it configurable, at least.

        bool swap = false;
        switch (settings->byte_swap()) {
        case Settings::EnumByte_swap::Yes:
            swap = true;
            break;
        case Settings::EnumByte_swap::No:
            swap = false;
            break;
        default:
#if Q_BYTE_ORDER == Q_LITTLE_ENDIAN
            swap = false; // it looks like lame is now clever enough to do the right thing by default? (#171065)
#else
            swap = false;
#endif
        }
        if (swap)
            args << "-x";

	int quality = settings->quality();
	if (quality < 0 ) quality = quality *-1;
	if (quality > 9) quality = 9;

	int method = settings->bitrate_constant() ? 0 : 1 ;

	if (method == 0) {
		// Constant Bitrate Encoding
		args.append("-b");
		args.append(QString("%1").arg(bitrates[settings->cbr_bitrate()]));
		d->bitrate = bitrates[settings->cbr_bitrate()];
		args.append("-q");
		args.append(QString("%1").arg(quality));
	}
	else {
		// Variable Bitrate Encoding
		if (settings->vbr_average_br()) {
			args.append("--abr");
			args.append(QString("%1").arg(bitrates[settings->vbr_mean_brate()]));
			d->bitrate = bitrates[settings->vbr_mean_brate()];
			if (settings->vbr_min_br()){
				args.append("-b");
				args.append(QString("%1").arg(bitrates[settings->vbr_min_brate()]));
			}
			if (settings->vbr_min_hard())
				args.append("-F");
			if (settings->vbr_max_br()){
				args.append("-B");
				args.append(QString("%1").arg(bitrates[settings->vbr_max_brate()]));
			}
		} else {
			d->bitrate = 128;
			args.append("-V");
			args.append(QString("%1").arg(quality));
		}
		if ( !settings->vbr_xing_tag() )
			args.append("-t");
	}

	args.append("-m");
	switch ( settings->stereo() ) {
		case 0:
			args.append("s");
			break;
		case 1:
			args.append("j");
			break;
		case 2:
			args.append("d");
			break;
		case 3:
			args.append("m");
			break;
		default:
			args.append("s");
			break;
	}

	if(settings->copyright())
		args.append("-c");
	if(!settings->original())
		args.append("-o");
	if(settings->iso())
		args.append("--strictly-enforce-ISO");
	if(settings->crc())
		args.append("-p");

	if ( settings->enable_lowpass() ) {
		args.append("--lowpass");
		args.append(QString("%1").arg(settings->lowfilterfreq()));

		if (settings->set_lpf_width()){
			args.append("--lowpass-width");
			args.append(QString("%1").arg(settings->lowfilterwidth()));
		}
	}

	if ( settings->enable_highpass()) {
		args.append("--hipass");
		args.append(QString("%1").arg(settings->highfilterfreq()));

		if (settings->set_hpf_width()){
			args.append("--hipass-width");
			args.append(QString("%1").arg(settings->highfilterwidth()));
		}
	}
}
Ejemplo n.º 14
0
void MenuCallbacks::killCam(MenuVItem* item)
{
	settings.setOption("MarkExecute", "killCam", item->getOptionValue());
	settings.save();
}
Ejemplo n.º 15
0
int main(int argc, char* argv[])
{
	// setup roothpaths
	BeFilesystem filesystem;
	Settings *settings = Settings::Instance();

	std::string home(filesystem.getHomedir());
	
	#if !defined(WIN32)
		filesystem.getRootPaths().push(home);
		
		// parse argv[0] for binary path
		char buf3[1024];
		readlink("/proc/self/exe", buf3, 1024);
		
		string path(buf3);
		size_t pos = path.find_last_of("/", path.size());
		std::stringstream buff;
		if ( pos != string::npos )
			buff << path.substr( 0, pos+1 );
		
		buff << "../share/critterding/";
		filesystem.getRootPaths().push( buff.str() );
// 		std::cout << "ROOTPATHS: " << buff.str() << std::endl;

	#else
		filesystem.getRootPaths().push(home);
		filesystem.getRootPaths().push( "critterding/" );
	#endif		
	
	// settings belonging to Critterding
	settings->registerCVar("threads",							new CVar(1, 1, 2147483647, false, "threads to use"));
	settings->registerCVar("startseed",							new CVar(0, 0, 2147483647, true, "startseed for random number generation"));
	
// 	4294967296
// 	2147483648
// 	1112992850
	
	settings->registerCVar("benchmark",							new CVar(0, 0, 1, true, "run the critterding benchmark"));
	settings->registerCVar("benchmark_frames",						new CVar(1000, 1, 2147483647, true, "length of benchmark in frames"));

	settings->registerCVar("race",								new CVar(0, 0, 1, false, "enable race simulation"));
	settings->registerCVar("roundworld",							new CVar(0, 0, 1, false, "enable round planet"));
// 	settings->registerCVar("concavefloor",							new CVar(0, 0, 1, false, "enable concave floor"));
// 	settings->registerCVar("testworld",							new CVar(0, 0, 1, false, "a world for test purposes"));

	settings->registerCVar("worldsizeX",							new CVar(250, 1, 2147483647, false, "size of the world along axis X"));
	settings->registerCVar("worldsizeY",							new CVar(140, 1, 2147483647, false, "size of the world along axis Y"));
// 	settings->registerCVar("worldsizeZ",							new CVar(100, 0, 2147483647, false, "height of hills using concave floor"));
	settings->registerCVar("worldwalls",							new CVar(1, 0, 1, false, "enable walls around the world"));

	settings->registerCVar("energy",							new CVar(1000, 0, 2147483647, false, "energy in the system by number of food cubes"));
	settings->registerCVar("mincritters",							new CVar(20, 0, 1000, false, "minimum number of critters"));

// 	settings->registerCVar("retinasperrow",							new CVar(119, 1, 1000, false, "number of vision retinas to stack per row onscreen"));
	settings->registerCVar("camerasensitivity_move",					new CVar(20, 1, 1000, false, "sensitivity of the camera when moving"));
	settings->registerCVar("camerasensitivity_look",					new CVar(20, 1, 1000, false, "sensitivity of the camera when looking around"));

	settings->registerCVar("colormode",							new CVar(0, 0, 1, true, "colors genetically exact critters identically"));
	settings->registerCVar("exit_if_empty",							new CVar(0, 0, 1, true, "exit simulation if there are no critters"));
	settings->registerCVar("autoload",							new CVar(0, 0, 1, true, "autoload critters from ~/.critterding/load"));
	settings->registerCVar("autoloadlastsaved",						new CVar(0, 0, 1, true, "autoload critters from ~/.critterding/lastsaved"));

	settings->registerCVar("critter_insertevery",						new CVar(0, 0, 2147483647, false, "inserts a random critter every n frames"));
	settings->registerCVar("critter_maxlifetime",						new CVar(32000, 1, 2147483647, false, "maximum number of frames a critter lives"));
	settings->registerCVar("critter_maxenergy",						new CVar(5000, 1, 2147483647, false, "maximum amount of energy a critter has"));

	settings->registerCVar("critter_startenergy",						new CVar(3000, 1, 2147483647, false, "energy a new critter (adam) starts with"));
	settings->registerCVar("critter_procinterval",						new CVar(500, 1, 2147483647, false, "minimum frames between procreations"));
	settings->registerCVar("critter_minenergyproc",						new CVar(3000, 1, 2147483647, false, "energy a critters needs to procreate"));
	settings->registerCVar("critter_sightrange",						new CVar(100, 1, 2147483647, false, "distance a critter can see (10 = 1 worldsize)"));

	settings->registerCVar("critter_retinasize",						new CVar(16, 1, 1000, false, "size of a critters eye retina"));
	settings->registerCVar("critter_autosaveinterval",					new CVar(0, 0, 2147483647, false, "save critters every n seconds"));
	settings->registerCVar("critter_autoexchangeinterval",					new CVar(0, 0, 2147483647, false, "save critters every n seconds"));
	settings->registerCVar("critter_enableomnivores",					new CVar(0, 0, 1, true, "enables critters to eat each other"));
	settings->registerCVar("critter_raycastvision",						new CVar(0, 0, 1, true, "use raycast vision instead of opengl"));
	
	settings->registerCVar("food_maxlifetime",						new CVar(32000, 1, 2147483647, false, "maximum number of frames a food unit exists"));
	settings->registerCVar("food_maxenergy",						new CVar(1500, 1, 2147483647, false, "maximum amount of energy a food unit has"));
	settings->registerCVar("food_size",								new CVar(100, 1, 2147483647, false, "size of a food unit"));

	settings->registerCVar("body_maxmutations",						new CVar(5, 1, 2147483647, false, "maximum mutations on a body mutant"));
	settings->registerCVar("body_mutationrate",						new CVar(100, 0, 1000, false, "rate of body mutation (permille)"));

	settings->registerCVar("body_minbodyparts",						new CVar(2, 0, 2147483647, false, "minimum body parts per critter"));
	settings->registerCVar("body_maxbodyparts",						new CVar(30, 0, 2147483647, false, "maximum body parts per critter"));
	settings->registerCVar("body_minbodypartsatbuildtime",					new CVar(4, 1, 2147483647, false, "minimum body parts for a new critter"));
	settings->registerCVar("body_maxbodypartsatbuildtime",					new CVar(8, 1, 2147483647, false, "maximum body parts for a new critter"));
	
	settings->registerCVar("body_maxconstraintangle",					new CVar(31416, 0, 2147483647, false, "maximum amount of rotation on a contraint"));
	settings->registerCVar("body_maxconstraintlimit",					new CVar(7853, 0, 2147483647, false, "maximum limit of a contraint"));
	
	settings->registerCVar("body_minbodypartsize",						new CVar(10, 1, 2147483647, false, "minimum size of a critters body part"));
	settings->registerCVar("body_maxbodypartsize",						new CVar(100, 1, 2147483647, false, "maximum size of a critters body part"));
	settings->registerCVar("body_minheadsize",						new CVar(5, 1, 2147483647, false, "minimum size of a critters head"));
	settings->registerCVar("body_maxheadsize",						new CVar(50, 1, 2147483647, false, "maximum size of a critters head"));

	settings->registerCVar("body_percentmutateeffectchangecolor",						new CVar(2, 0, 100, false, "chance of changing body color"));
	settings->registerCVar("body_percentmutateeffectchangecolor_slightly",				new CVar(5, 0, 100, false, "chance of changing body color"));
	settings->registerCVar("body_percentmutateeffectaddbodypart",						new CVar(2, 0, 100, false, "chance of adding a body part"));
	settings->registerCVar("body_percentmutateeffectremovebodypart",					new CVar(2, 0, 100, false, "chance of removing a body part"));
	settings->registerCVar("body_percentmutateeffectresizebodypart",					new CVar(2, 0, 100, false, "chance of resizing a body part"));
	settings->registerCVar("body_percentmutateeffectresizebodypart_slightly",			new CVar(5, 0, 100, false, "chance of slightly resizing a body part"));
	settings->registerCVar("body_percentmutateeffectchangeconstraintlimits",			new CVar(2, 0, 100, false, "chance of changing a joints motion limits"));
	settings->registerCVar("body_percentmutateeffectchangeconstraintlimits_slightly",	new CVar(5, 0, 100, false, "chance of slightly changing a joints motion limits"));
	settings->registerCVar("body_percentmutateeffectchangeconstraintangles",			new CVar(2, 0, 100, false, "chance of changing a joints position angles"));
	settings->registerCVar("body_percentmutateeffectchangeconstraintangles_slightly",	new CVar(5, 0, 100, false, "chance of changing a joints position angles"));
	settings->registerCVar("body_percentmutateeffectchangeconstraintposition",			new CVar(2, 0, 100, false, "chance of changing a joints position"));
	settings->registerCVar("body_percentmutateeffectchangeconstraintposition_slightly",	new CVar(0, 0, 100, false, "chance of slightly changing a joints position"));
	settings->registerCVar("body_percentmutateeffectresizehead",						new CVar(2, 0, 100, false, "chance of resizing a head"));
	settings->registerCVar("body_percentmutateeffectresizehead_slightly",				new CVar(5, 0, 100, false, "chance of slightly resizing a head"));
	settings->registerCVar("body_percentmutateeffectrepositionhead",					new CVar(5, 0, 100, false, "chance of repositioning head"));


// 	settings->registerCVar("body_percentmutateeffectchangecolor",						new CVar(0, 0, 100, false, "chance of changing body color"));
// 	settings->registerCVar("body_percentmutateeffectchangecolor_slightly",				new CVar(0, 0, 100, false, "chance of changing body color"));
// 	settings->registerCVar("body_percentmutateeffectaddbodypart",						new CVar(0, 0, 100, false, "chance of adding a body part"));
// 	settings->registerCVar("body_percentmutateeffectremovebodypart",					new CVar(0, 0, 100, false, "chance of removing a body part"));
// 	settings->registerCVar("body_percentmutateeffectresizebodypart",					new CVar(0, 0, 100, false, "chance of resizing a body part"));
// 	settings->registerCVar("body_percentmutateeffectresizebodypart_slightly",			new CVar(0, 0, 100, false, "chance of slightly resizing a body part"));
// 	settings->registerCVar("body_percentmutateeffectchangeconstraintlimits",			new CVar(0, 0, 100, false, "chance of changing a joints motion limits"));
// 	settings->registerCVar("body_percentmutateeffectchangeconstraintlimits_slightly",	new CVar(0, 0, 100, false, "chance of slightly changing a joints motion limits"));
// 	settings->registerCVar("body_percentmutateeffectchangeconstraintangles",			new CVar(0, 0, 100, false, "chance of changing a joints position angles"));
// 	settings->registerCVar("body_percentmutateeffectchangeconstraintangles_slightly",	new CVar(0, 0, 100, false, "chance of changing a joints position angles"));
// 	settings->registerCVar("body_percentmutateeffectchangeconstraintposition",			new CVar(1, 0, 100, false, "chance of changing a joints position"));
// 	settings->registerCVar("body_percentmutateeffectchangeconstraintposition_slightly",	new CVar(1, 0, 100, false, "chance of slightly changing a joints position"));
// 	settings->registerCVar("body_percentmutateeffectresizehead",						new CVar(0, 0, 100, false, "chance of resizing a head"));
// 	settings->registerCVar("body_percentmutateeffectresizehead_slightly",				new CVar(0, 0, 100, false, "chance of slightly resizing a head"));
// 	settings->registerCVar("body_percentmutateeffectrepositionhead",					new CVar(0, 0, 100, false, "chance of repositioning head"));
	
	settings->registerCVar("body_selfcollisions",						new CVar(0, 0, 1, true, "critters can exploit physics glitches"));

	settings->registerCVar("body_costhavingbodypart",					new CVar(10, 0, 2147483647, false, "cost of having a bodypart (1/100000 energy)"));
	settings->registerCVar("body_costtotalweight",						new CVar(10, 0, 2147483647, false, "cost multiplier of total body weight (1/100000 energy)"));
	
	
	settings->registerCVar("brain_maxmutations",						new CVar(10, 1, 2147483647, false, "maximum mutations on a brain mutant"));
	settings->registerCVar("brain_mutationrate",						new CVar(120, 0, 1000, false, "rate of brain mutation (permille)"));

	settings->registerCVar("brain_maxneurons",						new CVar(1000, 1, 2147483647, false, "maximum neurons per critter"));
	settings->registerCVar("brain_minsynapses",						new CVar(1, 1, 2147483647, false, "minimum synapses per neuron"));
	settings->registerCVar("brain_maxsynapses",						new CVar(1000, 1, 2147483647, false, "maximum synapses per neuron"));
	settings->registerCVar("brain_minneuronsatbuildtime",					new CVar(10, 1, 2147483647, false, "minimum neurons for a new critter"));
	settings->registerCVar("brain_maxneuronsatbuildtime",					new CVar(300, 1, 2147483647, false, "maximum neurons for a new critter"));

	settings->registerCVar("brain_minsynapsesatbuildtime",					new CVar(10, 1, 2147483647, false, "minimum synapses for a new neuron"));
	settings->registerCVar("brain_maxsynapsesatbuildtime",					new CVar(200, 1, 2147483647, false, "maximum synapses for a new neuron of a new critter"));

	settings->registerCVar("brain_percentchanceinhibitoryneuron",				new CVar(50, 0, 100, false, "percent chance a neuron is inhibotory"));
	settings->registerCVar("brain_mutate_percentchanceinhibitoryneuron",				new CVar(0, 0, 1, true, "mutate this value"));

	settings->registerCVar("brain_percentchancemotorneuron",				new CVar(100, 0, 100, false, "percent chance a neuron is a motor neuron"));
	settings->registerCVar("brain_mutate_percentchancemotorneuron",					new CVar(0, 0, 1, true, "mutate this value"));

	settings->registerCVar("brain_percentchanceplasticneuron",				new CVar(20, 0, 100, false, "percent chance a neuron has plastic synapses"));
	settings->registerCVar("brain_mutate_percentchanceplasticneuron",				new CVar(0, 0, 1, true, "mutate this value"));

	settings->registerCVar("brain_minplasticitystrengthen",					new CVar(100, 1, 2147483647, false, "minimum weight by which plastic synapses strengthen"));
	settings->registerCVar("brain_maxplasticitystrengthen",					new CVar(1000, 1, 2147483647, false, "maximum weight by which plastic synapses strengthen"));
	settings->registerCVar("brain_minplasticityweaken",					new CVar(1000, 1, 2147483647, false, "minimum weight by which plastic synapses weaken"));
	settings->registerCVar("brain_maxplasticityweaken",					new CVar(10000, 1, 2147483647, false, "maximum weight by which plastic synapses weaken"));
	settings->registerCVar("brain_mutate_plasticityfactors",					new CVar(0, 0, 1, true, "mutate min/max plasticity values"));

	settings->registerCVar("brain_minfiringthreshold",					new CVar(2, 1, 2147483647, false, "minimum firingthreshold of a neuron"));
	settings->registerCVar("brain_mutate_minfiringthreshold",					new CVar(0, 0, 1, true, "mutate this value"));

	settings->registerCVar("brain_maxfiringthreshold",					new CVar(12, 1, 2147483647, false, "maximum firingthreshold of a neuron"));
	settings->registerCVar("brain_mutate_maxfiringthreshold",					new CVar(0, 0, 1, true, "mutate this value"));

	settings->registerCVar("brain_percentchanceconsistentsynapses",				new CVar(0, 0, 100, false, "percent chance a neurons synapses are all inhibitory or excitatory"));
	settings->registerCVar("brain_mutate_percentchanceconsistentsynapses",				new CVar(0, 0, 1, true, "mutate this value"));

	settings->registerCVar("brain_percentchanceinhibitorysynapses",				new CVar(50, 0, 100, false, "percent chance a synapse is inhibitory"));
	settings->registerCVar("brain_mutate_percentchanceinhibitorysynapses",				new CVar(0, 0, 1, true, "mutate this value"));

	settings->registerCVar("brain_percentchancesensorysynapse",				new CVar(20, 0, 100, false, "percent change a synapse connects to an input"));
	settings->registerCVar("brain_mutate_percentchancesensorysynapse",				new CVar(0, 0, 1, true, "mutate this value"));

	settings->registerCVar("brain_percentmutateeffectaddneuron",				new CVar(1, 0, 100, false, "chance of adding a neuron"));
	settings->registerCVar("brain_percentmutateeffectremoveneuron",				new CVar(1, 0, 100, false, "chance of removing a neuron"));
	settings->registerCVar("brain_percentmutateeffectalterneuron",				new CVar(2, 0, 100, false, "chance of altering a neuron"));
	settings->registerCVar("brain_percentmutateeffectaddsynapse",				new CVar(5, 0, 100, false, "chance of adding a synapse"));
	settings->registerCVar("brain_percentmutateeffectremovesynapse",			new CVar(6, 0, 100, false, "chance of removing a synapse"));
	settings->registerCVar("brain_mutate_mutateeffects",						new CVar(0, 0, 1, true, "mutate mutation effects"));

	settings->registerCVar("brain_percentmutateeffectaltermutable",				new CVar(1, 0, 100, false,"mutate value of a mutatable option"));

	settings->registerCVar("brain_costhavingneuron",					new CVar(8, 0, 2147483647, false, "cost of having a neuron (1/100000 energy)"));
	settings->registerCVar("brain_costfiringneuron",					new CVar(2, 0, 2147483647, false, "cost of firing a neuron"));
	settings->registerCVar("brain_costfiringmotorneuron",					new CVar(300, 0, 2147483647, false, "cost of firing a motor neuron"));
	settings->registerCVar("brain_costhavingsynapse",					new CVar(1, 0, 2147483647, false, "cost of having a synapse"));

	
	settings->registerCVar("population_eliminate_portion",						new CVar(180, 2, 2147483647, false, "eliminate a percentage of critters if population reaches n"));
	settings->registerCVar("population_eliminate_portion_percent",					new CVar(50, 1, 100, false, "eliminate n% of critters if population reaches population_eliminate_portion"));
	settings->registerCVar("population_eliminate_portion_decrenergy",					new CVar(5, 0, 100, false, "decrease energy by n when killhalfat triggers"));
	settings->registerCVar("population_eliminate_portion_incrworldsizeX",					new CVar(0, 0, 100, false, "increase worldsizeX by n when killhalfat triggers"));
	settings->registerCVar("population_eliminate_portion_incrworldsizeY",					new CVar(0, 0, 100, false, "increase worldsizeY by n when killhalfat triggers"));
	settings->registerCVar("population_eliminate_portion_decrmaxlifetimepct",					new CVar(0, 0, 100, false, "decrease critter_maxlifetime by n when killhalfat triggers"));

	settings->registerCVar("population_eliminate_portion_brainmutationratechange",				new CVar(0, 0, 1, true, "change mutationrate of brain between min and max"));
	settings->registerCVar("population_eliminate_portion_brainmutationratemin",					new CVar(0, 0, 100, false, "minimum mutationrate of body"));
	settings->registerCVar("population_eliminate_portion_brainmutationratemax",					new CVar(0, 0, 100, false, "maximum mutationrate of body"));
	settings->registerCVar("population_eliminate_portion_bodymutationratechange",				new CVar(0, 0, 1, true, "change mutationrate of brain between min and max"));
	settings->registerCVar("population_eliminate_portion_bodymutationratemin",					new CVar(0, 0, 100, false, "minimum mutationrate of brain"));
	settings->registerCVar("population_eliminate_portion_bodymutationratemax",					new CVar(0, 0, 100, false, "maximum mutationrate of brain"));
	
	
	settings->registerCVar("population_limit_energy",							new CVar(120, 0, 2147483647, false, "population limit"));
	settings->registerCVar("population_limit_energy_percent",		new CVar(50, 0, 100, false, "if population limit is exceeded drop energy to percentage"));

	settings->registerCVar("population_double",						new CVar(0, 0, 2147483647, false, "duplicate all critters if population reaches n"));
	
	settings->checkCommandLineOptions(argc,argv );
	
	// MAIN LOOP
	Evolution evolution(filesystem);
	evolution.run();
	return 0;

}
SelectBackgroundColorDialog::SelectBackgroundColorDialog(GladeSearchpath* gladeSearchPath, Control* control) :
		GladeGui(gladeSearchPath, "page-background-color.glade", "pageBgColorDialog")
{

	XOJ_INIT_TYPE(SelectBackgroundColorDialog);

	this->control = control;
	this->selected = -1;
	this->colorDlg = NULL;

	ColorEntry* e = new ColorEntry(this, -1, true);
	this->colors.push_back(e);

	int predef_bgcolors_rgba[] = { 0xffffff, 0xa0e8ff, 0x80ffc0, 0xffc0d4, 0xffc080, 0xffff80 };

	GtkWidget* toolbar = get("tbPredefinedColors");

	for (int color : predef_bgcolors_rgba)
	{
		ColorEntry* e = new ColorEntry(this, color, false);
		this->colors.push_back(e);

		GtkWidget* iconWidget = selectcolor_new(color);
		selectcolor_set_size(iconWidget, 32);
		selectcolor_set_circle(iconWidget, true);
		GtkToolItem* it = gtk_tool_button_new(iconWidget, "");
		gtk_toolbar_insert(GTK_TOOLBAR(toolbar), GTK_TOOL_ITEM(it), -1);
		g_signal_connect(it, "clicked", G_CALLBACK(&buttonSelectedCallback), e);
	}

	gtk_widget_show_all(toolbar);

	toolbar = get("tbLastUsedColors");

	Settings* settings = control->getSettings();
	SElement& el = settings->getCustomElement("lastUsedPageBgColor");

	int count = 0;
	el.getInt("count", count);

	for (int i = 0; i < count; i++)
	{
		int color = -1;
		char* settingName = g_strdup_printf("color%02i", i);
		bool read = el.getInt(settingName, color);
		g_free(settingName);

		if (!read)
		{
			continue;
		}

		ColorEntry* e = new ColorEntry(this, color, true);
		this->colors.push_back(e);

		GtkWidget* iconWidget = selectcolor_new(color);
		selectcolor_set_size(iconWidget, 32);
		selectcolor_set_circle(iconWidget, true);
		GtkToolItem* it = gtk_tool_button_new(iconWidget, "");
		gtk_toolbar_insert(GTK_TOOLBAR(toolbar), GTK_TOOL_ITEM(it), -1);
		g_signal_connect(it, "clicked", G_CALLBACK(&buttonSelectedCallback), e);
	}
	gtk_widget_show_all(toolbar);

	if (count == 0)
	{
		// no colors => not title
		GtkWidget* w = get("lbLastUsed");
		gtk_widget_hide(w);
	}

	g_signal_connect(get("cbSelect"), "clicked", G_CALLBACK(&buttonCustomCallback), this);
}
Ejemplo n.º 17
0
Page* InspectorOverlay::overlayPage()
{
    if (m_overlayPage)
        return m_overlayPage.get();

    static FrameLoaderClient* dummyFrameLoaderClient =  new EmptyFrameLoaderClient;
    Page::PageClients pageClients;
    fillWithEmptyClients(pageClients);
    m_overlayPage = adoptPtr(new Page(pageClients));

    Settings* settings = m_page->settings();
    Settings* overlaySettings = m_overlayPage->settings();

    overlaySettings->setStandardFontFamily(settings->standardFontFamily());
    overlaySettings->setSerifFontFamily(settings->serifFontFamily());
    overlaySettings->setSansSerifFontFamily(settings->sansSerifFontFamily());
    overlaySettings->setCursiveFontFamily(settings->cursiveFontFamily());
    overlaySettings->setFantasyFontFamily(settings->fantasyFontFamily());
    overlaySettings->setPictographFontFamily(settings->pictographFontFamily());
    overlaySettings->setMinimumFontSize(settings->minimumFontSize());
    overlaySettings->setMinimumLogicalFontSize(settings->minimumLogicalFontSize());
    overlaySettings->setMediaEnabled(false);
    overlaySettings->setScriptEnabled(true);
    overlaySettings->setPluginsEnabled(false);

    RefPtr<Frame> frame = Frame::create(m_overlayPage.get(), 0, dummyFrameLoaderClient);
    frame->setView(FrameView::create(frame.get()));
    frame->init();
    FrameLoader* loader = frame->loader();
    frame->view()->setCanHaveScrollbars(false);
    frame->view()->setTransparent(true);
    ASSERT(loader->activeDocumentLoader());
    loader->activeDocumentLoader()->writer()->setMIMEType("text/html");
    loader->activeDocumentLoader()->writer()->begin();
    loader->activeDocumentLoader()->writer()->addData(reinterpret_cast<const char*>(InspectorOverlayPage_html), sizeof(InspectorOverlayPage_html));
    loader->activeDocumentLoader()->writer()->end();

#if OS(WINDOWS)
    evaluateInOverlay("setPlatform", "windows");
#elif OS(MAC_OS_X)
    evaluateInOverlay("setPlatform", "mac");
#elif OS(UNIX)
    evaluateInOverlay("setPlatform", "linux");
#endif

    return m_overlayPage.get();
}
bool ScriptController::isEnabled()
{
    Settings* settings = m_frame->settings();
    return (settings && settings->isJavaScriptEnabled());
}
Ejemplo n.º 19
0
MainWindow::MainWindow( const QStringList &_params )
:	QWidget()
,	cardsGroup( new QActionGroup( this ) )
,	quitOnClose( false )
{
	setAttribute( Qt::WA_DeleteOnClose, true );
	setupUi( this );

	cards->hide();
	cards->hack();
	languages->hack();

	setWindowFlags( Qt::Window | Qt::CustomizeWindowHint | Qt::WindowMinimizeButtonHint );
#if QT_VERSION >= 0x040500
	setWindowFlags( windowFlags() | Qt::WindowCloseButtonHint );
#else
	setWindowFlags( windowFlags() | Qt::WindowSystemMenuHint );
#endif

	Settings s;
	// Mobile
	infoMobileCode->setValidator( new IKValidator( infoMobileCode ) );
	infoMobileCode->setText( s.value( "Client/MobileCode" ).toString() );
	infoMobileCell->setText( s.value( "Client/MobileNumber", "+372" ).toString() );
	connect( infoMobileCode, SIGNAL(textEdited(QString)), SLOT(enableSign()) );
	connect( infoMobileCell, SIGNAL(textEdited(QString)), SLOT(enableSign()) );
	connect( infoSignMobile, SIGNAL(toggled(bool)), SLOT(showCardStatus()) );

	// Buttons
	QButtonGroup *buttonGroup = new QButtonGroup( this );

	buttonGroup->addButton( settings, HeadSettings );
	buttonGroup->addButton( help, HeadHelp );
	buttonGroup->addButton( about, HeadAbout );

	buttonGroup->addButton( homeSign, HomeSign );
	buttonGroup->addButton( homeView, HomeView );
	buttonGroup->addButton( homeCrypt, HomeCrypt );

	introNext = introButtons->addButton( tr( "Next" ), QDialogButtonBox::ActionRole );
	buttonGroup->addButton( introNext, IntroNext );
	buttonGroup->addButton( introButtons->button( QDialogButtonBox::Cancel ), IntroBack );

	signButton = signButtons->addButton( tr("Sign"), QDialogButtonBox::AcceptRole );
	buttonGroup->addButton( signButton, SignSign );
	buttonGroup->addButton( signButtons->button( QDialogButtonBox::Cancel ), SignCancel );

	viewAddSignature = viewButtons->addButton( tr("Add signature"), QDialogButtonBox::ActionRole );
	buttonGroup->addButton( viewAddSignature, ViewAddSignature );
	buttonGroup->addButton( viewButtons->button( QDialogButtonBox::Close ), ViewClose );
	connect( buttonGroup, SIGNAL(buttonClicked(int)),
		SLOT(buttonClicked(int)) );

	connect( infoCard, SIGNAL(linkActivated(QString)), SLOT(parseLink(QString)) );
	connect( cards, SIGNAL(activated(QString)), qApp->signer(), SLOT(selectCard(QString)), Qt::QueuedConnection );
	connect( qApp, SIGNAL(dataChanged()), SLOT(showCardStatus()) );

	// Digidoc
	doc = new DigiDoc( this );

	// Translations
	lang << "et" << "en" << "ru";
	QString deflang;
	switch( QLocale().language() )
	{
	case QLocale::English: deflang = "en"; break;
	case QLocale::Russian: deflang = "ru"; break;
	case QLocale::Estonian:
	default: deflang = "et"; break;
	}
	on_languages_activated( lang.indexOf(
		s.value( "Main/Language", deflang ).toString() ) );
	QActionGroup *langGroup = new QActionGroup( this );
	QAction *etAction = langGroup->addAction( new QAction( langGroup ) );
	QAction *enAction = langGroup->addAction( new QAction( langGroup ) );
	QAction *ruAction = langGroup->addAction( new QAction( langGroup ) );
	etAction->setData( 0 );
	enAction->setData( 1 );
	ruAction->setData( 2 );
	etAction->setShortcut( Qt::CTRL + Qt::SHIFT + Qt::Key_1 );
	enAction->setShortcut( Qt::CTRL + Qt::SHIFT + Qt::Key_2 );
	ruAction->setShortcut( Qt::CTRL + Qt::SHIFT + Qt::Key_3 );
	addAction( etAction );
	addAction( enAction );
	addAction( ruAction );
	connect( langGroup, SIGNAL(triggered(QAction*)), SLOT(changeLang(QAction*)) );
	connect( cardsGroup, SIGNAL(triggered(QAction*)), SLOT(changeCard(QAction*)) );

	// Views
	signContentView->setColumnHidden( 2, true );
	viewContentView->setColumnHidden( 3, true );
	connect( signContentView, SIGNAL(remove(unsigned int)),
		SLOT(removeDocument(unsigned int)) );
	connect( viewContentView, SIGNAL(remove(unsigned int)),
		SLOT(removeDocument(unsigned int)) );

	if( !_params.empty() )
	{
		quitOnClose = true;
		params = _params;
		buttonClicked( HomeSign );
	}
}
Ejemplo n.º 20
0
void RootLayerScrollsFrameSettingOverride(Settings& settings)
{
    settings.setRootLayerScrolls(true);
}
Ejemplo n.º 21
0
Arena::Arena(je::Game *game, const Settings& settings)
	:je::Level(game, 640, 480)
	,settings(settings)
	,scores(std::bind(&Arena::updateScores, this))
{
	const int groundHeight = getHeight() - 128;
	int yoffset = 0;
	for (int i = 0; i < getWidth(); i += 32)
	{
		yoffset += je::random(8) - 4;
		if (yoffset > 8)
			yoffset = 8;
		if (yoffset < -12)
			yoffset = -12;
		for (int j = groundHeight + yoffset; j < getHeight(); j += 32)
		{
			SolidGround *ground = new SolidGround(this, i, j, sf::Rect<int>(i, j, 32, 32), "dirt.png");
			ground->setDepth(-10);
			this->addEntity(ground);
		}
		Scenery *grass = new Scenery(this, i, groundHeight - 6 + yoffset, (rand() % 2 ? "grass0.png" : "grass1.png"));
		grass->setDepth(-11);
		this->addEntity(grass);
	}

	Scenery *beam = new Scenery(this, 32 + 16, groundHeight - 32, "beam.png");
	beam->setDepth(1);
	this->addEntity(beam);
	beam = new Scenery(this, 164 + 16 + 4, groundHeight - 32, "beam.png");
	beam->setDepth(1);
	addEntity(beam);
	for (int i = 32; i < 164; i += 32)
	{
		addEntity(new JumpThroughPlatform(this, sf::Vector2f(i, groundHeight - 32)));
	}
	addEntity(new JumpThroughPlatform(this, sf::Vector2f(0, groundHeight - 88)));
	addEntity(new JumpThroughPlatform(this, sf::Vector2f(32, groundHeight - 88)));
	for (int i = 128; i < 256; i += 32)
	{
		addEntity(new JumpThroughPlatform(this, sf::Vector2f(i - 16, groundHeight - 128)));
	}

	int gapSize = getWidth() / (settings.getNumberOfPlayers() + 1);
	for (int i = 0; i < settings.getNumberOfPlayers(); ++i)
	{
		Player *player = new Player(this, (i + 1) * gapSize, getHeight() / 2, settings.getPlayerConfig(i), scores);
		scores.registerPlayer(player->getConfig());
		this->addEntity(player);
	}

	//	set up background gradient
	bgVertices[0].color = bgVertices[1].color = sf::Color(11, 26, 34);
	bgVertices[2].color = bgVertices[3].color = sf::Color(40, 90, 116);
	bgVertices[0].position = sf::Vector2f(0, 0);
	bgVertices[1].position = sf::Vector2f(getWidth(), 0);
	bgVertices[2].position = sf::Vector2f(getWidth(), getHeight());
	bgVertices[3].position = sf::Vector2f(0, getHeight());
	//	GAME JAM THEME: CASTLE
	Scenery *castle = new Scenery(this, getWidth() / 2 - (192/2), groundHeight -128, "castle.png");
	castle->setDepth(100);//in the distance (WHICH IS WHY IT'S SMALL!!!)
	this->addEntity(castle);

	//	forest time!
	const bool netbook = true;
	if (netbook)
	{
		Scenery *forest = new Scenery(this, 0, 116, "bamboo_nolag.png");
		forest->setDepth(9001);
		addEntity(forest);

	}
	else
	{
		const float totalDensity = 0.85f;
		const float sideDensity = totalDensity / 4.f;
		const float backDensity = totalDensity - sideDensity;
		const int frontForestWidth = 164;
		//	add background forest
		addEntity(new BambooForest(this, sf::Vector2f(0, groundHeight), this->getWidth(), totalDensity));
		//	and one to make up for the frontal side forests (to keep uniform tree density across map)
		addEntity(new BambooForest(this, sf::Vector2f(frontForestWidth, groundHeight), this->getWidth() - frontForestWidth * 2, sideDensity));

		//	and the two frontal forests
		BambooForest *frontForest = new BambooForest(this, sf::Vector2f(0, groundHeight), frontForestWidth, sideDensity);
		frontForest->setDepth(-9);	//	behind grass and land, in front of rest
		this->addEntity(frontForest);
		frontForest = new BambooForest(this, sf::Vector2f(getWidth() - frontForestWidth, groundHeight), frontForestWidth, sideDensity);
		frontForest->setDepth(-9);	//	behind grass and land, in front of rest
		this->addEntity(frontForest);
	}

	//	init all score text crap (jesus christ max why would you recreate this every frame?)
	if (!font.loadFromFile ("resources/DOMOAN__.ttf"))
		std::cerr << "bad font file";
	scoreTexts.resize(settings.getNumberOfPlayers(), sf::Text()); 
	for (sf::Text& scoreText : scoreTexts)
	{
		scoreText.setFont(font);
		scoreText.setCharacterSize(20);
		scoreText.setColor(sf::Color::White);
	}

	//	make sure players are updated before heads and bones (or else the heads lag behind)
	this->setSpecificOrderEntitiesPre({"Player"});



	this->updateScores();

	//for (int i = 0; i < 1; ++i)
	//{
	//	addEntity(new PolyTest(
	//		this,
	//		sf::Vector2f(200, 100),
	//		std::unique_ptr<je::DetailedMask>(
	//			new je::PolygonMask({
	//					sf::Vector2f(-32, 24),
	//					sf::Vector2f(32, 24),
	//					sf::Vector2f(0, -24)
	//				})
	//		)
	//	));
	//}
}
Ejemplo n.º 22
0
void Database::prepareDatabase()
{
  {
    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE", "initialization");
    db.setDatabaseName(mainApp->dbFileName());
    if (!db.open()) {
      QString message = QString("Cannot open SQLite database! \n"
                                "Error: %1").arg(db.lastError().text());
      qCritical() << message;
      QMessageBox::critical(0, QObject::tr("Error"), message);
    } else {
      setPragma(db);
      QSqlQuery q(db);
      q.setForwardOnly(true);

      if (!mainApp->dbFileExists()) {
        qWarning() << "Creating database";

        createTables(db);
        createLabels(db);
        q.prepare("INSERT INTO info(name, value) VALUES ('version', :version)");
        q.bindValue(":version", version());
        q.exec();
        q.prepare("INSERT INTO info(name, value) VALUES('appVersion', :appVersion)");
        q.bindValue(":appVersion", STRPRODUCTVER);
        q.exec();
      } else {
        qWarning() << "Preparation database";

        // Version DB > 0.12.1
        Settings settings;

        int dbVersion = -1;
        q.exec("SELECT value FROM info WHERE name='version'");
        if (q.first()) {
          dbVersion = q.value(0).toInt();
        }

        QString appVersion = QString();
        q.exec("SELECT value FROM info WHERE name='appVersion'");
        if (q.first()) {
          appVersion = q.value(0).toString();
        }

        // Create backups for DB and Settings
        if (appVersion != STRPRODUCTVER) {
          Common::createFileBackup(mainApp->dbFileName(), appVersion);
          Common::createFileBackup(settings.fileName(), appVersion);
        }

        if (dbVersion < 14) {
          q.exec("ALTER TABLE feeds ADD COLUMN showNotification integer default 0");
          q.exec("ALTER TABLE feeds ADD COLUMN disableUpdate integer default 0");
          q.exec("ALTER TABLE feeds ADD COLUMN javaScriptEnable integer default 1");
        }
        if (dbVersion < 16) {
          q.exec("ALTER TABLE feeds ADD COLUMN layoutDirection integer default 0");
        }

        // Update appVersion anyway
        if (appVersion.isEmpty()) {
          q.prepare("INSERT INTO info(name, value) VALUES('appVersion', :appVersion)");
          q.bindValue(":appVersion", STRPRODUCTVER);
          q.exec();
        } else if (appVersion != STRPRODUCTVER) {
          q.prepare("UPDATE info SET value=:appVersion WHERE name='appVersion'");
          q.bindValue(":appVersion", STRPRODUCTVER);
          q.exec();
        }

        if (dbVersion == -1) {
          q.prepare("INSERT INTO info(name, value) VALUES('version', :version)");
          q.bindValue(":version", version());
          q.exec();
        } else if (dbVersion < version()) {
          q.prepare("UPDATE info SET value=:version WHERE name='version'");
          q.bindValue(":version", version());
          q.exec();
        }

        settings.setValue("VersionDB", version());
      }

      q.finish();
      db.close();
    }
  }
  QSqlDatabase::removeDatabase("initialization");
}
Ejemplo n.º 23
0
bool MediaElementSession::allowsPictureInPicture(const HTMLMediaElement& element) const
{
    Settings* settings = element.document().settings();
    return settings && settings->allowsPictureInPictureMediaPlayback() && !element.webkitCurrentPlaybackTargetIsWireless();
}
TEST_F(FrameFetchContextTest, ModifyPriorityForExperiments)
{
    Settings* settings = document->frame()->settings();
    FetchRequest request(ResourceRequest("http://www.example.com"), FetchInitiatorInfo());

    FetchRequest preloadRequest(ResourceRequest("http://www.example.com"), FetchInitiatorInfo());
    preloadRequest.setForPreload(true);

    FetchRequest deferredRequest(ResourceRequest("http://www.example.com"), FetchInitiatorInfo());
    deferredRequest.setDefer(FetchRequest::LazyLoad);

    // Start with all experiments disabled.
    settings->setFEtchIncreaseAsyncScriptPriority(false);
    settings->setFEtchIncreaseFontPriority(false);
    settings->setFEtchDeferLateScripts(false);
    settings->setFEtchIncreasePriorities(false);

    // Base case, no priority change. Note that this triggers m_imageFetched, which will matter for setFetchDeferLateScripts() case below.
    EXPECT_EQ(ResourceLoadPriorityVeryLow, fetchContext->modifyPriorityForExperiments(ResourceLoadPriorityVeryLow, Resource::Image, request, ResourcePriority::NotVisible));

    // Image visibility should increase priority
    EXPECT_EQ(ResourceLoadPriorityLow, fetchContext->modifyPriorityForExperiments(ResourceLoadPriorityVeryLow, Resource::Image, request, ResourcePriority::Visible));

    // Font priority with and without fetchIncreaseFontPriority()
    EXPECT_EQ(ResourceLoadPriorityMedium, fetchContext->modifyPriorityForExperiments(ResourceLoadPriorityMedium, Resource::Font, request, ResourcePriority::NotVisible));
    settings->setFEtchIncreaseFontPriority(true);
    EXPECT_EQ(ResourceLoadPriorityHigh, fetchContext->modifyPriorityForExperiments(ResourceLoadPriorityMedium, Resource::Font, request, ResourcePriority::NotVisible));

    // Basic script cases
    EXPECT_EQ(ResourceLoadPriorityMedium, fetchContext->modifyPriorityForExperiments(ResourceLoadPriorityMedium, Resource::Script, request, ResourcePriority::NotVisible));
    EXPECT_EQ(ResourceLoadPriorityMedium, fetchContext->modifyPriorityForExperiments(ResourceLoadPriorityMedium, Resource::Script, preloadRequest, ResourcePriority::NotVisible));

    // Enable deferring late scripts. Preload priority should drop.
    settings->setFEtchDeferLateScripts(true);
    EXPECT_EQ(ResourceLoadPriorityLow, fetchContext->modifyPriorityForExperiments(ResourceLoadPriorityMedium, Resource::Script, preloadRequest, ResourcePriority::NotVisible));

    // Enable increasing priority of async scripts.
    EXPECT_EQ(ResourceLoadPriorityLow, fetchContext->modifyPriorityForExperiments(ResourceLoadPriorityMedium, Resource::Script, deferredRequest, ResourcePriority::NotVisible));
    settings->setFEtchIncreaseAsyncScriptPriority(true);
    EXPECT_EQ(ResourceLoadPriorityMedium, fetchContext->modifyPriorityForExperiments(ResourceLoadPriorityMedium, Resource::Script, deferredRequest, ResourcePriority::NotVisible));

    // Enable increased priorities for the remainder.
    settings->setFEtchIncreasePriorities(true);

    // Re-test image priority based on visibility with increased priorities
    EXPECT_EQ(ResourceLoadPriorityLow, fetchContext->modifyPriorityForExperiments(ResourceLoadPriorityVeryLow, Resource::Image, request, ResourcePriority::NotVisible));
    EXPECT_EQ(ResourceLoadPriorityHigh, fetchContext->modifyPriorityForExperiments(ResourceLoadPriorityVeryLow, Resource::Image, request, ResourcePriority::Visible));

    // Re-test font priority with increased prioriries
    settings->setFEtchIncreaseFontPriority(false);
    EXPECT_EQ(ResourceLoadPriorityHigh, fetchContext->modifyPriorityForExperiments(ResourceLoadPriorityMedium, Resource::Font, request, ResourcePriority::NotVisible));
    settings->setFEtchIncreaseFontPriority(true);
    EXPECT_EQ(ResourceLoadPriorityVeryHigh, fetchContext->modifyPriorityForExperiments(ResourceLoadPriorityMedium, Resource::Font, request, ResourcePriority::NotVisible));

    // Re-test basic script cases and deferring late script case with increased prioriries
    settings->setFEtchDeferLateScripts(false);
    EXPECT_EQ(ResourceLoadPriorityVeryHigh, fetchContext->modifyPriorityForExperiments(ResourceLoadPriorityMedium, Resource::Script, request, ResourcePriority::NotVisible));
    EXPECT_EQ(ResourceLoadPriorityHigh, fetchContext->modifyPriorityForExperiments(ResourceLoadPriorityMedium, Resource::Script, preloadRequest, ResourcePriority::NotVisible));

    // Re-test deferring late scripts.
    settings->setFEtchDeferLateScripts(true);
    EXPECT_EQ(ResourceLoadPriorityMedium, fetchContext->modifyPriorityForExperiments(ResourceLoadPriorityMedium, Resource::Script, preloadRequest, ResourcePriority::NotVisible));

    // Re-test increasing priority of async scripts. Should ignore general incraesed priorities.
    settings->setFEtchIncreaseAsyncScriptPriority(false);
    EXPECT_EQ(ResourceLoadPriorityLow, fetchContext->modifyPriorityForExperiments(ResourceLoadPriorityMedium, Resource::Script, deferredRequest, ResourcePriority::NotVisible));
    settings->setFEtchIncreaseAsyncScriptPriority(true);
    EXPECT_EQ(ResourceLoadPriorityMedium, fetchContext->modifyPriorityForExperiments(ResourceLoadPriorityMedium, Resource::Script, deferredRequest, ResourcePriority::NotVisible));

    // Ensure we don't go out of bounds
    settings->setFEtchIncreasePriorities(true);
    EXPECT_EQ(ResourceLoadPriorityVeryHigh, fetchContext->modifyPriorityForExperiments(ResourceLoadPriorityVeryHigh, Resource::Script, request, ResourcePriority::NotVisible));
    settings->setFEtchIncreasePriorities(false);
    settings->setFEtchDeferLateScripts(true);
    EXPECT_EQ(ResourceLoadPriorityVeryLow, fetchContext->modifyPriorityForExperiments(ResourceLoadPriorityVeryLow, Resource::Script, preloadRequest, ResourcePriority::NotVisible));
}
Ejemplo n.º 25
0
void BrowserWindow::setupUi()
{
    int locationBarWidth;
    int websearchBarWidth;

    QDesktopWidget* desktop = mApp->desktop();
    int windowWidth = desktop->availableGeometry().width() / 1.3;
    int windowHeight = desktop->availableGeometry().height() / 1.3;

    Settings settings;
    settings.beginGroup("Browser-View-Settings");
    if (settings.value("WindowMaximised", false).toBool()) {
        resize(windowWidth, windowHeight);
        setWindowState(Qt::WindowMaximized);
    }
    else {
        // Let the WM decides where to put new browser window
        if ((m_windowType != Qz::BW_FirstAppWindow && m_windowType != Qz::BW_MacFirstWindow) && mApp->getWindow()) {
#ifdef Q_WS_WIN
            // Windows WM places every new window in the middle of screen .. for some reason
            QPoint p = mApp->getWindow()->geometry().topLeft();
            p.setX(p.x() + 30);
            p.setY(p.y() + 30);

            if (!desktop->availableGeometry(mApp->getWindow()).contains(p)) {
                p.setX(desktop->availableGeometry(mApp->getWindow()).x() + 30);
                p.setY(desktop->availableGeometry(mApp->getWindow()).y() + 30);
            }

            setGeometry(QRect(p, mApp->getWindow()->size()));
#else
            resize(mApp->getWindow()->size());
#endif
        }
        else if (!restoreGeometry(settings.value("WindowGeometry").toByteArray())) {
#ifdef Q_WS_WIN
            setGeometry(QRect(desktop->availableGeometry(mApp->getWindow()).x() + 30,
                              desktop->availableGeometry(mApp->getWindow()).y() + 30, windowWidth, windowHeight));
#else
            resize(windowWidth, windowHeight);
#endif
        }
    }

    locationBarWidth = settings.value("LocationBarWidth", 480).toInt();
    websearchBarWidth = settings.value("WebSearchBarWidth", 140).toInt();
    settings.endGroup();

    QWidget* widget = new QWidget(this);
    widget->setCursor(Qt::ArrowCursor);
    setCentralWidget(widget);

    m_mainLayout = new QVBoxLayout(widget);
    m_mainLayout->setContentsMargins(0, 0, 0, 0);
    m_mainLayout->setSpacing(0);
    m_mainSplitter = new QSplitter(this);
    m_mainSplitter->setObjectName("sidebar-splitter");
    m_tabWidget = new TabWidget(this);
    m_superMenu = new QMenu(this);
    m_navigationToolbar = new NavigationBar(this);
    m_navigationToolbar->setSplitterSizes(locationBarWidth, websearchBarWidth);
    m_bookmarksToolbar = new BookmarksToolbar(this);

    m_navigationContainer = new NavigationContainer(this);
    m_navigationContainer->addWidget(m_navigationToolbar);
    m_navigationContainer->addWidget(m_bookmarksToolbar);
    m_navigationContainer->setTabBar(m_tabWidget->tabBar());

    m_mainSplitter->addWidget(m_tabWidget);
    m_mainSplitter->setCollapsible(0, false);

    m_mainLayout->addWidget(m_navigationContainer);
    m_mainLayout->addWidget(m_mainSplitter);

    statusBar()->setObjectName("mainwindow-statusbar");
    statusBar()->setCursor(Qt::ArrowCursor);
    m_progressBar = new ProgressBar(statusBar());
    m_adblockIcon = new AdBlockIcon(this);
    m_ipLabel = new QLabel(this);
    m_ipLabel->setObjectName("statusbar-ip-label");
    m_ipLabel->setToolTip(tr("IP Address of current page"));

    statusBar()->addPermanentWidget(m_progressBar);
    statusBar()->addPermanentWidget(m_ipLabel);
    statusBar()->addPermanentWidget(m_adblockIcon);

    // Workaround for Oxygen tooltips not having transparent background
    QPalette pal = QToolTip::palette();
    QColor col = pal.window().color();
    col.setAlpha(0);
    pal.setColor(QPalette::Window, col);
    QToolTip::setPalette(pal);

    // Set some sane minimum width
    setMinimumWidth(300);
}
Ejemplo n.º 26
0
void TimersEdit::createSettings()
{
    Settings *settings = new Settings(this);
    ui->toolBar->setToolButtonStyle(Qt::ToolButtonStyle(settings->toolbarLook()));
    delete settings;
}
Ejemplo n.º 27
0
void CTTToeView::processMenuActions(){
	if(menuSequenceOn){
		switch(menuSequenceId){
				case FSIZE_INCREASE:
				case FSIZE_DECREASE:
					if(sequenceValue > 0){
						Settings sett = settings;
					
						for(int i = 0; i < sequenceValue; i++){
							sett.fieldSize++;

							if(!isPossibleToFitFieldInClientArea(&sett,prevRect)){
								sett.fieldSize--;
								break;
							}
						}

						if(sett.fieldSize != settings.fieldSize){
							applySettingsAndRerender(sett);
						}
					}
					else{
						Settings tSett = settings;

						if(sequenceValue + settings.fieldSize >= MIN_FIELD_SIZE){
							tSett.fieldSize += sequenceValue;
						}	
						else{
							tSett.fieldSize = MIN_FIELD_SIZE;
						}

						if(tSett.fieldSize != settings.fieldSize){
							applySettingsAndRerender(tSett);
						}
					}

					menuSequenceOn = false;
					sequenceValue = 0;
				break;

				case SUBCELLSIZE_DECREASE:
				case SUBCELLSIZE_INCREASE:
					if(sequenceValue > 0){
						Settings sett = settings;					

						for(int i = 0; i < sequenceValue; i++){
							sett.setSizes(sett.subCellSizes[0], sett.subCellSizes[sett.posnum-1] + 1);

							if(!isPossibleToFitFieldInClientArea(&sett,prevRect)){
								sett.setSizes(sett.subCellSizes[0], sett.subCellSizes[sett.posnum-1] - 1);
								break;
							}
						}
						if(sett.subCellSizes[sett.posnum - 1] != settings.subCellSizes[settings.posnum - 1]){
							applySettingsAndRerender(sett);
						}
					}
					else{
						Settings sett = settings;

						if(sequenceValue + settings.subCellSizes[settings.posnum-1] >= MIN_SUBCELL_SIZE){
							sett.setSizes(sett.subCellSizes[0], sett.subCellSizes[sett.posnum-1] + sequenceValue);
						}	
						else{
							sett.setSizes(sett.subCellSizes[0], MIN_SUBCELL_SIZE);
						}

						if(sett.subCellSizes[sett.posnum - 1] != settings.subCellSizes[settings.posnum - 1]){
							applySettingsAndRerender(sett);
						}
					}

					menuSequenceOn = false;
					sequenceValue = 0;
				break;

				case NUM_OF_SUBCELLS_DECREASE:
				case NUM_OF_SUBCELLS_INCREASE:
					if(sequenceValue > 0){
						Settings sett = settings;
					
						for(int i = 0; i < sequenceValue; i++){
							sett.numOfSubCells++;

							if(!isPossibleToFitFieldInClientArea(&sett,prevRect)){
								sett.numOfSubCells--;
								break;
							}
						}
						if(sett.numOfSubCells != settings.numOfSubCells){
							applySettingsAndRerender(sett);
						}
					}
					else{
						Settings sett = settings;

						if(sequenceValue + settings.numOfSubCells >= MIN_NUM_OF_SUBCELLS){
							sett.numOfSubCells = sett.numOfSubCells + sequenceValue;
						}	
						else{
							sett.numOfSubCells = MIN_NUM_OF_SUBCELLS;
						}

						if(sett.numOfSubCells != settings.numOfSubCells){
							applySettingsAndRerender(sett);
						}
					}

					menuSequenceOn = false;
					sequenceValue = 0;
				break;

				case DIST_CELL_DECREASE:
				case DIST_CELL_INCREASE:
					if(sequenceValue > 0){
						Settings sett = settings;
					
						for(int i = 0; i < sequenceValue; i++){
							sett.distCellHalf ++;

							if(!isPossibleToFitFieldInClientArea(&sett,prevRect)){
								sett.distCellHalf--;
								break;
							}
						}

						if(sett.distCellHalf != settings.distCellHalf){
							applySettingsAndRerender(sett);
						}
					}
					else{
						Settings sett = settings;

						if(sequenceValue + settings.distCellHalf >= 0){
							sett.distCellHalf = sett.distCellHalf + sequenceValue;
						}	
						else{
							sett.distCellHalf = 0;
						}

						if(sett.distCellHalf != settings.distCellHalf){
							applySettingsAndRerender(sett);
						}
					}

					menuSequenceOn = false;
					sequenceValue = 0;
				break;
		}

		refreshControlLabels();
	}
}
Ejemplo n.º 28
0
void OptionsDialog::resetKeywordsButtonClicked()
{
    Settings newSettings;
    newSettings.setDefault();
    uiFromSettings(newSettings);
}
Ejemplo n.º 29
0
EXPORT void benchmark(const char* url, int reloadCount, int width, int height) {
    ScriptController::initializeThreading();

    // Setting this allows data: urls to load from a local file.
    SecurityOrigin::setLocalLoadPolicy(SecurityOrigin::AllowLocalLoadsForAll);

    // Create the fake JNIEnv and JavaVM
    InitializeJavaVM();

    // The real function is private to libwebcore but we know what it does.
    notifyHistoryItemChanged = historyItemChanged;

    // Implement the shared timer callback
    MyJavaSharedClient client;
    JavaSharedClient::SetTimerClient(&client);
    JavaSharedClient::SetCookieClient(&client);

    // Create the page with all the various clients
    ChromeClientAndroid* chrome = new ChromeClientAndroid;
    EditorClientAndroid* editor = new EditorClientAndroid;
    DeviceMotionClientAndroid* deviceMotion = new DeviceMotionClientAndroid;
    DeviceOrientationClientAndroid* deviceOrientation = new DeviceOrientationClientAndroid;
    WebCore::Page::PageClients pageClients;
    pageClients.chromeClient = chrome;
    pageClients.contextMenuClient = new ContextMenuClientAndroid;
    pageClients.editorClient = editor;
    pageClients.dragClient = new DragClientAndroid;
    pageClients.inspectorClient = new InspectorClientAndroid;
    pageClients.deviceMotionClient = deviceMotion;
    pageClients.deviceOrientationClient = deviceOrientation;
    WebCore::Page* page = new WebCore::Page(pageClients);
    editor->setPage(page);

    // Create MyWebFrame that intercepts network requests
    MyWebFrame* webFrame = new MyWebFrame(page);
    webFrame->setUserAgent("Performance testing"); // needs to be non-empty
    chrome->setWebFrame(webFrame);
    // ChromeClientAndroid maintains the reference.
    Release(webFrame);

    // Create the Frame and the FrameLoaderClient
    FrameLoaderClientAndroid* loader = new FrameLoaderClientAndroid(webFrame);
    RefPtr<Frame> frame = Frame::create(page, NULL, loader);
    loader->setFrame(frame.get());

    // Build our View system, resize it to the given dimensions and release our
    // references. Note: We keep a referenec to frameView so we can layout and
    // draw later without risk of it being deleted.
    WebViewCore* webViewCore = new WebViewCore(JSC::Bindings::getJNIEnv(),
            MY_JOBJECT, frame.get());
    RefPtr<FrameView> frameView = FrameView::create(frame.get());
    WebFrameView* webFrameView = new WebFrameView(frameView.get(), webViewCore);
    frame->setView(frameView);
    frameView->resize(width, height);
    Release(webViewCore);
    Release(webFrameView);

    // Initialize the frame and turn of low-bandwidth display (it fails an
    // assertion in the Cache code)
    frame->init();
    frame->selection()->setFocused(true);
    frame->page()->focusController()->setFocused(true);

    deviceMotion->setWebViewCore(webViewCore);
    deviceOrientation->setWebViewCore(webViewCore);

    // Set all the default settings the Browser normally uses.
    Settings* s = frame->settings();
#ifdef ANDROID_LAYOUT
    s->setLayoutAlgorithm(Settings::kLayoutNormal); // Normal layout for now
#endif
    s->setStandardFontFamily("sans-serif");
    s->setFixedFontFamily("monospace");
    s->setSansSerifFontFamily("sans-serif");
    s->setSerifFontFamily("serif");
    s->setCursiveFontFamily("cursive");
    s->setFantasyFontFamily("fantasy");
    s->setMinimumFontSize(8);
    s->setMinimumLogicalFontSize(8);
    s->setDefaultFontSize(16);
    s->setDefaultFixedFontSize(13);
    s->setLoadsImagesAutomatically(true);
    s->setJavaScriptEnabled(true);
    s->setDefaultTextEncodingName("latin1");
    s->setPluginsEnabled(false);
    s->setShrinksStandaloneImagesToFit(false);
#ifdef ANDROID_LAYOUT
    s->setUseWideViewport(false);
#endif

    // Finally, load the actual data
    ResourceRequest req(url);
    frame->loader()->load(req, false);

    do {
        // Layout the page and service the timer
        frame->view()->layout();
        while (client.m_hasTimer) {
            client.m_func();
            JavaSharedClient::ServiceFunctionPtrQueue();
        }
        JavaSharedClient::ServiceFunctionPtrQueue();

        // Layout more if needed.
        while (frame->view()->needsLayout())
            frame->view()->layout();
        JavaSharedClient::ServiceFunctionPtrQueue();

        if (reloadCount)
            frame->loader()->reload(true);
    } while (reloadCount--);

    // Draw into an offscreen bitmap
    SkBitmap bmp;
    bmp.setConfig(SkBitmap::kARGB_8888_Config, width, height);
    bmp.allocPixels();
    SkCanvas canvas(bmp);
    PlatformGraphicsContext ctx(&canvas);
    GraphicsContext gc(&ctx);
    frame->view()->paintContents(&gc, IntRect(0, 0, width, height));

    // Write the bitmap to the sdcard
    SkImageEncoder* enc = SkImageEncoder::Create(SkImageEncoder::kPNG_Type);
    enc->encodeFile("/sdcard/webcore_test.png", bmp, 100);
    delete enc;

    // Tear down the world.
    frame->loader()->detachFromParent();
    delete page;
}
Ejemplo n.º 30
0
void MenuCallbacks::markAll(MenuVItem* item)
{
	settings.setOption("MarkExecute", "markAllOnHold", item->toggleValue ? "true" : "false");
	settings.save();
}