TEST_F(StaticRangeTest, SplitTextNodeRangeWithinText)
{
    document().body()->setInnerHTML("1234", ASSERT_NO_EXCEPTION);
    Text* oldText = toText(document().body()->firstChild());

    StaticRange* staticRange04 = StaticRange::create(document(), oldText, 0, oldText, 4);
    StaticRange* staticRange02 = StaticRange::create(document(), oldText, 0, oldText, 2);
    StaticRange* staticRange22 = StaticRange::create(document(), oldText, 2, oldText, 2);
    StaticRange* staticRange24 = StaticRange::create(document(), oldText, 2, oldText, 4);

    Range* range04 = staticRange04->toRange(ASSERT_NO_EXCEPTION);
    Range* range02 = staticRange02->toRange(ASSERT_NO_EXCEPTION);
    Range* range22 = staticRange22->toRange(ASSERT_NO_EXCEPTION);
    Range* range24 = staticRange24->toRange(ASSERT_NO_EXCEPTION);

    oldText->splitText(2, ASSERT_NO_EXCEPTION);
    Text* newText = toText(oldText->nextSibling());

    // Range should mutate.
    EXPECT_TRUE(range04->boundaryPointsValid());
    EXPECT_EQ(oldText, range04->startContainer());
    EXPECT_EQ(0, range04->startOffset());
    EXPECT_EQ(newText, range04->endContainer());
    EXPECT_EQ(2, range04->endOffset());

    EXPECT_TRUE(range02->boundaryPointsValid());
    EXPECT_EQ(oldText, range02->startContainer());
    EXPECT_EQ(0, range02->startOffset());
    EXPECT_EQ(oldText, range02->endContainer());
    EXPECT_EQ(2, range02->endOffset());

    // Our implementation always moves the boundary point at the separation point to the end of the original text node.
    EXPECT_TRUE(range22->boundaryPointsValid());
    EXPECT_EQ(oldText, range22->startContainer());
    EXPECT_EQ(2, range22->startOffset());
    EXPECT_EQ(oldText, range22->endContainer());
    EXPECT_EQ(2, range22->endOffset());

    EXPECT_TRUE(range24->boundaryPointsValid());
    EXPECT_EQ(oldText, range24->startContainer());
    EXPECT_EQ(2, range24->startOffset());
    EXPECT_EQ(newText, range24->endContainer());
    EXPECT_EQ(2, range24->endOffset());

    // StaticRange shouldn't mutate.
    EXPECT_EQ(oldText, staticRange04->startContainer());
    EXPECT_EQ(0, staticRange04->startOffset());
    EXPECT_EQ(oldText, staticRange04->endContainer());
    EXPECT_EQ(4, staticRange04->endOffset());

    EXPECT_EQ(oldText, staticRange02->startContainer());
    EXPECT_EQ(0, staticRange02->startOffset());
    EXPECT_EQ(oldText, staticRange02->endContainer());
    EXPECT_EQ(2, staticRange02->endOffset());

    EXPECT_EQ(oldText, staticRange22->startContainer());
    EXPECT_EQ(2, staticRange22->startOffset());
    EXPECT_EQ(oldText, staticRange22->endContainer());
    EXPECT_EQ(2, staticRange22->endOffset());

    EXPECT_EQ(oldText, staticRange24->startContainer());
    EXPECT_EQ(2, staticRange24->startOffset());
    EXPECT_EQ(oldText, staticRange24->endContainer());
    EXPECT_EQ(4, staticRange24->endOffset());
}
TextSelection ShiftItemSelection(
		TextSelection selection,
		const Text &byText) {
	return ShiftItemSelection(selection, byText.length());
}
bool UIListViewTest_Vertical::init()
{
    if (UIScene::init())
    {
        Size widgetSize = _widget->getContentSize();
        
        _displayValueLabel = Text::create("Move by vertical direction", "fonts/Marker Felt.ttf", 32);
        _displayValueLabel->setAnchorPoint(Vec2(0.5f, -1.0f));
        _displayValueLabel->setPosition(Vec2(widgetSize.width / 2.0f,
                                              widgetSize.height / 2.0f + _displayValueLabel->getContentSize().height * 1.5f));
        _uiLayer->addChild(_displayValueLabel);
        
        
        Text* alert = Text::create("ListView vertical", "fonts/Marker Felt.ttf", 30);
        alert->setColor(Color3B(159, 168, 176));
        alert->setPosition(Vec2(widgetSize.width / 2.0f,
                                 widgetSize.height / 2.0f - alert->getContentSize().height * 3.075f));
        _uiLayer->addChild(alert);
        
        Layout* root = static_cast<Layout*>(_uiLayer->getChildByTag(81));
        
        Layout* background = dynamic_cast<Layout*>(root->getChildByName("background_Panel"));
        Size backgroundSize = background->getContentSize();
        
        
        // create list view ex data
       
        for (int i = 0; i < 20; ++i)
        {
            std::string ccstr = StringUtils::format("listview_item_%d", i);
            _array.push_back(ccstr);
        }
        
        
        // Create the list view ex
        ListView* listView = ListView::create();
        // set list view ex direction
        listView->setDirection(ui::ScrollView::Direction::VERTICAL);
        listView->setBounceEnabled(true);
        listView->setBackGroundImage("cocosui/green_edit.png");
        listView->setBackGroundImageScale9Enabled(true);
        listView->setContentSize(Size(240, 130));
		listView->setPosition(Vec2((widgetSize - listView->getContentSize()) / 2.0f));
        listView->addEventListener((ui::ListView::ccListViewCallback)CC_CALLBACK_2(UIListViewTest_Vertical::selectedItemEvent, this));
        listView->addEventListener((ui::ListView::ccScrollViewCallback)CC_CALLBACK_2(UIListViewTest_Vertical::selectedItemEventScrollView,this));
		listView->setScrollBarPositionFromCorner(Vec2(7, 7));
        _uiLayer->addChild(listView);
        
        
        // create model
        Button* default_button = Button::create("cocosui/backtotoppressed.png", "cocosui/backtotopnormal.png");
        default_button->setName("Title Button");
        
        Layout* default_item = Layout::create();
        default_item->setTouchEnabled(true);
        default_item->setContentSize(default_button->getContentSize());
		default_button->setPosition(Vec2(default_item->getContentSize() / 2.0f));
        default_item->addChild(default_button);
        
        // set model
        listView->setItemModel(default_item);
        
        // add default item
        ssize_t count = _array.size();
        for (int i = 0; i < count / 4; ++i)
        {
            listView->pushBackDefaultItem();
        }
        // insert default item
        for (int i = 0; i < count / 4; ++i)
        {
            listView->insertDefaultItem(0);
        }
        
        listView->removeAllChildren();
        
        Sprite* testSprite = Sprite::create("cocosui/backtotoppressed.png");
        testSprite->setPosition(Vec2(200,200));
        listView->addChild(testSprite);
        
        // add custom item
        for (int i = 0; i < count / 4; ++i)
        {
            Button* custom_button = Button::create("cocosui/button.png", "cocosui/buttonHighlighted.png");
            custom_button->setName("Title Button");
            custom_button->setScale9Enabled(true);
            custom_button->setContentSize(default_button->getContentSize());
            
            Layout *custom_item = Layout::create();
            custom_item->setContentSize(custom_button->getContentSize());
            custom_button->setPosition(Vec2(custom_item->getContentSize().width / 2.0f, custom_item->getContentSize().height / 2.0f));
            custom_item->addChild(custom_button);
            
            listView->addChild(custom_item);
        }
        // insert custom item
        Vector<Widget*>& items = listView->getItems();
        ssize_t items_count = items.size();
        for (int i = 0; i < count / 4; ++i)
        {
            Button* custom_button = Button::create("cocosui/button.png", "cocosui/buttonHighlighted.png");
            custom_button->setName("Title Button");
            custom_button->setScale9Enabled(true);
            custom_button->setContentSize(default_button->getContentSize());
            
            Layout *custom_item = Layout::create();
            custom_item->setContentSize(custom_button->getContentSize());
            custom_button->setPosition(Vec2(custom_item->getContentSize().width / 2.0f, custom_item->getContentSize().height / 2.0f));
            custom_item->addChild(custom_button);
            custom_item->setTag(1);
            
            listView->insertCustomItem(custom_item, items_count);
        }
        
        // set item data
        items_count = items.size();
        for (int i = 0; i < items_count; ++i)
        {
            Widget* item = listView->getItem(i);
            Button* button = static_cast<Button*>(item->getChildByName("Title Button"));
            ssize_t index = listView->getIndex(item);
            button->setTitleText(_array[index]);
        }
        
        // remove last item
        listView->removeChildByTag(1);
        
        // remove item by index
        items_count = items.size();
        listView->removeItem(items_count - 1);
        
        // set all items layout gravity
        listView->setGravity(ListView::Gravity::CENTER_VERTICAL);
        
        // set items margin
        listView->setItemsMargin(2.0f);

        // Show the indexes of items on each boundary.
        {
            float position = 75;
            // Labels
            _indexLabels[0] = Text::create(" ", "fonts/Marker Felt.ttf", 12);
            _indexLabels[0]->setAnchorPoint(Vec2::ANCHOR_MIDDLE);
            _indexLabels[0]->setPosition(_uiLayer->getContentSize() / 2 + Size(0, position));
            _uiLayer->addChild(_indexLabels[0]);
            _indexLabels[1] = Text::create("  ", "fonts/Marker Felt.ttf", 12);
            _indexLabels[1]->setAnchorPoint(Vec2::ANCHOR_MIDDLE);
            _indexLabels[1]->setPosition(_uiLayer->getContentSize() / 2 + Size(140, 0));
            _uiLayer->addChild(_indexLabels[1]);
            _indexLabels[2] = Text::create(" ", "fonts/Marker Felt.ttf", 12);
            _indexLabels[2]->setAnchorPoint(Vec2::ANCHOR_MIDDLE);
            _indexLabels[2]->setPosition(_uiLayer->getContentSize() / 2 + Size(0, -position));
            _uiLayer->addChild(_indexLabels[2]);
            
            // Callback
            listView->ScrollView::addEventListener([this](Ref* ref, ScrollView::EventType eventType) {
                ListView* listView = dynamic_cast<ListView*>(ref);
                if(listView == nullptr || eventType != ScrollView::EventType::CONTAINER_MOVED)
                {
                    return;
                }
                auto bottom = listView->getBottommostItemInCurrentView();
                auto center = listView->getCenterItemInCurrentView();
                auto top = listView->getTopmostItemInCurrentView();
                
                _indexLabels[0]->setString(StringUtils::format("Top index=%zd", listView->getIndex(top)));
                _indexLabels[1]->setString(StringUtils::format("Center\nindex=%zd", listView->getIndex(center)));
                _indexLabels[2]->setString(StringUtils::format("Bottom index=%zd", listView->getIndex(bottom)));
            });
        }
        
        return true;
    }
    
    return false;
}
Game::menu_t Game::ScenarioInfo(void)
{
    Settings & conf = Settings::Get();

    AGG::PlayMusic(MUS::MAINMENU);

    MapsFileInfoList lists;
    if(!PrepareMapsFileInfoList(lists, (conf.GameType(Game::TYPE_MULTI))))
    {
	Dialog::Message(_("Warning"), _("No maps available!"), Font::BIG, Dialog::OK);
        return MAINMENU;
    }

    menu_t result = QUITGAME;
    LocalEvent & le = LocalEvent::Get();

    // cursor
    Cursor & cursor = Cursor::Get();
    cursor.Hide();
    cursor.SetThemes(cursor.POINTER);

    Display & display = Display::Get();

    Point top, pointDifficultyInfo, pointOpponentInfo, pointClassInfo;
    Rect rectPanel;
    Button* buttonSelectMaps = NULL;
    Button* buttonOk = NULL;
    Button* buttonCancel = NULL;

    // vector coord difficulty
    Rects coordDifficulty;
    coordDifficulty.reserve(5);

    const Sprite & ngextra = AGG::GetICN(ICN::NGEXTRA, 62);
    Dialog::FrameBorder* frameborder = NULL;

    // image background
    if(conf.QVGA())
    {
	frameborder = new Dialog::FrameBorder(Size(380, 224));
	rectPanel = frameborder->GetArea();

	pointDifficultyInfo = Point(rectPanel.x + 4, rectPanel.y + 24);
	pointOpponentInfo = Point(rectPanel.x + 4, rectPanel.y + 94);
	pointClassInfo = Point(rectPanel.x + 4, rectPanel.y + 148);

	coordDifficulty.push_back(Rect(rectPanel.x + 1, rectPanel.y + 21,   ngextra.w(), ngextra.h()));
	coordDifficulty.push_back(Rect(rectPanel.x + 78, rectPanel.y + 21,  ngextra.w(), ngextra.h()));
	coordDifficulty.push_back(Rect(rectPanel.x + 154, rectPanel.y + 21, ngextra.w(), ngextra.h()));
	coordDifficulty.push_back(Rect(rectPanel.x + 231, rectPanel.y + 21, ngextra.w(), ngextra.h()));
        coordDifficulty.push_back(Rect(rectPanel.x + 308, rectPanel.y + 21, ngextra.w(), ngextra.h()));

	buttonOk = new Button(rectPanel.x + rectPanel.w / 2 - 160, rectPanel.y + rectPanel.h - 30, ICN::NGEXTRA, 66, 67);
	buttonCancel = new Button(rectPanel.x + rectPanel.w / 2 + 60, rectPanel.y + rectPanel.h - 30, ICN::NGEXTRA, 68, 69);

	Text text;
	text.Set(conf.CurrentFileInfo().name, Font::BIG);
	text.Blit(rectPanel.x + (rectPanel.w - text.w()) / 2, rectPanel.y + 5);
    }
    else
    {
	const Sprite &panel = AGG::GetICN(ICN::NGHSBKG, 0);
	const Sprite &back = AGG::GetICN(ICN::HEROES, 0);
	const Point top((display.w() - back.w()) / 2, (display.h() - back.h()) / 2);

	rectPanel = Rect(top.x + 204, top.y + 32, panel.w(), panel.h());
	pointDifficultyInfo = Point(rectPanel.x + 24, rectPanel.y + 93);
	pointOpponentInfo = Point(rectPanel.x + 24, rectPanel.y + 202);
	pointClassInfo = Point(rectPanel.x + 24, rectPanel.y + 282);

	coordDifficulty.push_back(Rect(rectPanel.x + 21, rectPanel.y + 91,  ngextra.w(), ngextra.h()));
	coordDifficulty.push_back(Rect(rectPanel.x + 98, rectPanel.y + 91,  ngextra.w(), ngextra.h()));
	coordDifficulty.push_back(Rect(rectPanel.x + 174, rectPanel.y + 91, ngextra.w(), ngextra.h()));
	coordDifficulty.push_back(Rect(rectPanel.x + 251, rectPanel.y + 91, ngextra.w(), ngextra.h()));
	coordDifficulty.push_back(Rect(rectPanel.x + 328, rectPanel.y + 91, ngextra.w(), ngextra.h()));

	buttonSelectMaps = new Button(rectPanel.x + 309, rectPanel.y + 45, ICN::NGEXTRA, 64, 65);
	buttonOk = new Button(rectPanel.x + 31, rectPanel.y + 380, ICN::NGEXTRA, 66, 67);
	buttonCancel = new Button(rectPanel.x + 287, rectPanel.y + 380, ICN::NGEXTRA, 68, 69);

	back.Blit(top);
    }

    const bool reset_starting_settings = conf.MapsFile().empty() || ! System::IsFile(conf.MapsFile());
    Players & players = conf.GetPlayers();
    Interface::PlayersInfo playersInfo(true, !conf.QVGA(), !conf.QVGA());

    // set first maps settings
    if(reset_starting_settings)
	conf.SetCurrentFileInfo(lists.front());

    playersInfo.UpdateInfo(players, pointOpponentInfo, pointClassInfo);

    RedrawScenarioStaticInfo(rectPanel);
    RedrawDifficultyInfo(pointDifficultyInfo, !conf.QVGA());

    playersInfo.RedrawInfo();

    TextSprite* rating = conf.QVGA() ? NULL : new TextSprite();
    if(rating)
    {
	rating->SetFont(Font::BIG);
	rating->SetPos(rectPanel.x + 166, rectPanel.y + 383);
	RedrawRatingInfo(*rating);
    }

    SpriteMove levelCursor(ngextra);

    switch(conf.GameDifficulty())
    {
	case Difficulty::EASY:		levelCursor.Move(coordDifficulty[0]); break;
	case Difficulty::NORMAL:	levelCursor.Move(coordDifficulty[1]); break;
	case Difficulty::HARD:		levelCursor.Move(coordDifficulty[2]); break;
	case Difficulty::EXPERT:	levelCursor.Move(coordDifficulty[3]); break;
	case Difficulty::IMPOSSIBLE:	levelCursor.Move(coordDifficulty[4]); break;
    }

    if(buttonSelectMaps) buttonSelectMaps->Draw();
    buttonOk->Draw();
    buttonCancel->Draw();

    cursor.Show();
    display.Flip();

    while(le.HandleEvents())
    {
	// press button
	if(buttonSelectMaps)
	le.MousePressLeft(*buttonSelectMaps) ? buttonSelectMaps->PressDraw() : buttonSelectMaps->ReleaseDraw();
	le.MousePressLeft(*buttonOk) ? buttonOk->PressDraw() : buttonOk->ReleaseDraw();
	le.MousePressLeft(*buttonCancel) ? buttonCancel->PressDraw() : buttonCancel->ReleaseDraw();

	// click select
	if(buttonSelectMaps &&
	  (Game::HotKeyPress(Game::EVENT_BUTTON_SELECT) || le.MouseClickLeft(*buttonSelectMaps)))
	{
	    levelCursor.Hide();
	    const Maps::FileInfo* fi = Dialog::SelectScenario(lists);
	    if(fi)
	    {
		conf.SetCurrentFileInfo(*fi);
		playersInfo.UpdateInfo(players, pointOpponentInfo, pointClassInfo);

		cursor.Hide();
		RedrawScenarioStaticInfo(rectPanel);
		RedrawDifficultyInfo(pointDifficultyInfo, !conf.QVGA());
		playersInfo.RedrawInfo();
		if(rating) RedrawRatingInfo(*rating);
		// default difficulty normal
		levelCursor.Move(coordDifficulty[1]);
    		conf.SetGameDifficulty(Difficulty::NORMAL);
		buttonOk->Draw();
		buttonCancel->Draw();
	    }
	    cursor.Show();
	    display.Flip();
	}
	else
	// click cancel
	if(HotKeyPress(EVENT_DEFAULT_EXIT) || le.MouseClickLeft(*buttonCancel))
	{
	    result = MAINMENU;
	    break;
	}
	else
	// click ok
	if(HotKeyPress(EVENT_DEFAULT_READY) || le.MouseClickLeft(*buttonOk))
	{
	    DEBUG(DBG_GAME, DBG_INFO, "select maps: " << conf.MapsFile() << \
		    ", difficulty: " << Difficulty::String(conf.GameDifficulty()));
	    result = STARTGAME;
	    break;
	}
	else
	if(le.MouseClickLeft(rectPanel))
	{
	    const s32 index = coordDifficulty.GetIndex(le.GetMouseCursor());

	    // select difficulty
	    if(0 <= index)
	    {
		cursor.Hide();
		levelCursor.Move(coordDifficulty[index]);
		conf.SetGameDifficulty(index);
		if(rating) RedrawRatingInfo(*rating);
		cursor.Show();
		display.Flip();
	    }
	    else
	    // playersInfo
	    if(playersInfo.QueueEventProcessing())
	    {
		cursor.Hide();
		RedrawScenarioStaticInfo(rectPanel);
		levelCursor.Redraw();
		RedrawDifficultyInfo(pointDifficultyInfo, !conf.QVGA());

		playersInfo.RedrawInfo();
		if(rating) RedrawRatingInfo(*rating);
		buttonOk->Draw();
		buttonCancel->Draw();
		cursor.Show();
		display.Flip();
	    }
	}

	if(le.MousePressRight(rectPanel))
	{
	    if(buttonSelectMaps && le.MousePressRight(*buttonSelectMaps))
		Dialog::Message(_("Scenario"), _("Click here to select which scenario to play."), Font::BIG);
	    else
	    if(0 <= coordDifficulty.GetIndex(le.GetMouseCursor()))
		Dialog::Message(_("Game Difficulty"), _("This lets you change the starting difficulty at which you will play. Higher difficulty levels start you of with fewer resources, and at the higher settings, give extra resources to the computer."), Font::BIG);
	    else
	    if(rating && le.MousePressRight(rating->GetRect()))
		Dialog::Message(_("Difficulty Rating"), _("The difficulty rating reflects a combination of various settings for your game. This number will be applied to your final score."), Font::BIG);
	    else
	    if(le.MousePressRight(*buttonOk))
		Dialog::Message(_("OK"), _("Click to accept these settings and start a new game."), Font::BIG);
	    else
	    if(le.MousePressRight(*buttonCancel))
		Dialog::Message(_("Cancel"), _("Click to return to the main menu."), Font::BIG);
	    else
		playersInfo.QueueEventProcessing();
	}
    }

    cursor.Hide();

    if(result == STARTGAME)
    {
	players.SetStartGame();
	if(conf.ExtGameUseFade()) display.Fade();
	Game::ShowLoadMapsText();
	// Load maps
	world.LoadMaps(conf.MapsFile());
    }

    if(frameborder) delete frameborder;
    if(rating) delete rating;
    if(buttonSelectMaps) delete buttonSelectMaps;
    delete buttonOk;
    delete buttonCancel;

    return result;
}
Example #5
0
DlgEventKeyDown::DlgEventKeyDown(Actor *actor, bool bUp)
	: Panel("EventKeyDown", (GameControl::Get()->Width() - ((bUp || !Tutorial::IsCompatible(VERSION_GET_ANIMINDEX))?WIDTH:WIDTH_KEY_DOWN))/2, 
				          (GameControl::Get()->Height() - ((bUp || !Tutorial::IsCompatible(VERSION_GET_ANIMINDEX))?HEIGHT:HEIGHT_KEY_DOWN))/2,
						  ((bUp || !Tutorial::IsCompatible(VERSION_GET_ANIMINDEX))?WIDTH:WIDTH_KEY_DOWN), 
						  ((bUp || !Tutorial::IsCompatible(VERSION_GET_ANIMINDEX))?HEIGHT:HEIGHT_KEY_DOWN))
{
	SetModal();
	eventActor = actor;
	this->bUp = bUp;
	mode = SDLK_UNKNOWN;

	Text *text;
	Button *button;	
	Actor *add;
	int y;
	listMode = listRepeat = NULL;
	textPanel = NULL;

	//Title
	text = AddText(bUp?"Key Up Event":"Key Down Event", CENTER_TEXT, 5);
	y = DrawHLine(text->Down() + 2);
	

	if(bUp || !Tutorial::IsCompatible(VERSION_GET_ANIMINDEX))
	{
		//Body
		text = AddText("Press event key or\nright click for 'any' key: ", 10, y);	
		textKey = AddText("              ", 170, text->Down() - 13);
		
		y = textKey->Down() + 5;
		if(!bUp)
		{
			SetToolTip(TIP_DLG_KEYDOWN);
			
			text = AddText("Repeat: ", 10, y+2);
			listRepeat = AddListPop(text->Right(), text->Top(), 128); listRepeat->SetToolTip(TIP_DLG_KEYDOWN_REPEAT);			
			y = listRepeat->Down();
		}
		else
		{
			SetToolTip(TIP_DLG_KEYUP);
			y += 20;
		}
	}
	else
	{
		//New Key Down intreface
		SetToolTip(TIP_DLG_KEYDOWN);

		text =    AddText("Press the key or key sequence (right click for 'any' key)", 10, y);	
		text =    AddText("Keys: ", 10, text->Down() + 4);	

		textKey = AddText("                                                          \n                                                          "
			, text->Right(), text->Top() + 2);

		textPanel = new Panel("textKeyPanel", textKey->Left() - 5, textKey->Top() - 2, textKey->Width() + 5, textKey->Height() + 4,
				  this, true, false, true, false);

		//Transparent background
		KrRGBA *pixels = textPanel->getCanvasResource()->Pixels();	
		if(pixels)
		{
			KrRGBA colorBack;
			colorBack.c.alpha = 0;
			
			for(int i = 2; i < textKey->Width() + 3; i++)
			{
				for(int j = 2; j < textKey->Height() + 2; j++)
				{
					pixels[ j*textPanel->Width() + i ] = colorBack;
				}
			}
		}

		GetFocus(this);

		textKey->getImage()->SetZDepth(textPanel->getImage()->ZDepth() + 1000);

		button = AddButton("Clear", textPanel->Right() - 45, textPanel->Down() + 3, 45, 0, BT_CLEAR); button->SetToolTip(TIP_DLG_KEYDOWN_CLEAR);			

		y = DrawHLine(button->Down() + 3);		
		
		text = AddText("Execute when: ", 10, y+2);
		listMode = AddListPop(text->Right(), text->Top(), 230); listMode->SetToolTip(TIP_DLG_KEYDOWN_MODE);			

		text = AddText("      Repeat: ", 10, listMode->Down() + 2);
		listRepeat = AddListPop(text->Right(), text->Top(), 128); listRepeat->SetToolTip(TIP_DLG_KEYDOWN_REPEAT);

		listMode->AddText("At least one key is pressed");
		listMode->AddText("All keys are pressed");
		listMode->AddText("Keys are pressed in order");
		listMode->SetItem("At least one key is pressed");
		
		y = listRepeat->Down();
	}
	
	//Close
	y = DrawHLine(y + 5);
	if(Action::inNewActivationEvent())
	{
		add = AddButton("Choose Actor", (((bUp || !Tutorial::IsCompatible(VERSION_GET_ANIMINDEX))?WIDTH:WIDTH_KEY_DOWN)-135)/2 - 15, y, 0, 0, LS_ACTION); ((Button *)add)->SetToolTip(TIP_ACTIVATIONEVENT_CHOOSE);	
	}
	else if(Action::getEditAction())
	{
		add = AddButton("Edit Action", (((bUp || !Tutorial::IsCompatible(VERSION_GET_ANIMINDEX))?WIDTH:WIDTH_KEY_DOWN)-135)/2 - 12, y, 0, 0, LS_ACTION); ((Button *)add)->SetToolTip(TIP_ACTION_EDIT);
	}
	else
	{
		add = AddListPop((((bUp || !Tutorial::IsCompatible(VERSION_GET_ANIMINDEX))?WIDTH:WIDTH_KEY_DOWN)-135)/2 - 10, y, 85, 0, LS_ACTION, "Add Action"); ((ListPop *)add)->SetToolTip(TIP_ADDACTION);	
		Action::Populate((ListPop *)add);
	}

	
	if(Action::getEditAction())
	{
		button = AddButton("Cancel", add->Right() + 10, y, 0, 0, BT_CANCEL); if(!Action::inNewActivationEvent()) button->SetToolTip(TIP_ACTION_CANCEL);	
	}
	else
	{
		button = AddButton("Close", add->Right() + 10, y, 0, 0, BT_CANCEL); if(!Action::inNewActivationEvent()) button->SetToolTip(TIP_ACTION_CLOSE);	
	}

	if(listRepeat)
	{
		listRepeat->AddText("Enable");
		listRepeat->AddText("Disable");
		listRepeat->SetItem("Enable");
	}

	Clear();

	UpdateEdition();
}
void InsertParagraphSeparatorCommand::doApply()
{
    bool splitText = false;
    if (endingSelection().isNone())
        return;
    
    Position insertionPosition = endingSelection().start();
        
    EAffinity affinity = endingSelection().affinity();
        
    // Delete the current selection.
    if (endingSelection().isRange()) {
        calculateStyleBeforeInsertion(insertionPosition);
        deleteSelection(false, true);
        insertionPosition = endingSelection().start();
        affinity = endingSelection().affinity();
    }
    
    // FIXME: The rangeCompliantEquivalent conversion needs to be moved into enclosingBlock.
    Node* startBlockNode = enclosingBlock(rangeCompliantEquivalent(insertionPosition).node());
    Position canonicalPos = VisiblePosition(insertionPosition).deepEquivalent();
    Element* startBlock = static_cast<Element*>(startBlockNode);
    if (!startBlockNode
            || !startBlockNode->isElementNode()
            || !startBlock->parentNode()
            || isTableCell(startBlock)
            || startBlock->hasTagName(formTag)
            || (canonicalPos.node()->renderer() && canonicalPos.node()->renderer()->isTable())
            || canonicalPos.node()->hasTagName(hrTag)) {
        applyCommandToComposite(InsertLineBreakCommand::create(document()));
        return;
    }
    
    // Use the leftmost candidate.
    insertionPosition = insertionPosition.upstream();
    if (!insertionPosition.isCandidate())
        insertionPosition = insertionPosition.downstream();

    // Adjust the insertion position after the delete
    insertionPosition = positionAvoidingSpecialElementBoundary(insertionPosition);
    VisiblePosition visiblePos(insertionPosition, affinity);
    calculateStyleBeforeInsertion(insertionPosition);

    //---------------------------------------------------------------------
    // Handle special case of typing return on an empty list item
    if (breakOutOfEmptyListItem())
        return;

    //---------------------------------------------------------------------
    // Prepare for more general cases.

    bool isFirstInBlock = isStartOfBlock(visiblePos);
    bool isLastInBlock = isEndOfBlock(visiblePos);
    bool nestNewBlock = false;

    // Create block to be inserted.
    RefPtr<Element> blockToInsert;
    if (startBlock == startBlock->rootEditableElement()) {
        blockToInsert = createDefaultParagraphElement(document());
        nestNewBlock = true;
    } else if (shouldUseDefaultParagraphElement(startBlock)) 
        blockToInsert = createDefaultParagraphElement(document());
    else
        blockToInsert = startBlock->cloneElementWithoutChildren();

    //---------------------------------------------------------------------
    // Handle case when position is in the last visible position in its block,
    // including when the block is empty. 
    if (isLastInBlock) {
        bool shouldApplyStyleAfterInsertion = true;
        if (nestNewBlock) {
            if (isFirstInBlock && !lineBreakExistsAtVisiblePosition(visiblePos)) {
                // The block is empty.  Create an empty block to
                // represent the paragraph that we're leaving.
                RefPtr<Element> extraBlock = createDefaultParagraphElement(document());
                appendNode(extraBlock, startBlock);
                appendBlockPlaceholder(extraBlock);
            }
            appendNode(blockToInsert, startBlock);
        } else {
            // We can get here if we pasted a copied portion of a blockquote with a newline at the end and are trying to paste it
            // into an unquoted area. We then don't want the newline within the blockquote or else it will also be quoted.
            if (Node* highestBlockquote = highestEnclosingNodeOfType(canonicalPos, &isMailBlockquote)) {
                startBlock = static_cast<Element*>(highestBlockquote);
                // When inserting the newline after the blockquote, we don't want to apply the original style after the insertion
                shouldApplyStyleAfterInsertion = false;
            }
            insertNodeAfter(blockToInsert, startBlock);
        }

        appendBlockPlaceholder(blockToInsert);
        setEndingSelection(VisibleSelection(Position(blockToInsert.get(), 0), DOWNSTREAM));
        if (shouldApplyStyleAfterInsertion)
            applyStyleAfterInsertion(startBlock);
        return;
    }

    //---------------------------------------------------------------------
    // Handle case when position is in the first visible position in its block, and
    // similar case where previous position is in another, presumeably nested, block.
    if (isFirstInBlock || !inSameBlock(visiblePos, visiblePos.previous())) {
        Node *refNode;
        if (isFirstInBlock && !nestNewBlock)
            refNode = startBlock;
        else if (insertionPosition.node() == startBlock && nestNewBlock) {
            refNode = startBlock->childNode(insertionPosition.deprecatedEditingOffset());
            ASSERT(refNode); // must be true or we'd be in the end of block case
        } else
            refNode = insertionPosition.node();

        // find ending selection position easily before inserting the paragraph
        insertionPosition = insertionPosition.downstream();
        
        insertNodeBefore(blockToInsert, refNode);
        appendBlockPlaceholder(blockToInsert.get());
        setEndingSelection(VisibleSelection(Position(blockToInsert.get(), 0), DOWNSTREAM));
        applyStyleAfterInsertion(startBlock);
        setEndingSelection(VisibleSelection(insertionPosition, DOWNSTREAM));
        return;
    }

    //---------------------------------------------------------------------
    // Handle the (more complicated) general case,

    // All of the content in the current block after visiblePos is
    // about to be wrapped in a new paragraph element.  Add a br before 
    // it if visiblePos is at the start of a paragraph so that the 
    // content will move down a line.
    if (isStartOfParagraph(visiblePos)) {
        RefPtr<Element> br = createBreakElement(document());
        insertNodeAt(br.get(), insertionPosition);
        insertionPosition = positionAfterNode(br.get());
    }
    
    // Move downstream. Typing style code will take care of carrying along the 
    // style of the upstream position.
    insertionPosition = insertionPosition.downstream();

    // At this point, the insertionPosition's node could be a container, and we want to make sure we include
    // all of the correct nodes when building the ancestor list.  So this needs to be the deepest representation of the position
    // before we walk the DOM tree.
    insertionPosition = VisiblePosition(insertionPosition).deepEquivalent();

    // Build up list of ancestors in between the start node and the start block.
    Vector<Element*> ancestors;
    if (insertionPosition.node() != startBlock) {
        for (Element* n = insertionPosition.node()->parentElement(); n && n != startBlock; n = n->parentElement())
            ancestors.append(n);
    }

    // Make sure we do not cause a rendered space to become unrendered.
    // FIXME: We need the affinity for pos, but pos.downstream() does not give it
    Position leadingWhitespace = insertionPosition.leadingWhitespacePosition(VP_DEFAULT_AFFINITY);
    // FIXME: leadingWhitespacePosition is returning the position before preserved newlines for positions
    // after the preserved newline, causing the newline to be turned into a nbsp.
    if (leadingWhitespace.isNotNull()) {
        Text* textNode = static_cast<Text*>(leadingWhitespace.node());
        ASSERT(!textNode->renderer() || textNode->renderer()->style()->collapseWhiteSpace());
        replaceTextInNode(textNode, leadingWhitespace.deprecatedEditingOffset(), 1, nonBreakingSpaceString());
    }
    
    // Split at pos if in the middle of a text node.
    if (insertionPosition.node()->isTextNode()) {
        Text* textNode = static_cast<Text*>(insertionPosition.node());
        bool atEnd = (unsigned)insertionPosition.deprecatedEditingOffset() >= textNode->length();
        if (insertionPosition.deprecatedEditingOffset() > 0 && !atEnd) {
            splitTextNode(textNode, insertionPosition.deprecatedEditingOffset());
            insertionPosition.moveToOffset(0);
            visiblePos = VisiblePosition(insertionPosition);
            splitText = true;
        }
    }

    // Put the added block in the tree.
    if (nestNewBlock)
        appendNode(blockToInsert.get(), startBlock);
    else
        insertNodeAfter(blockToInsert.get(), startBlock);

    updateLayout();
    
    // Make clones of ancestors in between the start node and the start block.
    RefPtr<Element> parent = blockToInsert;
    for (size_t i = ancestors.size(); i != 0; --i) {
        RefPtr<Element> child = ancestors[i - 1]->cloneElementWithoutChildren();
        appendNode(child, parent);
        parent = child.release();
    }

    // If the paragraph separator was inserted at the end of a paragraph, an empty line must be
    // created.  All of the nodes, starting at visiblePos, are about to be added to the new paragraph 
    // element.  If the first node to be inserted won't be one that will hold an empty line open, add a br.
    if (isEndOfParagraph(visiblePos) && !lineBreakExistsAtVisiblePosition(visiblePos))
        appendNode(createBreakElement(document()).get(), blockToInsert.get());
        
    // Move the start node and the siblings of the start node.
    if (insertionPosition.node() != startBlock) {
        Node* n = insertionPosition.node();
        if (insertionPosition.deprecatedEditingOffset() >= caretMaxOffset(n))
            n = n->nextSibling();

        while (n && n != blockToInsert) {
            Node *next = n->nextSibling();
            removeNode(n);
            appendNode(n, parent.get());
            n = next;
        }
    }            

    // Move everything after the start node.
    if (!ancestors.isEmpty()) {
        Element* leftParent = ancestors.first();
        while (leftParent && leftParent != startBlock) {
            parent = parent->parentElement();
            if (!parent)
                break;
            Node* n = leftParent->nextSibling();
            while (n && n != blockToInsert) {
                Node* next = n->nextSibling();
                removeNode(n);
                appendNode(n, parent.get());
                n = next;
            }
            leftParent = leftParent->parentElement();
        }
    }

    // Handle whitespace that occurs after the split
    if (splitText) {
        updateLayout();
        insertionPosition = Position(insertionPosition.node(), 0);
        if (!insertionPosition.isRenderedCharacter()) {
            // Clear out all whitespace and insert one non-breaking space
            ASSERT(insertionPosition.node()->isTextNode());
            ASSERT(!insertionPosition.node()->renderer() || insertionPosition.node()->renderer()->style()->collapseWhiteSpace());
            deleteInsignificantTextDownstream(insertionPosition);
            insertTextIntoNode(static_cast<Text*>(insertionPosition.node()), 0, nonBreakingSpaceString());
        }
    }

    setEndingSelection(VisibleSelection(Position(blockToInsert.get(), 0), DOWNSTREAM));
    applyStyleAfterInsertion(startBlock);
}
Example #7
0
bool UIImageViewTest_ContentSize::init()
{
    if (UIScene::init())
    {
        Size widgetSize = _widget->getContentSize();
        
        Text* alert = Text::create("ImageView ContentSize Change", "fonts/Marker Felt.ttf", 26);
        alert->setColor(Color3B(159, 168, 176));
        alert->setPosition(Vec2(widgetSize.width / 2.0f,
                                widgetSize.height / 2.0f - alert->getContentSize().height * 2.125f));
        
        _uiLayer->addChild(alert);
        
        Text *status = Text::create("child ImageView position percent", "fonts/Marker Felt.ttf", 16);
        status->setColor(Color3B::RED);
        status->setPosition(Vec2(widgetSize.width/2, widgetSize.height/2 + 80));
        _uiLayer->addChild(status,20);
        
        // Create the imageview
        ImageView* imageView = ImageView::create("cocosui/buttonHighlighted.png");
        imageView->setScale9Enabled(true);
        imageView->setContentSize(Size(200, 80));
        imageView->setPosition(Vec2(widgetSize.width / 2.0f,
                                    widgetSize.height / 2.0f ));
       
        
        ImageView* imageViewChild = ImageView::create("cocosui/buttonHighlighted.png");
        imageViewChild->setScale9Enabled(true);
        imageViewChild->setSizeType(Widget::SizeType::PERCENT);
        imageViewChild->setPositionType(Widget::PositionType::PERCENT);
        imageViewChild->setSizePercent(Vec2::ANCHOR_MIDDLE);
        imageViewChild->setPositionPercent(Vec2::ANCHOR_MIDDLE);
        imageViewChild->setPosition(Vec2(widgetSize.width / 2.0f,
                                    widgetSize.height / 2.0f));
        
        ImageView* imageViewChild2 = ImageView::create("cocosui/buttonHighlighted.png");
        imageViewChild2->setScale9Enabled(true);
        imageViewChild2->setSizeType(Widget::SizeType::PERCENT);
        imageViewChild2->setPositionType(Widget::PositionType::PERCENT);
        imageViewChild2->setSizePercent(Vec2::ANCHOR_MIDDLE);
        imageViewChild2->setPositionPercent(Vec2::ANCHOR_MIDDLE);
        imageViewChild->addChild(imageViewChild2);
        
        
        imageView->addChild(imageViewChild);
        
        imageView->setTouchEnabled(true);
        imageView->addTouchEventListener([=](Ref* sender, Widget::TouchEventType type){
            if (type == Widget::TouchEventType::ENDED) {
                float width = CCRANDOM_0_1() * 200 + 50;
                float height = CCRANDOM_0_1() * 80 + 30;
                imageView->setContentSize(Size(width, height));
                
                imageViewChild->setPositionPercent(Vec2(CCRANDOM_0_1(), CCRANDOM_0_1()));
                status->setString(StringUtils::format("child ImageView position percent: %f, %f",
                                                      imageViewChild->getPositionPercent().x, imageViewChild->getPositionPercent().y));
            }
        });
        
        _uiLayer->addChild(imageView);
        
        return true;
    }
    return false;
}
Example #8
0
//----- Begin of function FacultyRes::report ------//
//!
//! Display Stock Ownership Report
//!
//! <int> refreshFlag = INFO_REPAINT or INFO_UPDATE
//!
void FacultyRes::report(int refreshFlag) {
    //---- determine the department for display the faculty records ----//
    int deptRecno=1;

    if( department_array.selected_recno )
	deptRecno = department_array.selected_recno;
    cur_dept_ptr = department_array[deptRecno];

    // fix in version 2, infinite loop if report_faculty_recno is 0
    if( report_faculty_recno <= 0)
	report_faculty_recno = 1;

    // begin chwg080999 avoiding (facultyPtr->faculty_recno==0)
    Faculty* facultyPtr = cur_dept_ptr->faculty_array.get_unpacked_faculty(report_faculty_recno);
    while((facultyPtr->faculty_recno==0)&&(report_faculty_recno!=1))
	facultyPtr = cur_dept_ptr->faculty_array.get_unpacked_faculty(--report_faculty_recno);
    // end chwg080999

    //------ paint the background -------//
    vga.use_back();

    if( refreshFlag == INFO_REPAINT ) {
	user_interface.bg_img(BG_PIC_ID, &vga_back);

	if( report_type==REPORT_TYPE_LIST ) {
	    user_interface.brighten(REPORT_X1+100,REPORT_Y1-13,REPORT_X1+630,REPORT_Y1+10);
	    user_interface.rect(REPORT_X1+100,REPORT_Y1-13,REPORT_X1+630,REPORT_Y1+10,1);
	    font_charts.put(REPORT_X1+300,REPORT_Y1-8,"Faculty Directory");
	}

	report_paint_button(refreshFlag);
    }
    else {
	//		report_paint_button(refreshFlag);
    }

    //----------- If it's in the list mode -------------//
    if( report_type==REPORT_TYPE_LIST ) {
	if( refreshFlag == INFO_REPAINT ) {
	    browse_faculty.init( REPORT_X1, REPORT_Y1+10, REPORT_X2, REPORT_Y2+10,
				 0, FACULTY_REC_HEIGHT,
				 cur_dept_ptr->faculty_array.faculty_count,
				 disp_faculty_rec, NULL ,1 );
	    browse_faculty.open(report_faculty_recno,cur_dept_ptr->faculty_array.faculty_count);
	}
	else {                                        // refreshFlag == INFO_UPDATE
	    //			browse_faculty.refresh(-1, cur_dept_ptr->faculty_array.faculty_count);
	}
	report_faculty_recno = browse_faculty.recno();
    }
    else if( report_type==REPORT_TYPE_DETAIL) {
	//------- if it's in detailed mode --------//
	if( cur_dept_ptr->faculty_array.faculty_count > 0 ) {
	    switch( faculty_res.report_det_mode ) {
	    case REPORT_MODE2_STD:
		facultyPtr->disp_detail_std(refreshFlag);
		break;
	    }
	}
    }
    last_faculty_count = cur_dept_ptr->faculty_array.faculty_count;

    if( report_type==REPORT_RETIRE ) {
	if( refreshFlag == INFO_REPAINT ) {
	    switch( faculty_res.report_det_mode ) {
	    case REPORT_MODE2_STD:
		facultyPtr->disp_detail_std(refreshFlag);
		break;
	    }

	    //			user_interface.darken(ZOOM_X1, ZOOM_Y1, ZOOM_X2, ZOOM_Y2);
	    user_interface.darken(ZOOM_X1, ZOOM_Y1, ZOOM_X2, ZOOM_Y2);
	    info.disp_column_bitmap(&vga_back);
	    user_interface.bar(200,200,600,400,V_WHITE);
	    user_interface.brighten(200,200,600,400);
	    user_interface.rect(200,200,600,400);

	    button_retire_offer.create_text(250,370,400,390,"Make offer",1);
	    button_retire_offer.paint();
	    button_retire_cancel.create_text(450,370,550,390,"Cancel",1);
	    button_retire_cancel.paint();

	    font_chartsm.put(260,220,"How much would you offer to ");
	    font_chart_blue_sm.put(430,220,facultyPtr->name());
	    font_chartsm.put(260,240,"for retirement?");

	    //			retire_spinner.init(260, 275, 360, 305, &spinner1, 25.0, 300.0, 5.0,0,NULL,23);
	    if ( facultyPtr->rank_level == LONG_TERM_ADJUNCT ) {
		int yearCount  = (info.game_date-facultyPtr->start_teaching_date) / 365;
		int monthCount = ((info.game_date-facultyPtr->start_teaching_date) % 365) / 30;
		int remainYear;

		if ( monthCount )
		    remainYear = 5-yearCount%5-1;
		else
		    remainYear = 5-yearCount%5;

		int x = remainYear;

		if ( spinner1 != (float)x*10 )
		    spinner1 = (float)x*10;
	    }
	    else {
		spinner1 = 100.0;
	    }

	    //## chea 230999
	    retire_spinner.init(260, 275, 360, 305, &spinner1, 10.0, 300.0, 5.0,0,NULL,25);
	    retire_spinner.paint();
	    font_chartsm.put(380,285,"of annual salary");
	    font_chart_blue_sm.put(480,285,m.format(facultyPtr->salary,2));

	    font_chartsm.put(260,315,"=");
	    offerDollar=(int)(facultyPtr->salary*(*(retire_spinner.var_ptr))/100);
	    //			font_chart_blue_sm.put(270,315,m.format(offerDollar,1));  //## chea 230999  don't why this is here
	    //			font_chart_blue_sm.put(270,315,m.format(offerDollar,2));  //## chea 230999  don't why this is here
	    //			retire_result_txt.put(280,315,&offerDollar,1);
	    //## chea 230999
	    retire_result_txt.put(280,315,&offerDollar,2);
	}
	else {
	    offerDollar=(int)(facultyPtr->salary*(*(retire_spinner.var_ptr))/100);
	    retire_spinner.refresh();
	    retire_result_txt.refresh();
	}
    }
    vga.blt_buf(ZOOM_X1, ZOOM_Y1, ZOOM_X2, ZOOM_Y2);
}
Example #9
0
void Text::RefreshSizeWrap()
{
    RemoveAllChildren();
    m_Lines.clear();

    stl::vector<Gwen::String> words;
    SplitWords( GetText().Get(), ' ', words );

    // Adding a bullshit word to the end simplifies the code below
    // which is anything but simple.
    words.push_back( "" );

    if ( !GetFont() )
    {
        Debug::AssertCheck( 0, "Text::RefreshSize() - No Font!!\n" );
        return;
    }

    Point pFontSize = GetSkin()->GetRender()->MeasureText( GetFont(), " " );

    int w = GetParent()->Width();
    int x = 0, y = 0;

    Gwen::String strLine;

    stl::vector<Gwen::String>::iterator it = words.begin();
    for (; it != words.end(); ++it )
    {
        bool bFinishLine = false;
        //bool bWrapped = false;

        // If this word is a newline - make a newline (we still add it to the text)
        if ( (*it).c_str()[0] == '\n' ) bFinishLine = true;

        // Does adding this word drive us over the width?
        {
            strLine += (*it);
            Gwen::Point p = GetSkin()->GetRender()->MeasureText( GetFont(), strLine );
            if ( p.x > Width() ) {
                bFinishLine = true; /*bWrapped = true;*/
            }
        }

        // If this is the last word then finish the line
        // if ( --words.end() == it )
        // NOTE: replaced above commented out 'if' statement with this to appease
        //       the GCC compiler that comes with Marmalade SDK 6.0
        stl::vector<Gwen::String>::iterator temp = words.end() - 1;
        if ( temp == it )
        {
            bFinishLine = true;
        }

        if ( bFinishLine )
        {
            Text* t = new Text( this );
            t->SetFont( GetFont() );
            t->SetString( strLine.substr( 0, strLine.length() - (*it).length() ) );
            t->RefreshSize();
            t->SetPos( x, y );
            m_Lines.push_back( t );

            // newline should start with the word that was too big
            strLine = *it;

            // Position the newline
            y += pFontSize.y;
            x = 0;

            //if ( strLine[0] == ' ' ) x -= pFontSize.x;
        }

    }

    // Size to children height and parent width
    {
        Point childsize = ChildrenSize();
        SetSize( w, childsize.y );
    }

    InvalidateParent();
    Invalidate();
}
Example #10
0
/**
 * Initializes all the elements in the Mod Options window.
 * @param game Pointer to the core game.
 * @param origin Game section that originated this state.
 */
OptionsModsState::OptionsModsState(OptionsOrigin origin) : OptionsBaseState(origin)
{
	setCategory(_btnMods);

	// Create objects
	_txtMaster = new Text(114, 9, 94, 8);
	_cbxMasters = new ComboBox(this, 218, 16, 94, 18);
	_lstMods = new TextList(200, 104, 94, 40);

	add(_txtMaster, "text", "modsMenu");
	add(_lstMods, "optionLists", "modsMenu");
	add(_cbxMasters, "button", "modsMenu");

	centerAllSurfaces();

	// how much room do we need for YES/NO
	Text text = Text(100, 9, 0, 0);
	text.initText(_game->getResourcePack()->getFont("FONT_BIG"), _game->getResourcePack()->getFont("FONT_SMALL"), _game->getLanguage());
	text.setText(tr("STR_YES"));
	int yes = text.getTextWidth();
	text.setText(tr("STR_NO"));
	int no = text.getTextWidth();

	int rightcol = std::max(yes, no) + 2;
	int arrowCol = 25;
	int leftcol = _lstMods->getWidth() - (rightcol + arrowCol);

	// Set up objects
	_txtMaster->setText(tr("STR_GAME_TYPE"));

	// scan for masters
	const std::map<std::string, ModInfo> &modInfos(Options::getModInfos());
	size_t curMasterIdx = 0;
	std::vector<std::wstring> masterNames;
	for (std::vector< std::pair<std::string, bool> >::const_iterator i = Options::mods.begin(); i != Options::mods.end(); ++i)
	{
		std::string modId = i->first;
		ModInfo modInfo = modInfos.find(modId)->second;
		if (!modInfo.isMaster())
		{
			continue;
		}

		if (i->second)
		{
			_curMasterId = modId;
		}
		else if (_curMasterId.empty())
		{
			++curMasterIdx;
		}
		_masters.push_back(&modInfos.at(modId));
		masterNames.push_back(Language::utf8ToWstr(modInfo.getName()));
	}

	_cbxMasters->setOptions(masterNames);
	_cbxMasters->setSelected(curMasterIdx);
	_cbxMasters->onChange((ActionHandler)&OptionsModsState::cbxMasterChange);
	_cbxMasters->onMouseIn((ActionHandler)&OptionsModsState::txtTooltipIn);
	_cbxMasters->onMouseOut((ActionHandler)&OptionsModsState::txtTooltipOut);
	_cbxMasters->onMouseOver((ActionHandler)&OptionsModsState::cbxMasterHover);
	_cbxMasters->onListMouseIn((ActionHandler)&OptionsModsState::txtTooltipIn);
	_cbxMasters->onListMouseOut((ActionHandler)&OptionsModsState::txtTooltipOut);
	_cbxMasters->onListMouseOver((ActionHandler)&OptionsModsState::cbxMasterHover);

	_lstMods->setArrowColumn(leftcol + 1, ARROW_VERTICAL);
	_lstMods->setColumns(3, leftcol, arrowCol, rightcol);
	_lstMods->setAlign(ALIGN_RIGHT, 1);
	_lstMods->setSelectable(true);
	_lstMods->setBackground(_window);
	_lstMods->setWordWrap(true);
	_lstMods->onMouseClick((ActionHandler)&OptionsModsState::lstModsClick);
	_lstMods->onLeftArrowClick((ActionHandler)&OptionsModsState::lstModsLeftArrowClick);
	_lstMods->onRightArrowClick((ActionHandler)&OptionsModsState::lstModsRightArrowClick);
	_lstMods->onMousePress((ActionHandler)&OptionsModsState::lstModsMousePress);
	_lstMods->onMouseIn((ActionHandler)&OptionsModsState::txtTooltipIn);
	_lstMods->onMouseOut((ActionHandler)&OptionsModsState::txtTooltipOut);
	_lstMods->onMouseOver((ActionHandler)&OptionsModsState::lstModsHover);
	lstModsRefresh(0);
}
Example #11
0
bool CMainUIFight::onInit()
{
	do 
	{
		BREAK_IF(!GameUIWithOutSideTouchEvent::onInit());
		//左上 左下 右上 右下 四个面板
		m_panelLT = (Layout*)Helper::seekWidgetByName(m_pWidget,"LeftTop");
		m_panelRT = (Layout*)Helper::seekWidgetByName(m_pWidget,"RightTop");
		m_panelLB = (Layout*)Helper::seekWidgetByName(m_pWidget,"LeftBottom");
		m_panelRB = (Layout*)Helper::seekWidgetByName(m_pWidget,"RightBottom");
		BREAK_IF( !(m_panelLT&&m_panelLB&&m_panelRT&&m_panelRB) );

		//修正上下左右panel位置
		//float fRatio = gDirector->getVisibleSize().height / gDirector->getVisibleSize().width;
		//float fNewHeight = fRatio * UI_ORIG_SIZE.width;
		//if (fNewHeight > UI_ORIG_SIZE.height)
		//{
		//	float fOffsetY = (fNewHeight -UI_ORIG_SIZE.height) / 2;
		//	m_panelLT->setPositionY(m_panelLT->getPositionY() + fOffsetY);
		//	m_panelRT->setPositionY(m_panelRT->getPositionY() + fOffsetY);
		//	m_panelLB->setPositionY(m_panelLB->getPositionY() - fOffsetY);
		//	m_panelRB->setPositionY(m_panelRB->getPositionY() - fOffsetY);
		//}
		m_buffListView = (ListView*)Helper::seekWidgetByName(m_pWidget,"buffListView");
		BREAK_IF( !m_buffListView );
		//m_buffListView->setItemsMargin(0.1);

		//玩家头像
		m_HeadIcon = (ImageView*)Helper::seekWidgetByName(m_pWidget,"HeadBtn");
		m_HeroLv = (Text*)Helper::seekWidgetByName(m_pWidget,"Lv");
		m_HeroHp = (Text*)Helper::seekWidgetByName(m_pWidget,"HpValue");
		m_HeroMp = (Text*)Helper::seekWidgetByName(m_pWidget,"MpValue");
		m_HeroHpBar = (Layout*)Helper::seekWidgetByName(m_pWidget,"HpBarFrame");
		m_HeroMpBar = (Layout*)Helper::seekWidgetByName(m_pWidget,"MpBarFrame");
		m_HeroHpSlot = (ImageView*)Helper::seekWidgetByName(m_pWidget,"Img_hp");
		m_HeroMpSlot = (ImageView*)Helper::seekWidgetByName(m_pWidget,"Img_mp");
		m_HeroName = (Text*)Helper::seekWidgetByName(m_pWidget,"Name");
		BREAK_IF( !(m_HeroLv&&m_HeroHp&&m_HeroMp&&m_HeroHpBar&&m_HeroMpBar&&m_HeroHpSlot&&m_HeroMpSlot&&m_HeadIcon&&m_HeroName));
		m_HeroHpBar->setClippingEnabled(true);
		m_HeroMpBar->setClippingEnabled(true);
		m_HeadIcon->addTouchEventListener(this,toucheventselector(CMainUIFight::clickHead));

		CheckBox*	pCheckBox = (CheckBox*)(Helper::seekWidgetByName(m_pWidget,"PlayMode"));
		Text*	pMyScore = (Text*)(Helper::seekWidgetByName(m_pWidget,"Label_43"));
		Text*	pEnemyScore = (Text*)(Helper::seekWidgetByName(m_pWidget,"Label_43_0"));
		pCheckBox->setEnabled(false);
		pMyScore->setEnabled(false);
		pEnemyScore->setEnabled(false);

		//摇杆
		m_JoyStick = (ImageView*)Helper::seekWidgetByName(m_pWidget,"JoyStick");
		BREAK_IF( !m_JoyStick );
		m_JoyStick->setTouchEnabled(true);
		m_JoyStick->addTouchEventListener(this,toucheventselector(CMainUIFight::ClickJoyStick));

		//技能栏
		InitSkillBtns();

		//队伍
		for (int i=0; i<Team_Max_Num; ++i)
		{
			m_TeamHead[i].ui = Helper::seekWidgetByName(m_pWidget,CCString::createWithFormat("Team_%d",i)->getCString());
			m_TeamHead[i].ui->setEnabled(false);
			m_TeamHead[i].icon = (ImageView*)Helper::seekWidgetByName(m_pWidget,CCString::createWithFormat("TeamIcon_%d",i)->getCString());
			m_TeamHead[i].Txtleave = (Text*)Helper::seekWidgetByName(m_pWidget,CCString::createWithFormat("Leave_%d",i)->getCString());
			m_TeamHead[i].progress = ProgressTimer::create(Sprite::create(team_head_cd_path));
			BREAK_IF( !(m_TeamHead[i].ui&&m_TeamHead[i].icon&&m_TeamHead[i].progress&&m_TeamHead[i].Txtleave) );
			m_TeamHead[i].ui->addChild(m_TeamHead[i].progress);
			m_TeamHead[i].Txtleave->setLocalZOrder(100);
			m_TeamHead[i].Txtleave->setEnabled(false);
			Size size = m_TeamHead[i].ui->getContentSize();
			m_TeamHead[i].progress->setPosition(Point(size.width/2,size.height/2));
			m_TeamHead[i].progress->setReverseDirection(true);
		}

		//聊天
		m_pChatUI = (Layout*)Helper::seekWidgetByName(m_pWidget,"ChatLayout");
		m_pButtonChat =  (Button*)Helper::seekWidgetByName(m_pWidget,"ChatBtn");
		m_pButtonChat->addTouchEventListener(this,toucheventselector(CMainUIFight::clickChat));

		m_pMsgWind = CScrollMsgForMainUI::create();
		m_pMsgWind->setSize(m_pChatUI->getSize()); 	/*msgWind size 为300*i时,排版合适*/
		m_pMsgWind->setTouchEnabled(false);
		m_pMsgWind->setOpacity(0);
		m_pMsgWind->SetMaxMsgNum(1);
		ChatMainUI *pChatUI = (ChatMainUI*)gGameUILayer->getUI(IDU_CHATMAINUI);
		if (pChatUI)
		{
			m_pMsgWind->SetTouchNameListenner(gGameUILayer->getUI(IDU_CHATMAINUI), (SEL_TouchNameLinkEvent)&ChatMainUI::clickNameLink4MainUI);
			m_pMsgWind->SetTouchItemListenner(gGameUILayer->getUI(IDU_CHATMAINUI), (SEL_TouchItemLinkEvent)&ChatMainUI::clickItemLink4MainUI);
		}
		m_pChatUI->addChild(m_pMsgWind);
		m_pChatUI->setVisible(false);

		//右上 副本
		m_pPvPSmallMap =  Helper::seekWidgetByName(m_panelRT,"PVP_Map");
		BREAK_IF(!(m_pPvPSmallMap));
		m_pPvPSmallMap->setEnabled(false);
		return true;
	} while (0);
	
	return false;
}
Example #12
0
void GameStart() {
	RenderWindow window(VideoMode(MapWidth * SpriteSize, MapHeight * SpriteSize), "Snake");
	Clock clock;
	Game* game;
	NewGame(game);
	Text text = game->game_text->text;

	while (window.isOpen()) //разбить на 3 метода
	{
		float time = clock.getElapsedTime().asSeconds();
		clock.restart();
		game->consts->time_counter += time;

		ProcessEvents(window, game);

		if (game->state == STARTGAME) {
			window.clear();
			text.setCharacterSize(120);
			text.setString("       Snake!\n\nPress 'U' to start!");
			text.setPosition(250, 50);
			window.draw(text);
		}
		else if (game->state == RESTART) {
			DestroyGame(game);
			NewGame(game);
			text = game->game_text->text;
			game->state = PLAY;
		}
		else if (game->state == PAUSE) {
			window.clear();
			Render(window, game);
			text.setCharacterSize(150);
			text.setString("Pause");
			text.setPosition(455, 160);
			window.draw(text);
		}
		else if (game->state == PLAY) {
			while (game->consts->time_counter > game->consts->speed) {
				game->consts->time_counter = 0;

				//Snake movement

				Step(game->snake);

				int snake_draw_counter = SnakeLength(game->snake);

				ProcessCollisions(snake_draw_counter, game);
			}
			Render(window, game);
		}
		else if (game->state == ENDGAME) {
			window.clear();
			text.setCharacterSize(120);
			text.setString("       Score: " + ToString(game->consts->score) + "\n Press 'Esc' to exit\n Press 'R' to restart");
			text.setPosition(170, 28);
			window.draw(text);
		}

		window.display();
	}
	DestroyGame(game);
}
bool UIScrollViewDisableTest::init()
{
    if (UIScene::init())
    {
        Size widgetSize = _widget->getContentSize();

        // Add a label in which the scrollview alert will be displayed
        _displayValueLabel = Text::create("ScrollView Disable Test", "fonts/Marker Felt.ttf", 32);
        _displayValueLabel->setAnchorPoint(Vec2(0.5f, -1.0f));
        _displayValueLabel->setPosition(Vec2(widgetSize.width / 2.0f,
                                              widgetSize.height / 2.0f + _displayValueLabel->getContentSize().height * 1.5f));
        _uiLayer->addChild(_displayValueLabel);

        // Add the alert
        Text* alert = Text::create("ScrollView vertical", "fonts/Marker Felt.ttf", 30);
        alert->setColor(Color3B(159, 168, 176));
        alert->setPosition(Vec2(widgetSize.width / 2.0f, widgetSize.height / 2.0f - alert->getContentSize().height * 3.075f));
        _uiLayer->addChild(alert);

        Layout* root = static_cast<Layout*>(_uiLayer->getChildByTag(81));

        Layout* background = dynamic_cast<Layout*>(root->getChildByName("background_Panel"));

        // Create the scrollview by vertical
        ui::ScrollView* scrollView = ui::ScrollView::create();
        scrollView->setContentSize(Size(280.0f, 100.0f));
        Size backgroundSize = background->getContentSize();
        scrollView->setPosition(Vec2((widgetSize.width - backgroundSize.width) / 2.0f +
                               (backgroundSize.width - scrollView->getContentSize().width) / 2.0f,
                               (widgetSize.height - backgroundSize.height) / 2.0f +
                               (backgroundSize.height - scrollView->getContentSize().height) / 2.0f));
        scrollView->setScrollBarWidth(4);
        scrollView->setTouchEnabled(false);
        scrollView->setScrollBarPositionFromCorner(Vec2(2, 2));
        scrollView->setScrollBarColor(Color3B::WHITE);
        _uiLayer->addChild(scrollView);

        ImageView* imageView = ImageView::create("cocosui/ccicon.png");

        float innerWidth = scrollView->getContentSize().width;
        float innerHeight = scrollView->getContentSize().height + imageView->getContentSize().height;

        scrollView->setInnerContainerSize(Size(innerWidth, innerHeight));

        Button* button = Button::create("cocosui/animationbuttonnormal.png", "cocosui/animationbuttonpressed.png");
        button->setPosition(Vec2(innerWidth / 2.0f, scrollView->getInnerContainerSize().height - button->getContentSize().height / 2.0f));
        scrollView->addChild(button);

        Button* titleButton = Button::create("cocosui/backtotopnormal.png", "cocosui/backtotoppressed.png");
        titleButton->setTitleText("Title Button");
        titleButton->setPosition(Vec2(innerWidth / 2.0f, button->getBottomBoundary() - button->getContentSize().height));
        scrollView->addChild(titleButton);

        Button* button_scale9 = Button::create("cocosui/button.png", "cocosui/buttonHighlighted.png");
        button_scale9->setScale9Enabled(true);
        button_scale9->setContentSize(Size(100.0f, button_scale9->getVirtualRendererSize().height));
        button_scale9->setPosition(Vec2(innerWidth / 2.0f, titleButton->getBottomBoundary() - titleButton->getContentSize().height));
        scrollView->addChild(button_scale9);

        imageView->setPosition(Vec2(innerWidth / 2.0f, imageView->getContentSize().height / 2.0f));
        scrollView->addChild(imageView);


        return true;
    }

    return false;
}
bool UIScrollViewNestTest::init()
{
    if (UIScene::init())
    {
        Size widgetSize = _widget->getContentSize();
        
        // Add a label in which the scrollview alert will be displayed
        _displayValueLabel = Text::create("Move by vertical direction", "fonts/Marker Felt.ttf", 32);
        _displayValueLabel->setAnchorPoint(Vec2(0.5f, -1.0f));
        _displayValueLabel->setPosition(Vec2(widgetSize.width / 2.0f,
                                             widgetSize.height / 2.0f + _displayValueLabel->getContentSize().height * 1.5f));
        _uiLayer->addChild(_displayValueLabel);
        
        // Add the alert
        Text* alert = Text::create("ScrollView vertical", "fonts/Marker Felt.ttf", 30);
        alert->setColor(Color3B(159, 168, 176));
        alert->setPosition(Vec2(widgetSize.width / 2.0f, widgetSize.height / 2.0f - alert->getContentSize().height * 3.075f));
        _uiLayer->addChild(alert);
        
        Layout* root = static_cast<Layout*>(_uiLayer->getChildByTag(81));
        
        Layout* background = dynamic_cast<Layout*>(root->getChildByName("background_Panel"));
        
        // Create the scrollview by vertical
        ui::ScrollView* scrollView = ui::ScrollView::create();
        scrollView->setContentSize(Size(280.0f, 150.0f));
        scrollView->setDirection(ui::ScrollView::Direction::VERTICAL);
		scrollView->setScrollBarPositionFromCorner(Vec2(4, 4));
        Size backgroundSize = background->getContentSize();
        scrollView->setPosition(Vec2((widgetSize.width - backgroundSize.width) / 2.0f +
                                     (backgroundSize.width - scrollView->getContentSize().width) / 2.0f,
                                     (widgetSize.height - backgroundSize.height) / 2.0f +
                                     (backgroundSize.height - scrollView->getContentSize().height) / 2.0f));
		scrollView->setScrollBarPositionFromCornerForVertical(Vec2(scrollView->getContentSize().width - 4, 4));
		scrollView->setScrollBarColor(Color3B::BLUE);
        _uiLayer->addChild(scrollView);
        
        ImageView* imageView = ImageView::create("cocosui/ccicon.png");
        
        float innerWidth = scrollView->getContentSize().width;
        float innerHeight = scrollView->getContentSize().height + imageView->getContentSize().height;
        
        scrollView->setInnerContainerSize(Size(innerWidth, innerHeight));
        
        Button* button = Button::create("cocosui/animationbuttonnormal.png", "cocosui/animationbuttonpressed.png");
        button->setPosition(Vec2(innerWidth / 2.0f, scrollView->getInnerContainerSize().height - button->getContentSize().height / 2.0f));
        scrollView->addChild(button);
        
        Button* titleButton = Button::create("cocosui/backtotopnormal.png", "cocosui/backtotoppressed.png");
        titleButton->setTitleText("Title Button");
        titleButton->setPosition(Vec2(innerWidth / 2.0f, button->getBottomBoundary() - button->getContentSize().height));
        scrollView->addChild(titleButton);
        
        Button* button_scale9 = Button::create("cocosui/button.png", "cocosui/buttonHighlighted.png");
        button_scale9->setScale9Enabled(true);
        button_scale9->setContentSize(Size(100.0f, button_scale9->getVirtualRendererSize().height));
        button_scale9->setPosition(Vec2(innerWidth / 2.0f, titleButton->getBottomBoundary() - titleButton->getContentSize().height));
        scrollView->addChild(button_scale9);
        
        imageView->setPosition(Vec2(innerWidth / 2.0f, imageView->getContentSize().height / 2.0f));
        scrollView->addChild(imageView);
        
        
        
        // Create the scrollview by both
        ui::ScrollView* sc = ui::ScrollView::create();
        sc->setBackGroundColor(Color3B::GREEN);
        sc->setBackGroundColorType(Layout::BackGroundColorType::SOLID);
        sc->setBounceEnabled(true);
        sc->setDirection(ui::ScrollView::Direction::BOTH);
        sc->setInnerContainerSize(Size(480, 320));
        sc->setContentSize(Size(100,100));
        sc->setPropagateTouchEvents(false);
        sc->setPosition(Vec2(180,100));
        sc->scrollToPercentBothDirection(Vec2(50, 50), 1, true);
		sc->setScrollBarPositionFromCorner(Vec2(4, 4));
        ImageView* iv = ImageView::create("cocosui/Hello.png");
        iv->setPosition(Vec2(240, 160));
        sc->addChild(iv);

        
        scrollView->addChild(sc);
        
        return true;
    }
    
    return false;
}
bool
NetGameClient::DoJoinBacklog(NetJoinAnnounce* join_ann)
{
	bool finished = false;

	if (!join_ann)
	return finished;

	Sim* sim = Sim::GetSim();
	if (!sim)
	return finished;

	DWORD nid       = join_ann->GetNetID();
	DWORD oid       = join_ann->GetObjID();
	Text  name      = join_ann->GetName();
	Text  elem_name = join_ann->GetElement();
	Text  region    = join_ann->GetRegion();
	Point loc       = join_ann->GetLocation();
	Point velocity  = join_ann->GetVelocity();
	int   index     = join_ann->GetIndex();
	int   shld_lvl  = join_ann->GetShield();
	Ship* ship      = 0;
	char  ship_name[128];

	strcpy_s(ship_name, Game::GetText("NetGameClient.no-ship").data());

	if (nid && oid) {
		NetPlayer* remote_player = FindPlayerByObjID(oid);
		if (remote_player) {
			remote_player->SetName(name);
			remote_player->SetObjID(oid);

			if (index > 0)
			sprintf_s(ship_name, "%s %d", elem_name.data(), index);
			else
			sprintf_s(ship_name, "%s", elem_name.data());
		}
		else {
			Element* element = sim->FindElement(elem_name);

			if (element) {
				ship = element->GetShip(index);
			}

			if (ship) {
				strcpy_s(ship_name, ship->Name());

				SimRegion* rgn = ship->GetRegion();
				if (rgn && region != rgn->Name()) {
					SimRegion* dst = sim->FindRegion(region);
					if (dst) dst->InsertObject(ship);
				}

				ship->MoveTo(loc);
				ship->SetVelocity(velocity);

				Shield* shield = ship->GetShield();
				if (shield)
				shield->SetNetShieldLevel(shld_lvl);

				NetPlayer* remote_player = new(__FILE__,__LINE__) NetPlayer(nid);
				remote_player->SetName(name);
				remote_player->SetObjID(oid);
				remote_player->SetShip(ship);

				players.append(remote_player);
				finished = true;

				if (name == "Server A.I. Ship") {
					Print("NetGameClient::DoJoinBacklog() Remote Player '%s' has joined as '%s' with ID %d\n", name.data(), ship_name, oid);
				}
				else {
					HUDView::Message(Game::GetText("NetGameClient.remote-join").data(), name.data(), ship_name);
				}
			}
		}
	}

	return finished;
}
Example #16
0
void copySelectionHelper(Buffer const & buf, Text const & text,
	pit_type startpit, pit_type endpit,
	int start, int end, DocumentClassConstPtr dc, CutStack & cutstack)
{
	ParagraphList const & pars = text.paragraphs();

	// In most of these cases, we can try to recover.
	LASSERT(0 <= start, start = 0);
	LASSERT(start <= pars[startpit].size(), start = pars[startpit].size());
	LASSERT(0 <= end, end = 0);
	LASSERT(end <= pars[endpit].size(), end = pars[endpit].size());
	LASSERT(startpit != endpit || start <= end, return);

	// Clone the paragraphs within the selection.
	ParagraphList copy_pars(boost::next(pars.begin(), startpit),
				boost::next(pars.begin(), endpit + 1));

	// Remove the end of the last paragraph; afterwards, remove the
	// beginning of the first paragraph. Keep this order - there may only
	// be one paragraph!  Do not track deletions here; this is an internal
	// action not visible to the user

	Paragraph & back = copy_pars.back();
	back.eraseChars(end, back.size(), false);
	Paragraph & front = copy_pars.front();
	front.eraseChars(0, start, false);

	ParagraphList::iterator it = copy_pars.begin();
	ParagraphList::iterator it_end = copy_pars.end();

	for (; it != it_end; ++it) {
		// Since we have a copy of the paragraphs, the insets
		// do not have a proper buffer reference. It makes
		// sense to add them temporarily, because the
		// operations below depend on that (acceptChanges included).
		it->setBuffer(const_cast<Buffer &>(buf));
		// PassThru paragraphs have the Language
		// latex_language. This is invalid for others, so we
		// need to change it to the buffer language.
		if (it->isPassThru())
			it->changeLanguage(buf.params(), 
					   latex_language, buf.language());
	}

	// do not copy text (also nested in insets) which is marked as
	// deleted, unless the whole selection was deleted
	if (!isFullyDeleted(copy_pars))
		acceptChanges(copy_pars, buf.params());
	else
		rejectChanges(copy_pars, buf.params());


	// do some final cleanup now, to make sure that the paragraphs
	// are not linked to something else.
	it = copy_pars.begin();
	for (; it != it_end; ++it) {
		it->setBuffer(*static_cast<Buffer *>(0));
		it->setInsetOwner(0);
	}

	cutstack.push(make_pair(copy_pars, dc));
}
void
NetGameClient::DoElemCreate(NetMsg* msg)
{
	if (!msg) return;

	NetElemCreate elem_create;
	elem_create.Unpack(msg->Data());

	const char* elem_name = elem_create.GetName().data();

	::Print("NetGameClient::DoElemCreate name: %s iff: %d type %s\n",
	elem_name,
	elem_create.GetIFF(),
	Mission::RoleName(elem_create.GetType()));

	Sim*     sim   = Sim::GetSim();
	Element* elem  = sim->FindElement(elem_name);
	if (elem) {
		::Print("  element '%' already exists - ignored\n", elem_name);
		return;
	}

	elem = sim->CreateElement(elem_name,
	elem_create.GetIFF(),
	elem_create.GetType());

	int*     load     = elem_create.GetLoadout();
	int*     slots    = elem_create.GetSlots();
	int      squadron = elem_create.GetSquadron();
	int      code     = elem_create.GetObjCode();
	Text     target   = elem_create.GetObjective();
	bool     alert    = elem_create.GetAlert();
	bool     active   = elem_create.GetInFlight();

	elem->SetIntelLevel(elem_create.GetIntel());
	elem->SetLoadout(load);

	if (code > Instruction::RTB || target.length() > 0) {
		Instruction* obj  = new(__FILE__,__LINE__) Instruction(code, target);
		elem->AddObjective(obj);
	}

	Ship* carrier = sim->FindShip(elem_create.GetCarrier());
	if (carrier) {
		elem->SetCarrier(carrier);

		Hangar* hangar = carrier->GetHangar();
		if (hangar) {
			Text squadron_name = hangar->SquadronName(squadron);
			elem->SetSquadron(squadron_name);

			if (active) {
				for (int i = 0; i < 4; i++) {
					int slot = slots[i];
					if (slot > -1) {
						hangar->GotoActiveFlight(squadron, slot, elem, load);
					}
				}
			}

			else {
				FlightDeck* deck   = 0;
				int         queue  = 1000;

				for (int i = 0; i < carrier->NumFlightDecks(); i++) {
					FlightDeck* d = carrier->GetFlightDeck(i);

					if (d && d->IsLaunchDeck()) {
						int dq = hangar->PreflightQueue(d);

						if (dq < queue) {
							queue = dq;
							deck  = d;
						}
					}
				}

				for (int i = 0; i < 4; i++) {
					int slot = slots[i];
					if (slot > -1) {
						hangar->GotoAlert(squadron, slot, deck, elem, load, !alert);
					}
				}
			}
		}
	}
}
Example #18
0
/**
 * Converts this object to the corresponding SBML object.
 */
Text* CLText::toSBML(unsigned int level, unsigned int version) const
{
  Text* pText = new Text(level, version);
  this->addSBMLAttributes(pText);
  RelAbsVector* pV1 = this->mX.toSBML();
  RelAbsVector* pV2 = this->mY.toSBML();
  RelAbsVector* pV3 = this->mZ.toSBML();
  pText->setCoordinates(*pV1, *pV2, *pV3);
  delete pV1;
  delete pV2;
  delete pV3;
  pV1 = this->mFontSize.toSBML();
  pText->setFontSize(*pV1);
  delete pV1;
  pText->setFontFamily(this->getFontFamily());
  pText->setText(this->getText());

  switch (this->getFontWeight())
    {
      case CLText::WEIGHT_UNSET:
        pText->setFontWeight(Text::WEIGHT_UNSET);
        break;

      case CLText::WEIGHT_BOLD:
        pText->setFontWeight(Text::WEIGHT_BOLD);
        break;

      default:
        pText->setFontWeight(Text::WEIGHT_NORMAL);
        break;
    }

  switch (this->getFontStyle())
    {
      case CLText::STYLE_UNSET:
        pText->setFontStyle(Text::STYLE_UNSET);
        break;

      case CLText::STYLE_ITALIC:
        pText->setFontStyle(Text::STYLE_ITALIC);
        break;

      default:
        pText->setFontStyle(Text::STYLE_NORMAL);
        break;
    }

  switch (this->getTextAnchor())
    {
      case CLText::ANCHOR_UNSET:
        pText->setTextAnchor(Text::ANCHOR_UNSET);
        break;

      case CLText::ANCHOR_END:
        pText->setTextAnchor(Text::ANCHOR_END);
        break;

      case CLText::ANCHOR_MIDDLE:
        pText->setTextAnchor(Text::ANCHOR_MIDDLE);
        break;

      default:
        pText->setTextAnchor(Text::ANCHOR_START);
        break;
    }

  switch (this->getVTextAnchor())
    {
      case CLText::ANCHOR_UNSET:
        pText->setVTextAnchor(Text::ANCHOR_UNSET);
        break;

      case CLText::ANCHOR_BOTTOM:
        pText->setVTextAnchor(Text::ANCHOR_BOTTOM);
        break;

      case CLText::ANCHOR_MIDDLE:
        pText->setVTextAnchor(Text::ANCHOR_MIDDLE);
        break;

      default:
        pText->setVTextAnchor(Text::ANCHOR_TOP);
        break;
    }

  return pText;
}
Example #19
0
void GamePromptCenter::addNormalText(const string& msg)
{
	Text* pText = NULL;
	if( m_normalTextCache.size() > 0 )
	{
		pText = m_normalTextCache.front();
		m_normalTextCache.pop();
	}
	else
	{
		pText = Text::create();
		if ( pText )
		{
			m_pNormal->addChild(pText);
		}
	}

	if ( pText )
	{
		pText->setAnchorPoint(Point(0,0));
		pText->setTextHorizontalAlignment(TextHAlignment::LEFT);
		pText->setFontSize(14);
		pText->setColor(Color3B(155,10,10));
		pText->setColor(Color3B::WHITE);
		pText->setText(msg);
		pText->setVisible(true);

		m_normalText.push_back(make_pair(pText,0.0f));

		// 所有提示信息往上顶
		for ( size_t i = 0; i<m_normalText.size(); ++i )
		{
			float deltaX = 0.0f;
			float deltaY = 0.0f;

			Size tsize = pText->getSize();
			deltaY = (m_normalText.size()-i-1)*tsize.height;

			Text* pTextReady = m_normalText[i].first;
			if ( pTextReady )
			{
				pTextReady->setPosition(Point(deltaX,deltaY));
			}
		}
	}

	while (m_normalText.size() > 5)
	{
		popNormalText();
	}
}
Example #20
0
/**
 * Constructor to generate object from the corresponding SBML object.
 */
CLText::CLText(const Text& source, CCopasiContainer* pParent):
  CLGraphicalPrimitive1D(source),
  CCopasiObject("RenderText", pParent),
  mX(source.getX()),
  mY(source.getY()),
  mZ(source.getZ()),
  mFontFamily(source.getFontFamily()),
  mFontSize(source.getFontSize()),
  mText(source.getText()),
  mKey("")
{
  this->mKey = CCopasiRootContainer::getKeyFactory()->add("RenderText", this);

  switch (source.getFontWeight())
    {
      case Text::WEIGHT_UNSET:
        this->setFontWeight(CLText::WEIGHT_UNSET);
        break;

      case Text::WEIGHT_BOLD:
        this->setFontWeight(CLText::WEIGHT_BOLD);
        break;

      default:
        this->setFontWeight(CLText::WEIGHT_NORMAL);
        break;
    }

  switch (source.getFontStyle())
    {
      case Text::STYLE_UNSET:
        this->setFontStyle(CLText::STYLE_UNSET);
        break;

      case Text::STYLE_ITALIC:
        this->setFontStyle(CLText::STYLE_ITALIC);
        break;

      default:
        this->setFontStyle(CLText::STYLE_NORMAL);
        break;
    }

  switch (source.getTextAnchor())
    {
      case Text::ANCHOR_UNSET:
        this->setTextAnchor(CLText::ANCHOR_UNSET);
        break;

      case Text::ANCHOR_END:
        this->setTextAnchor(CLText::ANCHOR_END);
        break;

      case Text::ANCHOR_MIDDLE:
        this->setTextAnchor(CLText::ANCHOR_MIDDLE);
        break;

      default:
        this->setTextAnchor(CLText::ANCHOR_START);
        break;
    }

  switch (source.getVTextAnchor())
    {
      case Text::ANCHOR_UNSET:
        this->setVTextAnchor(CLText::ANCHOR_UNSET);
        break;

      case Text::ANCHOR_BOTTOM:
        this->setVTextAnchor(CLText::ANCHOR_BOTTOM);
        break;

      case Text::ANCHOR_MIDDLE:
        this->setVTextAnchor(CLText::ANCHOR_MIDDLE);
        break;

      default:
        this->setVTextAnchor(CLText::ANCHOR_TOP);
        break;
    }
}
Example #21
0
void NeuralNetwork::read(TextFileReader const& _file) throw()
{
	TextFileReader file = _file;
	
	Text text;
	int line = 0;
	int numLayers = -1;
	float learnRate, actFuncOffset;
	
	IntArray nodes;
	
	while(file.isEof() == false)
	{
		text = file.readLine();
		
		if(line == 0)
		{
			// should be the format/version string
			if(text.contains("NeuralNetworkSimple:v1") == false)
			{
				printf("NeuralNetwork::read wrong version type\n");
				return;
			}
		}
		else if(line == 1)
		{
			// should be learn rate and act func offset			
			sscanf(text.getArray(), "learnRate: %f actFuncOffset: %f", &learnRate, &actFuncOffset);
		}
		else if(line == 2)
		{
			// should be the number of layers			
			sscanf(text.getArray(), "Layers:%d", &numLayers);
			
			if(numLayers < 2) 
			{
				printf("NeuralNetwork::read invalid number of layers\n");
				return;
			}
			
			nodes = IntArray::withSize(numLayers, false);
		}
		else if(numLayers > 0)
		{
			int layer, numNodes;
			sscanf(text.getArray(), "Layer %d:%d", &layer, &numNodes);
			numLayers--;
			
			nodes[layer] = numNodes;
			
			if(numLayers == 0)
			{				
				if(nodes == getStructure())
				{
					setLearnRate(learnRate);
					setActFuncOffset(actFuncOffset);
				}
				else
				{
					setInternal(new NeuralNetworkSimpleInternal(nodes, learnRate, actFuncOffset));
				}
			}
		}
		else
		{
			// it's a weight or a threshold
			int layer, node, index;
			float value;
			sscanf(text.getArray(), "%d %d %d %f", &layer, &node, &index, &value);
			
			if(index < 0)
				setThreshold(layer, node, value);
			else
				setWeight(layer, node, index, value);
		}
		
		line++;
	}		
}
Example #22
0
Text replace(Text tokens, 
             const std::vector<std::size_t> &spans,
             const MapNgrams &map_words){
    
    if (tokens.size() == 0) return {}; // return empty vector for empty text
    
    unsigned int filler = UINT_MAX; // use largest limit as filler
    bool match = false;
    for (std::size_t span : spans) { // substitution starts from the longest sequences
        if (tokens.size() < span) continue;
        for (std::size_t i = 0; i < tokens.size() - (span - 1); i++){
            Ngram ngram(tokens.begin() + i, tokens.begin() + i + span);
            auto it = map_words.find(ngram);
            if (it != map_words.end()) {
                //unsigned int id = map_words[ngram];
                //if (id) {
                match = true;
                std::fill(tokens.begin() + i + 1, tokens.begin() + i + span, filler); // fill subsequent tokens
                tokens[i] = it->second;
            }
        }
    }
    if (match) tokens.erase(std::remove(tokens.begin(), tokens.end(), filler), tokens.end());
    return tokens;
}
Example #23
0
GameSettings::GameSettings()
	: Panel("GameSettings", (GameControl::Get()->Width() - WIDTH)/2, 
	(GameControl::Get()->Height() - getHeight())/2,
						  WIDTH, getHeight())
{
	SetModal();
	SetToolTip(TIP_GAMESETTINGS);

	gameSettings = this;
	listSuspend = listESC = listMotion = NULL;
	editViewSafeMargin = NULL;
	gamePort = gameID = NULL;
	listAutoStartNetwork = listGameServer = NULL;

	Text *text;
	Button *button;	
	int y, editSize = 40, editStart = 22;

	if(!Tutorial::IsCompatible(VERSION_OUT_OF_VISION_OPTIMIZATION))
	{
		editSize = 45;
		editStart = 8;
	}

	//Title
	text = AddText("Game Properties", CENTER_TEXT, 5);
	y = DrawHLine(text->Down() + 2);

	//Body
	text = AddText("Game resolution: ", 10, y);
	listRes = AddListPop(text->Right(), text->Top(), 128, 0, LS_RES); listRes->SetToolTip(TIP_GAMESETTINGS_RESOLUTION);

	editX = AddEditBox(listRes->Right() + editStart, listRes->Top(), editSize); editX->SetNumeric(2, 2000, 1);
	text = AddText("x", editX->Right()+1, editX->Top());
	editY = AddEditBox(text->Right() + 4, text->Top(), editSize); editY->SetNumeric(2, 2000, 1);

	text = AddText("Mode:            ", 10, editY->Down() + 4);
	listFull = AddListPop(text->Right(), text->Top(), 128, 0, LS_FULL); listFull->SetToolTip(TIP_GAMESETTINGS_MODE);

	if(Tutorial::IsCompatible(VERSION_OUT_OF_VISION_OPTIMIZATION))
	{
		text = AddText(" Safe margin: ", listFull->Right(), listFull->Top());
		editViewSafeMargin = AddEditBox(editY->Left(), text->Top(), editSize); editViewSafeMargin->SetNumeric(0, 2000, 1);
	}

	text = AddText("Frame rate:      ", 10, listFull->Down() + 4);
	editFps = AddEditBox(text->Right(), text->Top(), 50); editFps->SetNumeric(1, 512, 1);
	text = AddText("fps", editFps->Right() + 2, editFps->Top());

	listMouse = AddListPop(text->Right() + 32, text->Top(), 128, 0, LS_MOUSE); listMouse->SetToolTip(TIP_GAMESETTINGS_MOUSE);

	if(Tutorial::IsCompatible(VERSION_OUT_OF_VISION_OPTIMIZATION))
	{
		text = AddText("Suspend game if lost focus: ", 10, editFps->Down() + 6);
		listSuspend = AddListPop(text->Right() + 48, text->Top(), 32, 0, LS_SUSPEND); listSuspend->SetToolTip(TIP_GAMESETTINGS_SUSPEND);

		if(Tutorial::IsCompatible(VERSION_ESC_TO_EXIT))
		{
			text = AddText("  Use ESC key to exit game: ", 10, listSuspend->Down() + 6);
			listESC = AddListPop(text->Right() + 48, text->Top(), 32, 0, LS_ESC); listESC->SetToolTip(TIP_GAMESETTINGS_ESC);

			text = AddText("       Motion Compensation: ", 10, listESC->Down() + 6);
			listMotion = AddListPop(text->Right() + 48, text->Top(), 32, 0, LS_MOTION); listMotion->SetToolTip(TIP_GAMESETTINGS_MOTION_COMPENSATION);
		}
		
		
		y = DrawHLine(text->Down() + 8);
	}
	else
	{
		y = DrawHLine(editFps->Down() + 4);
	}
	
	text = AddText("Audio format: ", 10, y);
	listHz = AddListPop(text->Right(), text->Top(), 128, 0, LS_HZ); listHz->SetToolTip(TIP_GAMESETTINGS_AUDIO_HZ);
	listStereo = AddListPop(listHz->Right() + 4, listHz->Top(), 128, 0, LS_STEREO); listStereo->SetToolTip(TIP_GAMESETTINGS_AUDIO_STEREO);
	text = AddText("Maximum number of simultaneous sounds: ", 10, listStereo->Down()+4);
	editMaxSounds = AddEditBox(text->Right(), text->Top(), 50); editMaxSounds->SetNumeric(1, 512, 1);
	
	y = DrawHLine(editMaxSounds->Down() + 2);

	text = AddText("            Icon file:  ", 10, y + 2);
	iconPath = AddListDirectory(text->Right(), text->Top()); iconPath->SetToolTip(TIP_GAMESETTINGS_ICON);

	text = AddText("           Game title: ", 10, iconPath->Down() + 4);
	gameTitle = AddEditBox(text->Right(), text->Top(), 150);

	text = AddText("Game background color: ", 10, gameTitle->Down() + 4);
	backgroundColor = new ColorSample(this, text->Right(), text->Top(), 32); backgroundColor->SetToolTip(TIP_GAMESETTINGS_BACKGROUNDCOLOR);

	//Network
	if(Tutorial::IsCompatible(VERSION_NETWORK) && GAME_EDITOR_VERSION >= VERSION_NETWORK)
	{
		y = DrawHLine(backgroundColor->Down() + 2);

		text = AddText("     Game ID: ", 10, y);		
		gameID = AddEditBox(text->Right(), text->Top(), 256);

		text = AddText("Network Port: ", 10, gameID->Down() + 4);		
		gamePort = AddEditBox(text->Right(), text->Top(), 64);

		text = AddText("Use Game Editor Server: ", 10, gamePort->Down() + 4);
		listGameServer = AddListPop(text->Right() + 2, text->Top(), 32, 0, LS_GAMESERVER); listGameServer->SetToolTip(TIP_GAMESETTINGS_GAME_SERVER);

		text = AddText("    Auto Start Network: ", 10, listGameServer->Down() + 4);
		listAutoStartNetwork = AddListPop(text->Right() + 2, text->Top(), 32, 0, LS_AUTOSTART_NETWORK); listAutoStartNetwork->SetToolTip(TIP_GAMESETTINGS_AUTO_START_NETWORK);

		y = listAutoStartNetwork->Down() + 2;
	}
	else
	{
		y = backgroundColor->Down() + 2;
	}

	//PocketPC
	y = DrawHLine(y);
	listPocketKeys = AddListPop(10, y, 256, 0, LS_POCKET_KEYS, "Pocket PC and GP2X Keys"); listPocketKeys->SetToolTip(TIP_GAMESETTINGS_POCKET_KEYS);
	
	//Close
	y = DrawHLine(listPocketKeys->Down() + 2);
	button = AddButton("Ok", Width()/2 - 70, y, 0, 0, BT_ADD); SetConfirmButton(button);
	button = AddButton("Cancel", button->Right()+8, y, 0, 0, BT_CLOSE); SetCancelButton(button);


	//Populate resolutions
	char buf[64];
	if(Tutorial::IsOff())
	{
		SDL_Rect **modes;
		const SDL_VideoInfo *vinfo = SDL_GetVideoInfo();
		
		/* Get available fullscreen/hardware modes */
		modes=SDL_ListModes(vinfo->vfmt, VIDEO_FLAGS | SDL_FULLSCREEN);
		
		if(modes != (SDL_Rect **)0 && modes != (SDL_Rect **)-1)
		{		
			for(int i=0;modes[i];++i)
			{
				sprintf(buf, "%d x %d", modes[i]->w, modes[i]->h);
				listRes->AddText(buf);
			}
		}
	}
	else
	{
		//Don't change in different machines
		listRes->AddText("1280 x 1024");
		listRes->AddText("1280 x 960");
		listRes->AddText("1280 x 768");
		listRes->AddText("1280 x 720");
		listRes->AddText("1152 x 864");
		listRes->AddText("1024 x 768");
		listRes->AddText("848 x 480");
		listRes->AddText("800 x 600");
		listRes->AddText("720 x 576");
		listRes->AddText("720 x 480");
		listRes->AddText("640 x 480");
		listRes->AddText("640 x 400");
		listRes->AddText("512 x 384");
		listRes->AddText("480 x 360");
		listRes->AddText("400 x 300");
		listRes->AddText("320 x 240");
		listRes->AddText("320 x 200");		
	}

	if(Tutorial::IsCompatible(VERSION_OUT_OF_VISION_OPTIMIZATION))
	{
		listRes->AddText("240 x 320");
		listRes->AddText("240 x 320 Pocket PC");
		listRes->AddText("240 x 320 Pocket PC Upside down");
		listRes->AddText("320 x 240 Pocket PC Rotate left");
		listRes->AddText("320 x 240 Pocket PC Rotate right");

		listRes->AddText("480 x 640 Pocket PC");
		listRes->AddText("480 x 640 Pocket PC Upside down");
		listRes->AddText("640 x 480 Pocket PC Rotate left");
		listRes->AddText("640 x 480 Pocket PC Rotate right");
		listRes->AddText("800 x 480 Pocket PC Rotate left");
		listRes->AddText("800 x 480 Pocket PC Rotate right");

		//No changes in screen orientation now (don't have the w > h information)
		listRes->AddText("240 x 240 Pocket PC");
		listRes->AddText("480 x 480 Pocket PC");

		//Smartphone
		listRes->AddText("176 x 220 Smartphone");
		listRes->AddText("160 x 240 Smartphone");
		listRes->AddText("208 x 240 Smartphone");
		listRes->AddText("240 x 320 Smartphone");

		//HPC
		listRes->AddText("640 x 240 Handheld PC");
		listRes->AddText("640 x 480 Handheld PC");
		listRes->AddText("800 x 480 Handheld PC");
		listRes->AddText("800 x 600 Handheld PC");

		//GP2X
		listRes->AddText("320 x 240 GP2X");
		listRes->AddText("640 x 480 GP2X");

		// Apple iPhone // AKR
		listRes->AddText("320 x 480 iPhone");
		listRes->AddText("480 x 320 iPhone Rotate left");

		// Apple iPad // AKR
		listRes->AddText("768 x 1024 iPad");
		listRes->AddText("1024 x 768 iPad Rotate left");

	}
	else
	{
		listRes->AddText("240 x 320 Pocket PC");
	}

	listFull->AddText("Full screen");
	listFull->AddText("Window");


	listHz->AddText("44100 Hz");
	listHz->AddText("22050 Hz");
	listHz->AddText("11025 Hz");


	listStereo->AddText("Stereo");
	listStereo->AddText("Mono");

	listMouse->AddText("Show mouse");
	listMouse->AddText("Hide mouse");

	if(listSuspend)
	{
		listSuspend->AddText("Yes");
		listSuspend->AddText("No");
		
		if(GameControl::Get()->getSuspendGameIfLostFocus()) listSuspend->SetItem("Yes");
		else listSuspend->SetItem("No");
	}

	if(listAutoStartNetwork)
	{
		listAutoStartNetwork->AddText("Yes");
		listAutoStartNetwork->AddText("No");
				
		if(GameControl::Get()->getAutoStartNetwork()) listAutoStartNetwork->SetItem("Yes");
		else listAutoStartNetwork->SetItem("No");
	}

	if(listGameServer)
	{
		listGameServer->AddText("Yes");
		listGameServer->AddText("No");
				
		if(GameControl::Get()->getUseGameEditorServer()) listGameServer->SetItem("Yes");
		else listGameServer->SetItem("No");
	}

	if(listESC)
	{
		listESC->AddText("Yes");
		listESC->AddText("No");
		
		if(GameControl::Get()->getUseESCKeyToExit()) listESC->SetItem("Yes");
		else listESC->SetItem("No");
	}

	if(listMotion)
	{
		listMotion->AddText("Yes");
		listMotion->AddText("No");
		
		if(GameControl::Get()->getUseMotionCorrection()) listMotion->SetItem("Yes");
		else listMotion->SetItem("No");
	}

	if(gameID)
	{		
		gameID->SetText(GameControl::Get()->getGameID());
	}

	if(gamePort)
	{		
		gamePort->SetText(GameControl::Get()->getGamePort());
	}


	if(GameControl::Get()->getFullScreen()) listFull->SetItem("Full screen");
	else listFull->SetItem("Window");

	if(GameControl::Get()->getStereo()) listStereo->SetItem("Stereo");
	else listStereo->SetItem("Mono");

	if(GameControl::Get()->getShowMouse()) listMouse->SetItem("Show mouse");
	else listMouse->SetItem("Hide mouse");

	if(editViewSafeMargin)
	{
		editViewSafeMargin->SetText((int)GameControl::Get()->getViewSafeMargin());
	}
	

	sprintf(buf, "%ld Hz", GameControl::Get()->getAudioSamplerRate()); 
	listHz->SetItem(buf);

	sprintf(buf, "%d x %d", GameControl::Get()->getGameWidth(), GameControl::Get()->getGameHeight());
	listRes->SetItem(buf);

	editX->SetText(GameControl::Get()->getGameWidth());
	editY->SetText(GameControl::Get()->getGameHeight());
	editFps->SetText(GameControl::Get()->getFrameRate());
	editMaxSounds->SetText(GameControl::Get()->getMaximumSounds());

	bFlipPocketPCScreen = GameControl::Get()->getFlipPocketPCScreen();

	gedString res(buf);
	if(res == "240 x 320")
	{
		if(bFlipPocketPCScreen)
		{
			listRes->SetText("240 x 320 Up. down");
		}
	}
	else if(res == "320 x 240")
	{
		if(bFlipPocketPCScreen)
		{
			listRes->SetText("320 x 240 Rot.right");
		}
		else
		{
			listRes->SetText("320 x 240 Rot. left");
		}
	}
	else if(res == "480 x 640")
	{
		if(bFlipPocketPCScreen)
		{
			listRes->SetText("480 x 640 Up. down");
		}
		else
		{
			listRes->SetText("480 x 640 Pocket PC");
		}
	}
	else if(res == "640 x 480")
	{
		if(bFlipPocketPCScreen)
		{
			listRes->SetText("640 x 480 Rot.right");
		}
		else
		{
			//listRes->SetText("640 x 480 Rot. left");
			listRes->SetText("640 x 480");
		}
	}
	else if(res == "320 x 480")
	{
			listRes->SetText("320 x 480 iPhone");
	}
	else if(res == "480 x 320")
	{
		listRes->SetText("480 x 320 Rot.left");
	}
	else if(res == "768 x 1024")
	{
			listRes->SetText("768x1024 iPad");
	}
	else if(res == "800 x 480")
	{
		if(bFlipPocketPCScreen)
		{
			listRes->SetText("800 x 480 Rot.right");
		}
		else
		{			
			listRes->SetText("800 x 480");
		}
	}
	else if(res == "240 x 240")
	{
		listRes->SetText("240 x 240 Pocket PC");
	}
	else if(res == "480 x 480")
	{
		listRes->SetText("480 x 480 Pocket PC");
	}
	else if(res == "176 x 220")
	{
		listRes->SetText("176 x 220 Smartphone");
	}
	else if(res == "160 x 240")
	{
		listRes->SetText("160 x 240 Smartphone");
	}
	else if(res == "208 x 240")
	{
		listRes->SetText("208 x 240 Smartphone");
	}



	iconPath->AddFilter("tga");
	iconPath->AddFilter("bmp");
	iconPath->AddFilter("pnm");
	iconPath->AddFilter("xpm");
	iconPath->AddFilter("xcf");
	iconPath->AddFilter("pcx");
	iconPath->AddFilter("gif");
	iconPath->AddFilter("jpg");
	iconPath->AddFilter("jpeg");
	iconPath->AddFilter("jpe");
	iconPath->AddFilter("jfif");
	iconPath->AddFilter("tif");
	iconPath->AddFilter("tiff");
	iconPath->AddFilter("iff");
	iconPath->AddFilter("lbm");
	iconPath->AddFilter("png");
	iconPath->AddFilter("ico");

	//iconPath->SetText(GameControl::Get()->getIconPath());

	if(!GameControl::Get()->getIconPath().empty())
	{
		gedString file, dir;
		SplitPath(GameControl::Get()->getIconPath(), file, dir);
		chdir(dir.c_str());

		iconPath->AddText(file);
		iconPath->SetItem(file);
	}

	gameTitle->SetText(GameControl::Get()->getGameTitle());

	backgroundColor->setColor(GameControl::Get()->getBackGroundColor());

	SetPocketKeys();
}
Example #24
0
void Text::copySpecialProperties(Widget *widget)
{
    Text* label = dynamic_cast<Text*>(widget);
    if (label)
    {
        setFontName(label->_fontName);
        setFontSize(label->getFontSize());
        setTextColor(label->getTextColor());
        setString(label->getString());
        setTouchScaleChangeEnabled(label->_touchScaleChangeEnabled);
        setTextHorizontalAlignment(label->_labelRenderer->getHorizontalAlignment());
        setTextVerticalAlignment(label->_labelRenderer->getVerticalAlignment());
        setTextAreaSize(label->_labelRenderer->getDimensions());
        setContentSize(label->getContentSize());

        LabelEffect effectType = label->getLabelEffectType();
        if (effectType == LabelEffect::GLOW)
        {
            enableGlow(label->getEffectColor());
        }
        else if (effectType == LabelEffect::OUTLINE)
        {
            enableOutline(label->getEffectColor(),label->getOutlineSize());
        }
        if (label->isShadowEnabled())
        {
            enableShadow(label->getShadowColor(),label->getShadowOffset(),label->getShadowBlurRadius());
        }
    }
}
void DiskIn::initWithAudioFile(const char* audioFilePath, 
							   const bool loopFlag, 
							   const double startTime,
							   const UGen::DoneAction doneAction) throw()
{
	Text path; // this needs to be here so it doesn't get garbage collected too early
	
	if(audioFilePath[0] != '/')
	{	
		path = NSUtilities::pathInDirectory(NSUtilities::Bundle, audioFilePath);
		audioFilePath = path.getArray();
	}
	
	OSStatus result;
	UInt32 dataSize;
	
	CFURLRef audioFileURL;
	audioFileURL = CFURLCreateFromFileSystemRepresentation(NULL,
														   (const UInt8*)audioFilePath, 
														   strlen(audioFilePath), 
														   false);
	
	AudioFileID	audioFile = 0;
	result = AudioFileOpenURL (audioFileURL, kAudioFileReadPermission, 0, &audioFile);
	CFRelease(audioFileURL);
	if (result != noErr) 
	{
		printf("DiskIn: error: Could not open file: %s err=%d\n", audioFilePath, (int)result);
		audioFile = 0;
	}
	
	if(audioFile)
	{
		AudioStreamBasicDescription format;
		dataSize = sizeof(format);
		result = AudioFileGetProperty(audioFile, kAudioFilePropertyDataFormat, &dataSize, &format);
		if (result != noErr) 
		{
			printf("DiskIn: error: Could not get data format: %s err=%d\n", audioFilePath, (int)result);
			AudioFileClose(audioFile);
			audioFile = 0;
		}
		else if(format.mFormatID != kAudioFormatLinearPCM)
		{
			printf("DiskIn: error: Only PCM formats supported\\n");
			AudioFileClose(audioFile);
			audioFile = 0;
		}
		else
		{
			if(format.mSampleRate != UGen::getSampleRate())
			{
				printf("DiskIn: warning: Sample rate mismatch - resampling is not yet implemented\\n");
			}
			
			if((format.mFormatFlags & kAudioFormatFlagIsFloat) != 0)
			{
				initInternal(format.mChannelsPerFrame);
				
				if((format.mFormatFlags & kAudioFormatFlagIsBigEndian) != 0)
				{
					generateFromProxyOwner(new DiskInUGenInternalFloatBigEndian(audioFile, 
																				format, 
																				loopFlag, 
																				startTime, 
																				doneAction));
					return;
				}
				else
				{
					generateFromProxyOwner(new DiskInUGenInternalFloatLittleEndian(audioFile, 
																				   format, 
																				   loopFlag, 
																				   startTime, 
																				   doneAction));
					return;
				}
			}
			else if((format.mFormatFlags & kAudioFormatFlagIsBigEndian) != 0)
			{
				// aif and other big edian?
				if(format.mBitsPerChannel == 16)
				{
					initInternal(format.mChannelsPerFrame);
					generateFromProxyOwner(new DiskInUGenInternalAiff16(audioFile, 
																		format, 
																		loopFlag, 
																		startTime, 
																		doneAction));
					return;
				}
				else if(format.mBitsPerChannel == 32)
				{
					initInternal(format.mChannelsPerFrame);
					generateFromProxyOwner(new DiskInUGenInternalAiff32(audioFile, 
																		format, 
																		loopFlag, 
																		startTime, 
																		doneAction));			
					return;
				}
				else if(format.mBitsPerChannel == 24)
				{
					initInternal(format.mChannelsPerFrame);
					generateFromProxyOwner(new DiskInUGenInternalAiff24(audioFile, 
																		format, 
																		loopFlag, 
																		startTime, 
																		doneAction));	
					return;
				}
				else
				{
					printf("DiskIn: error: Sound file format not yet supported.");
					AudioFileClose(audioFile);
					audioFile = 0;
				}
			}
			else
			{
				// wav and other little edian?
				if(format.mBitsPerChannel == 16)
				{
					initInternal(format.mChannelsPerFrame);
					generateFromProxyOwner(new DiskInUGenInternalWav16(audioFile, 
																	   format, 
																	   loopFlag, 
																	   startTime, 
																	   doneAction));
					return;					
				}
				else if(format.mBitsPerChannel == 32)
				{
					initInternal(format.mChannelsPerFrame);
					generateFromProxyOwner(new DiskInUGenInternalWav32(audioFile, 
																	   format, 
																	   loopFlag, 
																	   startTime, 
																	   doneAction));
					return;					
				}
				else if(format.mBitsPerChannel == 24)
				{
					initInternal(format.mChannelsPerFrame);
					generateFromProxyOwner(new DiskInUGenInternalWav24(audioFile, 
																	   format, 
																	   loopFlag, 
																	   startTime, 
																	   doneAction));
					return;					
				}
				else
				{
					printf("DiskIn: error: Sound file format not yet supported.");
					AudioFileClose(audioFile);
					audioFile = 0;
				}
			}
		}
	}
}
void
ComboBox::Draw()
{
	int x = 0;
	int y = 0;
	int w = rect.w;
	int h = rect.h;

	if (w < 1 || h < 1 || !shown)
	return;

	Rect btn_rect(x,y,w,h);

	// draw the bevel:
	DrawRectSimple(btn_rect, button_state);

	// draw the border:
	if (border)
	DrawRect(0,0,w-1,h-1,border_color);

	// draw the arrow:
	POINT arrow[3];
	double h3 = (double)h/3.0;

	arrow[0].x = (int) (w-2*h3);
	arrow[0].y = (int) (h3);
	arrow[1].x = (int) (w-h3);
	arrow[1].y = (int) (h3);
	arrow[2].x = (int) ((arrow[1].x + arrow[0].x)/2);
	arrow[2].y = (int) (2*h3);

	FillPoly(3, arrow, border_color);

	// draw text here:
	Text caption = text;
	if (GetSelectedIndex() >= 0)
	caption = GetSelectedItem();

	if (font && caption.length()) {
		int border_size = 4;

		if (style & WIN_RAISED_FRAME && style & WIN_SUNK_FRAME)
		border_size = 8;

		Rect label_rect = CalcLabelRect();
		int  vert_space = label_rect.h;
		int  horz_space = label_rect.w;

		DrawText(caption.data(), 0, label_rect, DT_CALCRECT | DT_WORDBREAK | text_align);
		vert_space = (vert_space - label_rect.h)/2;
		
		label_rect.w = horz_space;

		if (vert_space > 0)
		label_rect.y += vert_space;

		if (animated && button_state > 0) {
			label_rect.x += button_state;
			label_rect.y += button_state;
		}

		font->SetColor(fore_color);
		DrawText(caption.data(), 0, label_rect, DT_WORDBREAK | text_align);
	}
}
Example #27
0
bool UIListViewTest_Horizontal::init()
{
    if (UIScene::init())
    {
        Size widgetSize = _widget->getContentSize();
        
        _displayValueLabel = Text::create("Move by horizontal direction", "fonts/Marker Felt.ttf", 32);
        _displayValueLabel->setAnchorPoint(Vec2(0.5f, -1.0f));
        _displayValueLabel->setPosition(Vec2(widgetSize.width / 2.0f,
                                              widgetSize.height / 2.0f
                                              + _displayValueLabel->getContentSize().height * 1.5f));
        
        _uiLayer->addChild(_displayValueLabel);
        
        
        Text* alert = Text::create("ListView horizontal", "fonts/Marker Felt.ttf", 30);
        alert->setColor(Color3B(159, 168, 176));
        alert->setPosition(Vec2(widgetSize.width / 2.0f, widgetSize.height / 2.0f - alert->getContentSize().height * 3.075f));
        _uiLayer->addChild(alert);
        
        Layout* root = static_cast<Layout*>(_uiLayer->getChildByTag(81));
        
        Layout* background = static_cast<Layout*>(root->getChildByName("background_Panel"));
        Size backgroundSize = background->getContentSize();
        
        
        // create list view ex data
      
        for (int i = 0; i < 20; ++i)
        {
            std::string ccstr = StringUtils::format("listview_item_%d", i);
            _array.push_back(ccstr);
        }
        
        
        // Create the list view ex
        ListView* listView = ListView::create();
        // set list view ex direction
        listView->setDirection(ui::ScrollView::Direction::HORIZONTAL);
        listView->setTouchEnabled(true);
        listView->setBounceEnabled(true);
        listView->setBackGroundImage("cocosui/green_edit.png");
        listView->setBackGroundImageScale9Enabled(true);
        listView->setContentSize(Size(240, 130));
        listView->setPosition(Vec2((widgetSize.width - backgroundSize.width) / 2.0f +
                                    (backgroundSize.width - listView->getContentSize().width) / 2.0f,
                                    (widgetSize.height - backgroundSize.height) / 2.0f +
                                    (backgroundSize.height - listView->getContentSize().height) / 2.0f));
        listView->addEventListener((ui::ListView::ccListViewCallback)CC_CALLBACK_2(UIListViewTest_Horizontal::selectedItemEvent, this));
		listView->setScrollBarPositionFromCorner(Vec2(7, 7));
        _uiLayer->addChild(listView);
        
        
        // create model
        Button* default_button = Button::create("cocosui/backtotoppressed.png", "cocosui/backtotopnormal.png");
        default_button->setName("Title Button");
        
        Layout *default_item = Layout::create();
        default_item->setTouchEnabled(true);
        default_item->setContentSize(default_button->getContentSize());
        default_button->setPosition(Vec2(default_item->getContentSize().width / 2.0f, default_item->getContentSize().height / 2.0f));
        default_item->addChild(default_button);
        
        // set model
        listView->setItemModel(default_item);
        
        // add default item
        ssize_t count = _array.size();
        for (int i = 0; i < count / 4; ++i)
        {
            listView->pushBackDefaultItem();
        }
        // insert default item
        for (int i = 0; i < count / 4; ++i)
        {
            listView->insertDefaultItem(0);
        }
        
        // add custom item
        for (int i = 0; i < count / 4; ++i)
        {
            Button* custom_button = Button::create("cocosui/button.png", "cocosui/buttonHighlighted.png");
            custom_button->setName("Title Button");
            custom_button->setScale9Enabled(true);
            custom_button->setContentSize(default_button->getContentSize());
            
            Layout* custom_item = Layout::create();
            custom_item->setContentSize(custom_button->getContentSize());
            custom_button->setPosition(Vec2(custom_item->getContentSize().width / 2.0f, custom_item->getContentSize().height / 2.0f));
            custom_item->addChild(custom_button);
            
            listView->pushBackCustomItem(custom_item);
        }
        // insert custom item
        Vector<Widget*>& items = listView->getItems();
        ssize_t items_count = items.size();
        for (int i = 0; i < count / 4; ++i)
        {
            Button* custom_button = Button::create("cocosui/button.png", "cocosui/buttonHighlighted.png");
            custom_button->setName("Title Button");
            custom_button->setScale9Enabled(true);
            custom_button->setContentSize(default_button->getContentSize());
            
            Layout* custom_item = Layout::create();
            custom_item->setContentSize(custom_button->getContentSize());
            custom_button->setPosition(Vec2(custom_item->getContentSize().width / 2.0f, custom_item->getContentSize().height / 2.0f));
            custom_item->addChild(custom_button);
            
            listView->insertCustomItem(custom_item, items_count);
        }
        
        // set item data
        items_count = items.size();
        for (int i = 0; i < items_count; ++i)
        {
            Widget *item = listView->getItem(i);
            Button *button = static_cast<Button*>(item->getChildByName("Title Button"));
            ssize_t index = listView->getIndex(item);
            button->setTitleText(_array[index]);
        }
        // remove last item
        listView->removeLastItem();
        
        // remove item by index
        items_count = items.size();
        listView->removeItem(items_count - 1);        
        
        // set all items layout gravity
        listView->setGravity(ListView::Gravity::CENTER_VERTICAL);
        
        // set items margin
        listView->setItemsMargin(2);
        
        return true;
    }
    
    return false;
}
void
NetGameClient::DoJoinAnnounce(NetMsg* msg)
{
	if (!msg) return;

	Sim* sim = Sim::GetSim();
	if (!sim) return;

	NetJoinAnnounce*  join_ann = new(__FILE__,__LINE__) NetJoinAnnounce;
	bool              saved    = false;

	if (join_ann->Unpack(msg->Data())) {
		DWORD nid       = msg->NetID();
		DWORD oid       = join_ann->GetObjID();
		Text  name      = join_ann->GetName();
		Text  elem_name = join_ann->GetElement();
		Text  region    = join_ann->GetRegion();
		Point loc       = join_ann->GetLocation();
		Point velocity  = join_ann->GetVelocity();
		int   index     = join_ann->GetIndex();
		int   shld_lvl  = join_ann->GetShield();
		join_ann->SetNetID(nid);
		Ship* ship      = 0;
		char  ship_name[128];

		strcpy_s(ship_name, Game::GetText("NetGameClient.no-ship").data());

		if (local_player && player_name == name) {
			HUDView::Message(Game::GetText("NetGameClient.local-accept"), name.data(), local_player->Name());

			objid = oid;
			netid = nid;
			local_player->SetObjID(oid);
			local_player->SetNetObserver(false);
			Observe(local_player);

			SimRegion* rgn = local_player->GetRegion();
			if (rgn && region != rgn->Name()) {
				SimRegion* dst = sim->FindRegion(region);
				if (dst) dst->InsertObject(local_player);
			}

			local_player->MoveTo(loc);
			local_player->SetVelocity(velocity);

			Shield* shield = local_player->GetShield();
			if (shield)
			shield->SetNetShieldLevel(shld_lvl);
		}
		else {
			NetPlayer* remote_player = FindPlayerByObjID(oid);
			if (remote_player) {
				remote_player->SetName(name);
				remote_player->SetObjID(oid);

				if (index > 0)
				sprintf_s(ship_name, "%s %d", elem_name.data(), index);
				else
				sprintf_s(ship_name, "%s", elem_name.data());
			}
			else {
				Element* element = sim->FindElement(elem_name);

				if (element) {
					ship = element->GetShip(index);
				}
				else {
					Print("NetGameClient::DoJoinAnnounce() could not find elem %s for player '%s' objid %d\n",
					elem_name.data(), name.data(), oid);

					NetUtil::SendElemRequest(elem_name.data());
				}

				if (!ship) {
					// save it for later:
					join_backlog.append(join_ann);
					saved = true;
				}
				else {
					strcpy_s(ship_name, ship->Name());

					SimRegion* rgn = ship->GetRegion();
					if (rgn && region != rgn->Name()) {
						SimRegion* dst = sim->FindRegion(region);
						if (dst) dst->InsertObject(ship);
					}

					ship->MoveTo(loc);
					ship->SetVelocity(velocity);

					Shield* shield = ship->GetShield();
					if (shield)
					shield->SetNetShieldLevel(shld_lvl);

					NetPlayer* remote_player = new(__FILE__,__LINE__) NetPlayer(nid);
					remote_player->SetName(name);
					remote_player->SetObjID(oid);
					remote_player->SetShip(ship);

					players.append(remote_player);

					if (name == "Server A.I. Ship") {
						Print("Remote Player '%s' has joined as '%s' with ID %d\n", name.data(), ship_name, oid);
					}
					else {
						HUDView::Message(Game::GetText("NetGameClient.remote-join").data(), name.data(), ship_name);
					}
				}
			}
		}
	}

	if (!saved)
	delete join_ann;
}
Example #29
0
bool Issue8316::init()
{
    if (UIScene::init())
    {
        Size widgetSize = _widget->getContentSize();
        
        auto label = Text::create("Issue 8316", "fonts/Marker Felt.ttf", 32);
        label->setAnchorPoint(Vec2(0.5f, -1.0f));
        label->setPosition(Vec2(widgetSize.width / 2.0f,
                                widgetSize.height / 2.0f + label->getContentSize().height * 1.5f));
        _uiLayer->addChild(label);
        
        
        Text* alert = Text::create("ListView Disable Touch", "fonts/Marker Felt.ttf", 20);
        alert->setColor(Color3B(159, 168, 176));
        alert->setPosition(Vec2(widgetSize.width / 2.0f,
                                widgetSize.height / 2.0f - alert->getContentSize().height * 3.075f));
        _uiLayer->addChild(alert);
        
        Layout* root = static_cast<Layout*>(_uiLayer->getChildByTag(81));
        
        Layout* background = dynamic_cast<Layout*>(root->getChildByName("background_Panel"));
        Size backgroundSize = background->getContentSize();
        
        // Create the list view ex
        ListView* listView = ListView::create();
        // set list view ex direction
        listView->setDirection(ui::ScrollView::Direction::VERTICAL);
        listView->setBounceEnabled(true);
        listView->setTouchEnabled(false);
        listView->setBackGroundImage("cocosui/green_edit.png");
        listView->setBackGroundImageScale9Enabled(true);
        listView->setContentSize(Size(240, 130));
        listView->setPosition(Vec2((widgetSize.width - backgroundSize.width) / 2.0f +
                                   (backgroundSize.width - listView->getContentSize().width) / 2.0f,
                                   (widgetSize.height - backgroundSize.height) / 2.0f +
                                   (backgroundSize.height - listView->getContentSize().height) / 2.0f));
        listView->setScrollBarPositionFromCorner(Vec2(7, 7));
        listView->setClippingEnabled(true);
        listView->setClippingType(ui::Layout::ClippingType::SCISSOR);
        listView->setName("listview1");
        
        {
            Button* default_button = Button::create("cocosui/backtotoppressed.png", "cocosui/backtotopnormal.png");
            default_button->setName("Title Button");
            
            Layout* default_item = Layout::create();
            default_item->setTouchEnabled(true);
            default_item->setContentSize(default_button->getContentSize());
            default_button->setPosition(Vec2(default_item->getContentSize().width / 2.0f,
                                             default_item->getContentSize().height / 2.0f));
            default_item->addChild(default_button);
            
            // set model
            listView->setItemModel(default_item);
            listView->pushBackDefaultItem();
            listView->pushBackDefaultItem();
            listView->pushBackDefaultItem();
        }
        
        _uiLayer->addChild(listView);
        
      
        return true;
    }
    
    return false;
}
TEST_F(StaticRangeTest, SplitTextNodeRangeOutsideText)
{
    document().body()->setInnerHTML("<span id=\"outer\">0<span id=\"inner-left\">1</span>SPLITME<span id=\"inner-right\">2</span>3</span>", ASSERT_NO_EXCEPTION);

    Element* outer = document().getElementById(AtomicString::fromUTF8("outer"));
    Element* innerLeft = document().getElementById(AtomicString::fromUTF8("inner-left"));
    Element* innerRight = document().getElementById(AtomicString::fromUTF8("inner-right"));
    Text* oldText = toText(outer->childNodes()->item(2));

    StaticRange* staticRangeOuterOutside = StaticRange::create(document(), outer, 0, outer, 5);
    StaticRange* staticRangeOuterInside = StaticRange::create(document(), outer, 1, outer, 4);
    StaticRange* staticRangeOuterSurroundingText = StaticRange::create(document(), outer, 2, outer, 3);
    StaticRange* staticRangeInnerLeft = StaticRange::create(document(), innerLeft, 0, innerLeft, 1);
    StaticRange* staticRangeInnerRight = StaticRange::create(document(), innerRight, 0, innerRight, 1);
    StaticRange* staticRangeFromTextToMiddleOfElement = StaticRange::create(document(), oldText, 6, outer, 3);

    Range* rangeOuterOutside = staticRangeOuterOutside->toRange(ASSERT_NO_EXCEPTION);
    Range* rangeOuterInside = staticRangeOuterInside->toRange(ASSERT_NO_EXCEPTION);
    Range* rangeOuterSurroundingText = staticRangeOuterSurroundingText->toRange(ASSERT_NO_EXCEPTION);
    Range* rangeInnerLeft = staticRangeInnerLeft->toRange(ASSERT_NO_EXCEPTION);
    Range* rangeInnerRight = staticRangeInnerRight->toRange(ASSERT_NO_EXCEPTION);
    Range* rangeFromTextToMiddleOfElement = staticRangeFromTextToMiddleOfElement->toRange(ASSERT_NO_EXCEPTION);

    oldText->splitText(3, ASSERT_NO_EXCEPTION);
    Text* newText = toText(oldText->nextSibling());

    // Range should mutate.
    EXPECT_TRUE(rangeOuterOutside->boundaryPointsValid());
    EXPECT_EQ(outer, rangeOuterOutside->startContainer());
    EXPECT_EQ(0, rangeOuterOutside->startOffset());
    EXPECT_EQ(outer, rangeOuterOutside->endContainer());
    EXPECT_EQ(6, rangeOuterOutside->endOffset()); // Increased by 1 since a new node is inserted.

    EXPECT_TRUE(rangeOuterInside->boundaryPointsValid());
    EXPECT_EQ(outer, rangeOuterInside->startContainer());
    EXPECT_EQ(1, rangeOuterInside->startOffset());
    EXPECT_EQ(outer, rangeOuterInside->endContainer());
    EXPECT_EQ(5, rangeOuterInside->endOffset());

    EXPECT_TRUE(rangeOuterSurroundingText->boundaryPointsValid());
    EXPECT_EQ(outer, rangeOuterSurroundingText->startContainer());
    EXPECT_EQ(2, rangeOuterSurroundingText->startOffset());
    EXPECT_EQ(outer, rangeOuterSurroundingText->endContainer());
    EXPECT_EQ(4, rangeOuterSurroundingText->endOffset());

    EXPECT_TRUE(rangeInnerLeft->boundaryPointsValid());
    EXPECT_EQ(innerLeft, rangeInnerLeft->startContainer());
    EXPECT_EQ(0, rangeInnerLeft->startOffset());
    EXPECT_EQ(innerLeft, rangeInnerLeft->endContainer());
    EXPECT_EQ(1, rangeInnerLeft->endOffset());

    EXPECT_TRUE(rangeInnerRight->boundaryPointsValid());
    EXPECT_EQ(innerRight, rangeInnerRight->startContainer());
    EXPECT_EQ(0, rangeInnerRight->startOffset());
    EXPECT_EQ(innerRight, rangeInnerRight->endContainer());
    EXPECT_EQ(1, rangeInnerRight->endOffset());

    EXPECT_TRUE(rangeFromTextToMiddleOfElement->boundaryPointsValid());
    EXPECT_EQ(newText, rangeFromTextToMiddleOfElement->startContainer());
    EXPECT_EQ(3, rangeFromTextToMiddleOfElement->startOffset());
    EXPECT_EQ(outer, rangeFromTextToMiddleOfElement->endContainer());
    EXPECT_EQ(4, rangeFromTextToMiddleOfElement->endOffset());

    // StaticRange shouldn't mutate.
    EXPECT_EQ(outer, staticRangeOuterOutside->startContainer());
    EXPECT_EQ(0, staticRangeOuterOutside->startOffset());
    EXPECT_EQ(outer, staticRangeOuterOutside->endContainer());
    EXPECT_EQ(5, staticRangeOuterOutside->endOffset());

    EXPECT_EQ(outer, staticRangeOuterInside->startContainer());
    EXPECT_EQ(1, staticRangeOuterInside->startOffset());
    EXPECT_EQ(outer, staticRangeOuterInside->endContainer());
    EXPECT_EQ(4, staticRangeOuterInside->endOffset());

    EXPECT_EQ(outer, staticRangeOuterSurroundingText->startContainer());
    EXPECT_EQ(2, staticRangeOuterSurroundingText->startOffset());
    EXPECT_EQ(outer, staticRangeOuterSurroundingText->endContainer());
    EXPECT_EQ(3, staticRangeOuterSurroundingText->endOffset());

    EXPECT_EQ(innerLeft, staticRangeInnerLeft->startContainer());
    EXPECT_EQ(0, staticRangeInnerLeft->startOffset());
    EXPECT_EQ(innerLeft, staticRangeInnerLeft->endContainer());
    EXPECT_EQ(1, staticRangeInnerLeft->endOffset());

    EXPECT_EQ(innerRight, staticRangeInnerRight->startContainer());
    EXPECT_EQ(0, staticRangeInnerRight->startOffset());
    EXPECT_EQ(innerRight, staticRangeInnerRight->endContainer());
    EXPECT_EQ(1, staticRangeInnerRight->endOffset());

    EXPECT_EQ(oldText, staticRangeFromTextToMiddleOfElement->startContainer());
    EXPECT_EQ(6, staticRangeFromTextToMiddleOfElement->startOffset());
    EXPECT_EQ(outer, staticRangeFromTextToMiddleOfElement->endContainer());
    EXPECT_EQ(3, staticRangeFromTextToMiddleOfElement->endOffset());
}