text:
<?php

use PHPUnit_Extensions_Selenium2TestCase_Keys as Keys;

/**
 * Tests for PHPUnit_Extensions_Selenium2TestCase.
 *
 * @package    PHPUnit_Selenium
 * @author     Giorgio Sironi <info@giorgiosironi.com>
 * @copyright  2010-2013 Sebastian Bergmann <sebastian@phpunit.de>
 * @license    http://www.opensource.org/licenses/BSD-3-Clause  The BSD 3-Clause License
 * @link       http://www.phpunit.de/
 */
class Extensions_Selenium2TestCaseTest extends Tests_Selenium2TestCase_BaseTestCase
{
    public function testOpen()
    {
        $this->url('http://quantimodo.projectstatus.in');
        $this->assertStringEndsWith('http://quantimodo.projectstatus.in', $this->url());
    }

    public function testVersionCanBeReadFromTheTestCaseClass()
    {
        $this->assertEquals(1, version_compare(PHPUnit_Extensions_Selenium2TestCase::VERSION, "1.2.0"));
    }

    public function testCamelCaseUrlsAreSupported()
    {
        $this->url('html/CamelCasePage.html');
        $this->assertStringEndsWith('html/CamelCasePage.html', $this->url());
        $this->assertEquals('CamelCase page', $this->title());
    }

    public function testAbsoluteUrlsAreSupported()
    {
        $this->url(PHPUNIT_TESTSUITE_EXTENSION_SELENIUM_TESTS_URL . 'html/test_open.html');
        $this->assertEquals('Test open', $this->title());
    }

    public function testElementSelection()
    {
        $this->url('html/test_open.html');
        $element = $this->byCssSelector('body');
        $this->assertEquals('This is a test of the open command.', $element->text());

        $this->url('html/test_click_page1.html');
        $link = $this->byId('link');
        $this->assertEquals('Click here for next page', $link->text());
    }

    public function testMultipleElementsSelection()
    {
        $this->url('html/test_element_selection.html');
        $elements = $this->elements($this->using('css selector')->value('div'));
        $this->assertEquals(4, count($elements));
        $this->assertEquals('Other div', $elements[0]->text());
    }

    public function testElementFromResponseValue()
    {
        $this->url('html/test_open.html');
        $elementArray = $this->execute(array(
            'script' => 'return document.body;',
            'args' => array(),
        ));
        $element = $this->elementFromResponseValue($elementArray);
        $this->assertEquals('This is a test of the open command.', $element->text());
    }

    public function testSelectOptionsInMultiselect()
    {
        $this->url('html/test_multiselect.html');
        $this->select($this->byId('theSelect'))->selectOptionByValue("option1");
        $selectedOptions = $this->select($this->byId('theSelect'))->selectedLabels();
        $this->assertEquals(array('First Option','Second Option'), $selectedOptions);
        $this->select($this->byId('theSelect'))->selectOptionByLabel("Fourth Option");
        $selectedOptions = $this->select($this->byId('theSelect'))->selectedLabels();
        $this->assertEquals(array('First Option','Second Option','Fourth Option'), $selectedOptions);
    }

    public function testClearMultiselectSelectedOptions()
    {
        $this->url('html/test_multiselect.html');
        $selectedOptions = $this->select($this->byId('theSelect'))->selectedLabels();
        $this->assertEquals(array('Second Option'), $selectedOptions);
        $this->select($this->byId('theSelect'))->clearSelectedOptions();
        $selectedOptions = $this->select($this->byId('theSelect'))->selectedLabels();
        $this->assertEquals(array(), $selectedOptions);
    }

    public function testTheElementWithFocusCanBeInspected()
    {
        $this->url('html/test_select.html');

        // Select input and check if active
        $theInput = $this->byCssSelector('input[name="theInput"]');
        $theInput->click();
        $this->assertTrue($this->active()->equals($theInput), 'Input not recognized as active.');

        // Select select-group and check if active
        $selectGroup = $this->byCssSelector('#selectWithOptgroup');
        $selectGroup->click();
        $this->assertTrue($this->active()->equals($selectGroup), 'Select-group not recognized as active.');

        // Make sure that input is not recognized as selected
        $this->assertFalse($this->active()->equals($theInput), 'Input falsely recognized as active.');
    }

    public function testActivePageElementReceivesTheKeyStrokes()
    {
        $this->timeouts()->implicitWait(10000);

        $this->url('html/test_send_keys.html');
        $this->byId('q')->click();
        $this->keys('phpunit ');
        $this->assertEquals('phpunit', $this->byId('result')->text());
    }

    public function testElementsCanBeSelectedAsChildrenOfAlreadyFoundElements()
    {
        $this->url('html/test_element_selection.html');
        $parent = $this->byCssSelector('div#parentElement');
        $child = $parent->element($this->using('css selector')->value('span'));
        $this->assertEquals('Child span', $child->text());

        $rows = $this->byCssSelector('table')->elements($this->using('css selector')->value('tr'));
        $this->assertEquals(2, count($rows));
    }

    /**
     * Test on Session and Element
     *
     * @dataProvider getObjectsWithAccessToElement
     */
    public function testShortenedApiForSelectionOfElement($factory)
    {
        $this->url('html/test_element_selection.html');
        $parent = $factory($this);

        $element = $parent->byClassName('theDivClass');
        $this->assertEquals('The right div', $element->text());

        $element = $parent->byCssSelector('div.theDivClass');
        $this->assertEquals('The right div', $element->text());

        $element = $parent->byId('theDivId');
        $this->assertEquals('The right div', $element->text());

        $element = $parent->byName('theDivName');
        $this->assertEquals('The right div', $element->text());

        $element = $parent->byTag('div');
        $this->assertEquals('Other div', $element->text());

        $element = $parent->byXPath('//div[@id]');
        $this->assertEquals('The right div', $element->text());
    }

    public function getObjectsWithAccessToElement()
    {
        return array(
            array(function($s) { return $s; }),
            array(function($s) { return $s->byXPath('//body'); })
        );
    }

    public function testElementsKnowTheirTagName()
    {
        $this->url('html/test_element_selection.html');
        $element = $this->byClassName('theDivClass');
        $this->assertEquals('div', $element->name());
    }

    public function testFormElementsKnowIfTheyAreEnabled()
    {
        $this->url('html/test_form_elements.html');
        $this->assertTrue($this->byId('enabledInput')->enabled());
        $this->assertFalse($this->byId('disabledInput')->enabled());
    }

    public function testElementsKnowTheirAttributes()
    {
        $this->url('html/test_element_selection.html');
        $element = $this->byId('theDivId');
        $this->assertEquals('theDivClass', $element->attribute('class'));
    }

    public function testElementsDiscoverTheirEqualityWithOtherElements()
    {
        $this->url('html/test_element_selection.html');
        $element = $this->byId('theDivId');
        $differentElement = $this->byId('parentElement');
        $equalElement = $this->byId('theDivId');
        $this->assertTrue($element->equals($equalElement));
        $this->assertFalse($element->equals($differentElement));
    }

    public function testElementsKnowWhereTheyAreInThePage()
    {
        $this->url('html/test_element_selection.html');
        $element = $this->byCssSelector('body');
        $location = $element->location();
        $this->assertEquals(0, $location['x']);
        $this->assertEquals(0, $location['y']);
    }

    public function testElementsKnowTheirSize()
    {
        $this->url('html/test_geometry.html');
        $element = $this->byId('rectangle');
        $size = $element->size();
        $this->assertEquals(200, $size['width']);
        $this->assertEquals(100, $size['height']);
    }

    public function testElementsKnowTheirCssPropertiesValues()
    {
        $this->url('html/test_geometry.html');
        $element = $this->byId('colored');
        $this->assertRegExp('/rgba\(0,\s*0,\s*255,\s*1\)/', $element->css('background-color'));
    }

    public function testClick()
    {
        $this->url('html/test_click_page1.html');
        $link = $this->byId('link');
        $link->click();
        $this->assertEquals('Click Page Target', $this->title());
        $back = $this->byId('previousPage');
        $back->click();
        $this->assertEquals('Click Page 1', $this->title());

        $withImage = $this->byId('linkWithEnclosedImage');
        $withImage->click();
        $this->assertEquals('Click Page Target', $this->title());
        $back = $this->byId('previousPage');
        $back->click();

        $enclosedImage = $this->byId('enclosedImage');
        $enclosedImage->click();
        $this->assertEquals('Click Page Target', $this->title());
        $back = $this->byId('previousPage');
        $back->click();

        $toAnchor = $this->byId('linkToAnchorOnThisPage');
        $toAnchor->click();
        $this->assertEquals('Click Page 1', $this->title());

        $withOnClick = $this->byId('linkWithOnclickReturnsFalse');
        $withOnClick->click();
        $this->assertEquals('Click Page 1', $this->title());
    }

    public function testDoubleclick()
    {
        $this->url('html/test_doubleclick.html');
        $link = $this->byId('link');

        $this->moveto($link);
        $this->doubleclick();

        $this->assertEquals('doubleclicked', $this->alertText());
        $this->acceptAlert();
    }

    public function testByLinkText()
    {
        $this->url('html/test_click_page1.html');
        $link = $this->byLinkText('Click here for next page');
        $link->click();
        $this->assertEquals('Click Page Target', $this->title());
    }

    public function testByPartialLinkText()
    {
        $this->url('html/test_click_page1.html');
        $link = $this->byPartialLinkText('next page');
        $link->click();
        $this->assertEquals('Click Page Target', $this->title());
    }

    public function testClicksOnJavaScriptHref()
    {
        $this->url('html/test_click_javascript_page.html');
        $this->clickOnElement('link');
        $this->assertEquals('link clicked', $this->byId('result')->text());
    }

    public function testTypingViaTheKeyboard()
    {
        $this->url('html/test_type_page1.html');
        $usernameInput = $this->byName('username');
        $usernameInput->value('TestUser');
        $this->assertEquals('TestUser', $usernameInput->value());

        $passwordInput = $this->byName('password');
        $passwordInput->value('testUserPassword');
        $this->assertEquals('testUserPassword', $passwordInput->value());

        $this->clickOnElement('submitButton');
        $h2 = $this->byCssSelector('h2');
        $this->assertRegExp('/Welcome, TestUser!/', $h2->text());
    }

    /**
     * #190
     */
    public function testTypingAddsCharactersToTheCurrentValueOfAnElement()
    {
        $this->url('html/test_type_page1.html');
        $usernameInput = $this->byName('username');
        $usernameInput->value('first');
        $usernameInput->value('second');
        $this->assertEquals('firstsecond', $usernameInput->value());
    }

    /**
     * #165
     */
    public function testNumericValuesCanBeTyped()
    {
        $this->url('html/test_type_page1.html');
        $usernameInput = $this->byName('username');
        $usernameInput->value(1.13);
    }

    public function testFormsCanBeSubmitted()
    {
        $this->url('html/test_type_page1.html');
        $usernameInput = $this->byName('username');
        $usernameInput->value('TestUser');

        $this->byCssSelector('form')->submit();
        $h2 = $this->byCssSelector('h2');
        $this->assertRegExp('/Welcome, TestUser!/', $h2->text());
    }

    /**
     * @depends testTypingViaTheKeyboard
     */
    public function testTextTypedInAreasCanBeCleared()
    {
        $this->url('html/test_type_page1.html');
        $usernameInput = $this->byName('username');
        $usernameInput->value('TestUser');
        $usernameInput->clear();
        $this->assertEquals('', $usernameInput->value());
    }

    public function testTypingNonLatinText()
    {
        $this->url('html/test_type_page1.html');
        $usernameInput = $this->byName('username');
        $usernameInput->value('テストユーザ');
        $this->assertEquals('テストユーザ', $usernameInput->value());
    }

    public function testSelectElements()
    {
        $this->url('html/test_select.html');
        $option = $this->byId('o2');
        $this->assertEquals('Second Option', $option->text());
        $this->assertEquals('option2', $option->value());
        $this->assertTrue($option->selected());
        $option = $this->byId('o3');
        $this->assertFalse($option->selected());
        $option->click();
        $this->assertTrue($option->selected());
    }

    public function testASelectObjectCanBeBuildWithASpecificAPI()
    {
        $this->url('html/test_select.html');
        $select = $this->select($this->byCssSelector('select'));

        // basic
        $this->assertEquals('Second Option', $select->selectedLabel());
        $this->assertEquals('option2', $select->selectedValue());

        // by text, value attribute or generic criteria
        $select->selectOptionByLabel('Fourth Option');
        $this->assertEquals('option4', $select->selectedValue());

        $select->selectOptionByValue('option3');
        $this->assertEquals('Third Option', $select->selectedLabel());

        $select->selectOptionByCriteria($this->using('id')->value('o4'));
        $this->assertEquals('option4', $select->selectedValue());

        // empty values
        $select->selectOptionByValue('');
        $this->assertEquals('Empty Value Option', $select->selectedLabel());

        $select->selectOptionByLabel('');
        $this->assertEquals('', $select->selectedLabel());

    }

    /**
     * Ticket 119
     */
    public function testSelectOptionSelectsDescendantElement()
    {
        $this->url('html/test_select.html');
        $select = $this->select($this->byCssSelector('#secondSelect'));
        $this->assertEquals("option2", $select->selectedValue());

        $select->selectOptionByLabel("First Option");
        $this->assertEquals("option1", $select->selectedValue());

        $select->selectOptionByValue("option2");
        $this->assertEquals("option2", $select->selectedValue());
    }

    /**
     * Ticket 170
     */
    public function testSelectOptgroupDoNotGetInTheWay()
    {
        $this->url('html/test_select.html');
        $select = $this->select($this->byCssSelector('#selectWithOptgroup'));

        $select->selectOptionByLabel("Second");
        $this->assertEquals("2", $select->selectedValue());

        $select->selectOptionByValue("1");
        $this->assertEquals("1", $select->selectedValue());
    }

    public function testCheckboxesCanBeSelectedAndDeselected()
    {
        $this->markTestIncomplete("Flaky: fails on clicking in some browsers.");
        $this->url('html/test_check_uncheck.html');
        $beans = $this->byId('option-beans');
        $butter = $this->byId('option-butter');

        $this->assertTrue($beans->selected());
        $this->assertFalse($butter->selected());

        $butter->click();
        $this->assertTrue($butter->selected());
        $butter->click();
        $this->assertFalse($butter->selected());
    }

    public function testRadioBoxesCanBeSelected()
    {
        $this->url('html/test_check_uncheck.html');
        $spud = $this->byId('base-spud');
        $rice = $this->byId('base-rice');

        $this->assertTrue($spud->selected());
        $this->assertFalse($rice->selected());

        $rice->click();
        $this->assertFalse($spud->selected());
        $this->assertTrue($rice->selected());

        $spud->click();
        $this->assertTrue($spud->selected());
        $this->assertFalse($rice->selected());
    }

    public function testWaitPeriodsAreImplicitInSelection()
    {
        $this->timeouts()->implicitWait(10000);
        $this->url('html/test_delayed_element.html');
        $element = $this->byId('createElementButton')->click();
        $div = $this->byXPath("//div[@id='delayedDiv']");
        $this->assertEquals('Delayed div.', $div->text());
    }

    public function testTimeoutsCanBeDefinedForAsynchronousExecutionOfJavaScript()
    {
        $this->url('html/test_open.html');
        $this->timeouts()->asyncScript(10000);
        $script = 'var callback = arguments[0];
                   window.setTimeout(function() {
                       callback(document.title);
                   }, 1000);
        ';
        $result = $this->executeAsync(array(
            'script' => $script,
            'args'   => array()
        ));
        $this->assertEquals("Test open", $result);
    }

    public function testTheBackAndForwardButtonCanBeUsedToNavigate()
    {
        $this->url('html/test_click_page1.html');
        $this->assertEquals('Click Page 1', $this->title());

        $this->clickOnElement('link');
        $this->assertEquals('Click Page Target', $this->title());

        $this->back();
        $this->assertEquals('Click Page 1', $this->title());

        $this->forward();
        $this->assertEquals('Click Page Target', $this->title());
    }

    public function testThePageCanBeRefreshed()
    {
        $this->url('html/test_page.slow.html');
        $this->assertStringEndsWith('html/test_page.slow.html', $this->url());
        $this->assertEquals('Slow Loading Page', $this->title());

        $this->clickOnElement('changeSpan');
        $this->assertEquals('Changed the text', $this->byId('theSpan')->text());
        $this->refresh();
        $this->assertEquals('This is a slow-loading page.', $this->byId('theSpan')->text());

        $this->clickOnElement('changeSpan');
        $this->assertEquals('Changed the text', $this->byId('theSpan')->text());
    }

    public function testLinkEventsAreGenerated()
    {
        $this->url('html/test_form_events.html');
        $eventLog = $this->byId('eventlog');
        $eventLog->clear();

        $this->clickOnElement('theLink');
        $this->assertEquals('link clicked', $this->alertText());
        $this->acceptAlert();
        $this->assertContains('{click(theLink)}', $eventLog->value());
    }

    public function testButtonEventsAreGenerated()
    {
        $this->url('html/test_form_events.html');
        $eventLog = $this->byId('eventlog');
        $eventLog->clear();

        $this->clickOnElement('theButton');
        $this->assertContains('{focus(theButton)}', $eventLog->value());
        $this->assertContains('{click(theButton)}', $eventLog->value());
        $eventLog->clear();

        $this->clickOnElement('theSubmit');
        $this->assertContains('{focus(theSubmit)} {click(theSubmit)} {submit}', $eventLog->value());
    }

    public function testSelectEventsAreGeneratedbutOnlyIfANewSelectionIsMade()
    {
        $this->url('html/test_form_events.html');
        $select = $this->select($this->byId('theSelect'));
        $eventLog = $this->byId('eventlog');
        $eventLog->clear();

        $select->selectOptionByLabel('First Option');
        $this->assertEquals('option1', $select->selectedValue());
        $this->assertContains('{focus(theSelect)}', $eventLog->value());
        $this->assertContains('{change(theSelect)}', $eventLog->value());

        $eventLog->clear();
        $select->selectOptionByLabel('First Option');
        $this->assertEquals('option1', $select->selectedValue());
        $this->assertEquals('', $eventLog->value());
    }

    public function testRadioEventsAreGenerated()
    {
        $this->markTestIncomplete("Flaky: fails on focus in some browsers.");
        $this->url('html/test_form_events.html');
        $first = $this->byId('theRadio1');
        $second = $this->byId('theRadio2');
        $eventLog = $this->byId('eventlog');

        $this->assertFalse($first->selected());
        $this->assertFalse($second->selected());
        $this->assertEquals('', $eventLog->value());

        $first->click();
        $this->assertContains('{focus(theRadio1)}', $eventLog->value());
        $this->assertContains('{click(theRadio1)}', $eventLog->value());
        $this->assertContains('{change(theRadio1)}', $eventLog->value());
        $this->assertNotContains('theRadio2', $eventLog->value());

        $eventLog->clear();
        $first->click();
        $this->assertContains('{focus(theRadio1)}', $eventLog->value());
        $this->assertContains('{click(theRadio1)}', $eventLog->value());
    }

    public function testCheckboxEventsAreGenerated()
    {
        $this->markTestIncomplete("Flaky: fails on focus in some browsers.");
        $this->url('html/test_form_events.html');
        $checkbox = $this->byId('theCheckbox');
        $eventLog = $this->byId('eventlog');
        $this->assertFalse($checkbox->selected());
        $this->assertEquals('', $eventLog->value());

        $checkbox->click();
        $this->assertContains('{focus(theCheckbox)}', $eventLog->value());
        $this->assertContains('{click(theCheckbox)}', $eventLog->value());
        $this->assertContains('{change(theCheckbox)}', $eventLog->value());

        $eventLog->clear();
        $checkbox->click();
        $this->assertContains('{focus(theCheckbox)}', $eventLog->value());
        $this->assertContains('{click(theCheckbox)}', $eventLog->value());
        $this->assertContains('{change(theCheckbox)}', $eventLog->value());
    }

    public function testTextEventsAreGenerated()
    {
        $this->url('html/test_form_events.html');
        $textBox = $this->byId('theTextbox');
        $eventLog = $this->byId('eventlog');
        $this->assertEquals('', $textBox->value());
        $this->assertEquals('', $eventLog->value());

        $textBox->value('first value');
        $this->assertContains('{focus(theTextbox)}', $eventLog->value());
    }

    public function testMouseEventsAreGenerated()
    {
        $this->url('html/test_form_events.html');
        $this->clickOnElement('theTextbox');
        $this->clickOnElement('theButton');
        $eventLog = $this->byId('eventlog');
        $this->assertContains('{mouseover(theTextbox)}', $eventLog->value());
        $this->assertContains('{mousedown(theButton)}', $eventLog->value());
        $this->assertContains('{mouseover(theTextbox)}', $eventLog->value());
        $this->assertContains('{mousedown(theButton)}', $eventLog->value());
    }

    public function testKeyEventsAreGenerated()
    {
        $this->url('html/test_form_events.html');
        $this->byId('theTextbox')->value('t');

        $this->assertContains('{focus(theTextbox)}'
                           . ' {keydown(theTextbox - 84)}'
                           . ' {keypress(theTextbox)}'
                           . ' {keyup(theTextbox - 84)}',
                               $this->byId('eventlog')->value());
    }

    public function testConfirmationsAreHandledAsAlerts()
    {
        $this->url('html/test_confirm.html');
        $this->clickOnElement('confirmAndLeave');
        $this->assertEquals('You are about to go to a dummy page.', $this->alertText());
        $this->dismissAlert();
        $this->assertEquals('Test Confirm', $this->title());

        $this->clickOnElement('confirmAndLeave');
        $this->assertEquals('You are about to go to a dummy page.', $this->alertText());
        $this->acceptAlert();
        $this->assertEquals('Dummy Page', $this->title());
    }

    public function testPromptsCanBeAnsweredByTyping()
    {
        $this->url('html/test_prompt.html');

        $this->clickOnElement('promptAndLeave');
        $this->assertEquals("Type 'yes' and click OK", $this->alertText());
        $this->dismissAlert();
        $this->assertEquals('Test Prompt', $this->title());

        $this->clickOnElement('promptAndLeave');
        $this->alertText('yes');
        $this->acceptAlert();
        $this->assertEquals('Dummy Page', $this->title());
    }

    public function testInvisibleElementsDoNotHaveADisplayedText()
    {
        $this->url('html/test_visibility.html');
        $this->assertEquals('A visible paragraph', $this->byId('visibleParagraph')->text());
        $this->assertTrue($this->byId('visibleParagraph')->displayed());

        $this->assertEquals('', $this->byId('hiddenParagraph')->text());
        $this->assertFalse($this->byId('hiddenParagraph')->displayed());

        $this->assertEquals('', $this->byId('suppressedParagraph')->text());
        $this->assertEquals('', $this->byId('classSuppressedParagraph')->text());
        $this->assertEquals('', $this->byId('jsClassSuppressedParagraph')->text());
        $this->assertEquals('', $this->byId('hiddenSubElement')->text());
        $this->assertEquals('sub-element that is explicitly visible', $this->byId('visibleSubElement')->text());
        $this->assertEquals('', $this->byId('suppressedSubElement')->text());
        $this->assertEquals('', $this->byId('jsHiddenParagraph')->text());
    }

    public function testScreenshotsCanBeTakenAtAnyMoment()
    {
        $this->url('html/test_open.html');
        $screenshot = $this->currentScreenshot();
        $this->assertTrue(is_string($screenshot));
        $this->assertTrue(strlen($screenshot) > 0);
        $this->markTestIncomplete('By guaranteeing the size of the window, we could add a deterministic assertion for the image.');
    }

    public function testACurrentWindowHandleAlwaysExist()
    {
        $this->url('html/test_open.html');
        $window  = $this->windowHandle();
        $this->assertTrue(is_string($window));
        $this->assertTrue(strlen($window) > 0);
        $allHandles  = $this->windowHandles();
        $this->assertEquals(array('0' => $window), $allHandles);
    }

    public function testThePageSourceCanBeRead()
    {
        $this->url('html/test_open.html');
        $source = $this->source();
        $this->assertStringStartsWith('<!--', $source);
        $this->assertContains('<body>', $source);
        $this->assertStringEndsWith('</html>', $source);
    }

    public function testJavaScriptCanBeEmbeddedForExecution()
    {
        $this->url('html/test_open.html');
        $script = 'return document.title;';
        $result = $this->execute(array(
            'script' => $script,
            'args'   => array()
        ));
        $this->assertEquals("Test open", $result);
    }

    public function testAsynchronousJavaScriptCanBeEmbeddedForExecution()
    {
        $this->url('html/test_open.html');
        $script = 'var callback = arguments[0]; callback(document.title);';
        $result = $this->executeAsync(array(
            'script' => $script,
            'args'   => array()
        ));
        $this->assertEquals("Test open", $result);
    }

    public function testInputMethodFrameworksCanBeManagedViaTheApi()
    {
        $this->markTestIncomplete("Need to create an IME object.");
        $this->ime()->availableEngines();
        $this->ime()->activeEngine();
        $this->ime()->activated();
        $this->ime()->deactive();
        $this->ime()->activate();
    }

    public function testDifferentFramesFromTheMainOneCanGetFocusById()
    {
        $this->url('html/test_frames.html');
        $this->frame('my_iframe_id');
        $this->assertEquals('This is a test of the open command.', $this->byCssSelector('body')->text());

        $this->frame(NULL);
        $this->assertContains('This page contains frames.', $this->byCssSelector('body')->text());
    }

    public function testDifferentFramesFromTheMainOneCanGetFocusByFrameCount()
    {
        $this->url('html/test_frames.html');
        $this->frame(0);
        $this->assertEquals('This is a test of the open command.', $this->byCssSelector('body')->text());

        $this->frame(NULL);
        $this->assertContains('This page contains frames.', $this->byCssSelector('body')->text());
    }

    public function testDifferentFramesFromTheMainOneCanGetFocusByName()
    {
        $this->url('html/test_frames.html');
        $this->frame('my_iframe_name');
        $this->assertEquals('This is a test of the open command.', $this->byCssSelector('body')->text());

        $this->frame(NULL);
        $this->assertContains('This page contains frames.', $this->byCssSelector('body')->text());
    }

    public function testDifferentFramesFromTheMainOneCanGetFocusByElement()
    {
        $this->url('html/test_frames.html');
        $frame = $this->byId('my_iframe_id');
        $this->frame($frame);
        $this->assertEquals('This is a test of the open command.', $this->byCssSelector('body')->text());

        $this->frame(NULL);
        $this->assertContains('This page contains frames.', $this->byCssSelector('body')->text());
    }

    public function testDifferentWindowsCanBeFocusedOnDuringATest()
    {
        $this->url('html/test_select_window.html');
        $this->byId('popupPage')->click();

        $this->window('myPopupWindow');
        $this->assertEquals('Select Window Popup', $this->title());

        $this->window('');
        $this->assertEquals('Select Window Base', $this->title());

        $this->window('myPopupWindow');
        $this->byId('closePage')->click();

        $this->window('');
        $this->assertEquals('Select Window Base', $this->title());
    }

    public function testWindowsCanBeManipulatedAsAnObject()
    {
        $this->url('html/test_select_window.html');
        $this->byId('popupPage')->click();

        $this->window('myPopupWindow');
        $popup = $this->currentWindow();
        $this->assertTrue($popup instanceof PHPUnit_Extensions_Selenium2TestCase_Window);
        $popup->size(array('width' => 100, 'height' => 200));
        $size = $popup->size();
        $this->assertEquals(100, $size['width']);
        $this->assertEquals(200, $size['height']);

        $this->window('');
        $this->assertEquals('Select Window Base', $this->title());
    }

    public function testWindowsCanBeClosed()
    {
        $this->url('html/test_select_window.html');
        $this->byId('popupPage')->click();

        $this->window('myPopupWindow');
        $this->closeWindow();

        $this->window('');
        $this->assertEquals('Select Window Base', $this->title());
        $this->assertEquals(1, count($this->windowHandles()));
    }

    public function testCookiesCanBeSetAndRead()
    {
        $this->url('html/');
        $cookies = $this->cookie();
        $cookies->add('name', 'value')->set();
        $this->assertEquals('value', $cookies->get('name'));
    }

    /**
     * @depends testCookiesCanBeSetAndRead
     */
    public function testCookiesCanBeDeletedOneAtTheTime()
    {
        $this->url('html/');
        $cookies = $this->cookie();
        $cookies->add('name', 'value')->set();
        $cookies->remove('name');
        $this->assertThereIsNoCookieNamed('name');
    }

    public function testCookiesCanBeDeletedAllAtOnce()
    {
        $this->url('html/');
        $cookies = $this->cookie();
        $cookies->add('id', 'id_value')->set();
        $cookies->add('name', 'name_value')->set();
        $cookies->clear();
        $this->assertThereIsNoCookieNamed('id');
        $this->assertThereIsNoCookieNamed('name');
    }

    public function testAdvancedParametersOfCookieCanBeSet()
    {
        $this->url('/');
        $cookies = $this->cookie();
        $cookies->add('name', 'value')
                ->path('/html')
                ->domain('127.0.0.1')
                ->expiry(time()+60*60*24)
                ->secure(FALSE)
                ->set();
        $this->assertThereIsNoCookieNamed('name');
        $this->url('/html');
        $this->assertEquals('value', $cookies->get('name'));
    }

    private function assertThereIsNoCookieNamed($name)
    {
        try {
            $this->cookie()->get($name);
            $this->fail('The cookie shouldn\'t exist anymore.');
        } catch (PHPUnit_Extensions_Selenium2TestCase_Exception $e) {
            $this->assertEquals("There is no '$name' cookie available on this page.", $e->getMessage());
        }
    }

    public function testTheBrowsersOrientationCanBeModified()
    {
        $this->markTestIncomplete('Which browsers support this functionality?');
        $this->orientation('LANDSCAPE');
        $this->orientation('PORTRAIT');
        $this->orientation();
    }

    public function testTheMouseCanBeMovedToAKnownPosition()
    {
        // @TODO: remove markTestIncomplete() when the following bugs are fixed
        // @see https://code.google.com/p/selenium/issues/detail?id=5939
        // @see https://code.google.com/p/selenium/issues/detail?id=3578
        $this->markTestIncomplete('This is broken in a firefox driver yet');
        $this->url('html/test_moveto.html');
        $this->moveto(array(
            'element' => $this->byId('moveto'),
            'xoffset' => 10,
            'yoffset' => 10,
        ));
        $this->buttondown();

        $deltaX = 42;
        $deltaY = 11;
        $this->moveto(array(
            'xoffset' => $deltaX,
            'yoffset' => $deltaY,
        ));
        $this->buttonup();

        $down = explode(',', $this->byId('down')->text());
        $up = explode(',', $this->byId('up')->text());

        $this->assertCount(2, $down);
        $this->assertCount(2, $up);
        $this->assertEquals($deltaX, $up[0] - $down[0]);
        $this->assertEquals($deltaY, $up[1] - $down[1]);
    }

    public function testMoveToRequiresElementParamToBeValidElement()
    {
        $this->url('html/test_moveto.html');

        try {
            $this->moveto('moveto');
            $this->fail('A single non-element parameter should cause an exception');
        } catch (PHPUnit_Extensions_Selenium2TestCase_Exception $e) {
            $this->assertStringStartsWith('Only moving over an element is supported', $e->getMessage());
        }

        try {
            $this->moveto(array(
                'element' => 'moveto'
            ));
            $this->fail('An "element" array parameter with non-element value should cause an exception');
        } catch (PHPUnit_Extensions_Selenium2TestCase_Exception $e) {
            $this->assertStringStartsWith('Only moving over an element is supported', $e->getMessage());
        }
    }

    public function testMouseButtonsCanBeClickedMultipleTimes()
    {
        $this->markTestIncomplete();
        $this->moveto(array(
            'element' => 'id', // or Element object
            'xoffset' => 0,
            'yofsset' => 0
        ));
        $this->doubleClick();
    }

    public function testFingersCanBeMovedAndPressedOnTheScreen()
    {
        $this->markTestIncomplete('Which browser supports these events?');
        $this->touch()->click();
        $this->touch()->down();
        $this->touch()->up();
        $this->touch()->move();
        $this->touch()->scroll();
        $this->touch()->doubleClick();
        $this->touch()->longClick();
        $this->touch()->flick();
    }

    public function testGeoLocationIsAccessible()
    {
        $this->markTestIncomplete();
        $this->location();
    }

    public function testTheBrowserLocalStorageIsAccessible()
    {
        $this->markTestIncomplete('We need a browser which supports WebStorage.');
        //$this->localStorage(); // all keys
        $storage = $this->localStorage();
        $storage->key = 42;
        $this->assertSame("42", $storage->key);
        //$this->localStorage()->size(); // a value
        // how to clear the storage?
    }

    public function testTheBrowserSessionStorageIsAccessible()
    {
        $this->markTestIncomplete();
        $this->sessionStorage(); // all keys
        $this->sessionStorage()->key; // gets a value
        $this->sessionStorage()->key = 2; // sets a value
        $this->sessionStorage()->size(); // a value
        // how to clear the storage?
    }

    public function test404PagesCanBeLoaded()
    {
        $this->url('inexistent.html');
    }

    /**
     * Ticket #113.
     */
    public function testMultipleUrlsCanBeLoadedInATest()
    {
        $this->url('html/test_click_page1.html');
        $this->url('html/test_open.html');
        $this->assertEquals('Test open', $this->title());
        $this->assertStringEndsWith('html/test_open.html', strstr($this->url(), 'html/'));
    }

    public function testNonexistentElement()
    {
        $this->url('html/test_open.html');
        try {
            $el = $this->byId("nonexistent");
        } catch (PHPUnit_Extensions_Selenium2TestCase_WebDriverException $e) {
            $this->assertEquals(PHPUnit_Extensions_Selenium2TestCase_WebDriverException::NoSuchElement, $e->getCode());
            return;
        }
        $this->fail('The element shouldn\'t exist.');
    }

    public function testSpecialKeys()
    {
        $this->url('html/test_special_keys.html');
        $this->byId('input')->click();

        $this->keys(Keys::F2);
        $this->assertEquals('113', $this->byId('check')->text());

        $this->keys(Keys::ALT . Keys::ENTER);
        $this->assertEquals('13,alt', $this->byId('check')->text());

        // note that modifier keys (alt, control, shift) are sticky
        // so they are enabled until you explicitly disable it by another call
        // The above is valid for at least Chrome and Firefox, in IE they are
        // sticky only within a single keys() method call
        $this->keys(Keys::CONTROL . Keys::SHIFT . Keys::HOME);
        $this->assertEquals('36,alt,control,shift', $this->byId('check')->text());

        $this->keys(Keys::ALT . Keys::SHIFT . Keys::NUMPAD7);
        $this->assertEquals('103,control', $this->byId('check')->text());
    }

    public function testSessionClick()
    {
        $this->url('html/test_mouse_buttons.html');
        $input = $this->byId('input');

        $this->moveto($input);

        $this->click();
        $this->assertEquals('0', $this->byId('check')->text());

        $this->click(PHPUnit_Extensions_Selenium2TestCase_SessionCommand_Click::LEFT);
        $this->assertEquals('0', $this->byId('check')->text());

        // I couldn't get it worked in selenium webdriver 2.28: even though the client (phpunit-selenium) sends
        // the button: 1 in the request (checked with wireshark) - it still uses left mouse button (0)
        /*
        $this->click(PHPUnit_Extensions_Selenium2TestCase_SessionCommand_Click::MIDDLE);
        $this->assertEquals('1', $this->byId('check')->text());
        */

        $this->click(PHPUnit_Extensions_Selenium2TestCase_SessionCommand_Click::RIGHT);
        $this->assertEquals('2', $this->byId('check')->text());
    }

    /**
     * @expectedException BadMethodCallException
     */
    public function testSessionClickNotScalar()
    {
        $this->click(array());
    }

    /**
     * @expectedException BadMethodCallException
     */
    public function testSessionClickNotAValidValue()
    {
        $this->click(3);
    }

    public function testGetSelectedOptionDataInMultiselect()
    {
        $this->url('html/test_multiselect.html');
        $this->assertSame('Second Option', $this->select($this->byId('theSelect'))->selectedLabel());
        $this->assertSame('option2', $this->select($this->byId('theSelect'))->selectedValue());
        $this->assertSame('o2', $this->select($this->byId('theSelect'))->selectedId());
        $this->select($this->byId('theSelect'))->clearSelectedOptions();
        $this->assertSame('', $this->select($this->byId('theSelect'))->selectedLabel());
        $this->assertSame('', $this->select($this->byId('theSelect'))->selectedValue());
        $this->assertSame('', $this->select($this->byId('theSelect'))->selectedId());
    }
}


text:
#include "AssertLog.h"
#include "Defines.h"
#include "Display.h"

#pragma comment(lib, "d3d9.lib")
#pragma comment(lib, "d3dx9.lib")

Display::Display()	:
	m_pDirect3D(NULL),
	m_pDirect3DDevice(NULL),
	m_pRenderer(NULL)
{
}

Display::~Display()
{
	close();
}

Display* Display::create()
{
	Display*	pDisplay	= new Display();

	if (false == pDisplay->initialize())
	{
		delete	pDisplay;

		pDisplay	= NULL;
	}

	return	pDisplay;
}

bool Display::initialize()
{
	m_iDeviceWidth	= gsc_iWindowWidth;
	m_iDeviceHeight	= gsc_iWindowHeight;

	// Create a NULL renderer. The renderer will be created after the window is created.
	m_pRenderer = new Gwen::Renderer::DirectX9(NULL);

	return	true;
}

void Display::close()
{
	delete	m_pRenderer;

	m_pRenderer	= NULL;

	m_pDirect3DDevice	= NULL;

	SAFE_RELEASE(m_pDirect3D);
}

bool Display::initializeDirectX(HWND _hWnd)
{
	m_pDirect3D	= Direct3DCreate9(D3D_SDK_VERSION);

	if (NULL == m_pDirect3D)
	{
		return	false;
	}

	D3DDISPLAYMODE	displayMode;

	HRESULT	hResult	= m_pDirect3D->GetAdapterDisplayMode(D3DADAPTER_DEFAULT, &displayMode);

	if (FAILED(hResult))
	{
		Log::instance()->logError("GetAdapterDisplayMode error (%08X)", hResult);

		return	false;
	}

	hResult	= m_pDirect3D->CheckDeviceFormat(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, displayMode.Format, D3DUSAGE_DEPTHSTENCIL,
		D3DRTYPE_SURFACE, D3DFMT_D16);

	if (FAILED(hResult) && D3DERR_NOTAVAILABLE == hResult)
	{
		return	false;
	}

	hResult	= m_pDirect3D->GetDeviceCaps(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, &m_direct3DCaps);

	if (FAILED(hResult))
	{
		Log::instance()->logError("GetDeviceCaps error (%08X)", hResult);

		return	false;
	}

	DWORD uBehaviorFlags;

	if (m_direct3DCaps.VertexProcessingCaps != 0)
	{
		uBehaviorFlags	= D3DCREATE_HARDWARE_VERTEXPROCESSING;
	}

	else
	{
		uBehaviorFlags	= D3DCREATE_SOFTWARE_VERTEXPROCESSING;
	}

	D3DPRESENT_PARAMETERS	presentParameters;

	memset(&presentParameters, 0, sizeof(D3DPRESENT_PARAMETERS));

	presentParameters.BackBufferFormat			= displayMode.Format;
	presentParameters.BackBufferCount			= 1;
	presentParameters.SwapEffect				= D3DSWAPEFFECT_DISCARD;
	presentParameters.Windowed					= TRUE;
	presentParameters.EnableAutoDepthStencil	= FALSE;
	presentParameters.AutoDepthStencilFormat	= D3DFMT_D16;
	presentParameters.PresentationInterval		= D3DPRESENT_INTERVAL_ONE;
	presentParameters.hDeviceWindow				= _hWnd;

	hResult	= m_pDirect3D->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, _hWnd, uBehaviorFlags, &presentParameters, &m_pDirect3DDevice);

	if (FAILED(hResult))
	{
		Log::instance()->logError("CreateDevice error (%08X)", hResult);

		return	false;
	}

	// Set the final device device
	m_pRenderer->setDevice(m_pDirect3DDevice);

	return	true;
}

redpajama_set_name: RedPajamaGithub


text:
using content::BrowserThread;
void HandleTransferCompletion(PlatformUsbTransferHandle transfer);

namespace {

static uint8 ConvertTransferDirection(
    const UsbEndpointDirection direction) {
  switch (direction) {
    case USB_DIRECTION_INBOUND:
      return LIBUSB_ENDPOINT_IN;
    case USB_DIRECTION_OUTBOUND:
      return LIBUSB_ENDPOINT_OUT;
    default:
      NOTREACHED();
      return LIBUSB_ENDPOINT_IN;
  }
}

static uint8 CreateRequestType(const UsbEndpointDirection direction,
    const UsbDeviceHandle::TransferRequestType request_type,
    const UsbDeviceHandle::TransferRecipient recipient) {
  uint8 result = ConvertTransferDirection(direction);

  switch (request_type) {
    case UsbDeviceHandle::STANDARD:
      result |= LIBUSB_REQUEST_TYPE_STANDARD;
      break;
    case UsbDeviceHandle::CLASS:
      result |= LIBUSB_REQUEST_TYPE_CLASS;
      break;
    case UsbDeviceHandle::VENDOR:
      result |= LIBUSB_REQUEST_TYPE_VENDOR;
      break;
    case UsbDeviceHandle::RESERVED:
      result |= LIBUSB_REQUEST_TYPE_RESERVED;
      break;
  }

  switch (recipient) {
    case UsbDeviceHandle::DEVICE:
      result |= LIBUSB_RECIPIENT_DEVICE;
      break;
    case UsbDeviceHandle::INTERFACE:
      result |= LIBUSB_RECIPIENT_INTERFACE;
      break;
    case UsbDeviceHandle::ENDPOINT:
      result |= LIBUSB_RECIPIENT_ENDPOINT;
      break;
    case UsbDeviceHandle::OTHER:
      result |= LIBUSB_RECIPIENT_OTHER;
      break;
  }

  return result;
}

static UsbTransferStatus ConvertTransferStatus(
    const libusb_transfer_status status) {
  switch (status) {
    case LIBUSB_TRANSFER_COMPLETED:
      return USB_TRANSFER_COMPLETED;
    case LIBUSB_TRANSFER_ERROR:
      return USB_TRANSFER_ERROR;
    case LIBUSB_TRANSFER_TIMED_OUT:
      return USB_TRANSFER_TIMEOUT;
    case LIBUSB_TRANSFER_STALL:
      return USB_TRANSFER_STALLED;
    case LIBUSB_TRANSFER_NO_DEVICE:
      return USB_TRANSFER_DISCONNECT;
    case LIBUSB_TRANSFER_OVERFLOW:
      return USB_TRANSFER_OVERFLOW;
    case LIBUSB_TRANSFER_CANCELLED:
      return USB_TRANSFER_CANCELLED;
    default:
      NOTREACHED();
      return USB_TRANSFER_ERROR;
  }
}

static void LIBUSB_CALL PlatformTransferCompletionCallback(
    PlatformUsbTransferHandle transfer) {
  BrowserThread::PostTask(BrowserThread::FILE,
                          FROM_HERE,
                          base::Bind(HandleTransferCompletion, transfer));
}

}  // namespace

void HandleTransferCompletion(PlatformUsbTransferHandle transfer) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
  UsbDeviceHandle* const device_handle =
      reinterpret_cast<UsbDeviceHandle*>(transfer->user_data);
  CHECK(device_handle) << "Device handle is closed before transfer finishes.";
  device_handle->TransferComplete(transfer);
  libusb_free_transfer(transfer);
}

class UsbDeviceHandle::InterfaceClaimer
    : public base::RefCountedThreadSafe<UsbDeviceHandle::InterfaceClaimer> {
 public:
  InterfaceClaimer(const scoped_refptr<UsbDeviceHandle> handle,
                   const int interface_number);

  bool Claim() const;

  int alternate_setting() const { return alternate_setting_; }
  void set_alternate_setting(const int alternate_setting) {
    alternate_setting_ = alternate_setting;
  }

 private:
  friend class UsbDevice;
  friend class base::RefCountedThreadSafe<InterfaceClaimer>;
  ~InterfaceClaimer();

  const scoped_refptr<UsbDeviceHandle> handle_;
  const int interface_number_;
  int alternate_setting_;

  DISALLOW_COPY_AND_ASSIGN(InterfaceClaimer);
};

UsbDeviceHandle::InterfaceClaimer::InterfaceClaimer(
    const scoped_refptr<UsbDeviceHandle> handle, const int interface_number)
    : handle_(handle),
      interface_number_(interface_number),
      alternate_setting_(0) {
}

UsbDeviceHandle::InterfaceClaimer::~InterfaceClaimer() {
  libusb_release_interface(handle_->handle(), interface_number_);
}

bool UsbDeviceHandle::InterfaceClaimer::Claim() const {
  return libusb_claim_interface(handle_->handle(), interface_number_) == 0;
}

struct UsbDeviceHandle::Transfer {
  Transfer();
  ~Transfer();

  UsbTransferType transfer_type;
  scoped_refptr<net::IOBuffer> buffer;
  scoped_refptr<UsbDeviceHandle::InterfaceClaimer> claimed_interface;
  scoped_refptr<base::MessageLoopProxy> message_loop_proxy;
  size_t length;
  UsbTransferCallback callback;
};

UsbDeviceHandle::Transfer::Transfer()
    : transfer_type(USB_TRANSFER_CONTROL),
      length(0) {
}

UsbDeviceHandle::Transfer::~Transfer() {}

UsbDeviceHandle::UsbDeviceHandle(
    scoped_refptr<UsbContext> context,
    UsbDevice* device,
    PlatformUsbDeviceHandle handle)
    : device_(device), handle_(handle), context_(context) {
  DCHECK(thread_checker_.CalledOnValidThread());
  DCHECK(handle) << "Cannot create device with NULL handle.";
  interfaces_ = new UsbConfigDescriptor();
  device->ListInterfaces(interfaces_.get());
}

UsbDeviceHandle::UsbDeviceHandle() : device_(NULL), handle_(NULL) {
}

UsbDeviceHandle::~UsbDeviceHandle() {
  DCHECK(thread_checker_.CalledOnValidThread());

  libusb_close(handle_);
  handle_ = NULL;
}

scoped_refptr<UsbDevice> UsbDeviceHandle::device() const {
  return device_;
}

void UsbDeviceHandle::Close() {
  DCHECK(thread_checker_.CalledOnValidThread());
  if (device_)
    device_->Close(this);
}

void UsbDeviceHandle::TransferComplete(PlatformUsbTransferHandle handle) {
  DCHECK(ContainsKey(transfers_, handle)) << "Missing transfer completed";

  Transfer transfer = transfers_[handle];
  transfers_.erase(handle);

  DCHECK_GE(handle->actual_length, 0) << "Negative actual length received";
  size_t actual_length =
      static_cast<size_t>(std::max(handle->actual_length, 0));

  DCHECK(transfer.length >= actual_length) <<
      "data too big for our buffer (libusb failure?)";

  scoped_refptr<net::IOBuffer> buffer = transfer.buffer;
  switch (transfer.transfer_type) {
    case USB_TRANSFER_CONTROL:
      // If the transfer is a control transfer we do not expose the control
      // setup header to the caller. This logic strips off the header if
      // present before invoking the callback provided with the transfer.
      if (actual_length > 0) {
        CHECK(transfer.length >= LIBUSB_CONTROL_SETUP_SIZE) <<
            "buffer was not correctly set: too small for the control header";

        if (transfer.length >= actual_length &&
            actual_length >= LIBUSB_CONTROL_SETUP_SIZE) {
          // If the payload is zero bytes long, pad out the allocated buffer
          // size to one byte so that an IOBuffer of that size can be allocated.
          scoped_refptr<net::IOBuffer> resized_buffer = new net::IOBuffer(
              std::max(actual_length, static_cast<size_t>(1)));
          memcpy(resized_buffer->data(),
                 buffer->data() + LIBUSB_CONTROL_SETUP_SIZE,
                 actual_length);
          buffer = resized_buffer;
        }
      }
      break;

    case USB_TRANSFER_ISOCHRONOUS:
      // Isochronous replies might carry data in the different isoc packets even
      // if the transfer actual_data value is zero. Furthermore, not all of the
      // received packets might contain data, so we need to calculate how many
      // data bytes we are effectively providing and pack the results.
      if (actual_length == 0) {
        size_t packet_buffer_start = 0;
        for (int i = 0; i < handle->num_iso_packets; ++i) {
          PlatformUsbIsoPacketDescriptor packet = &handle->iso_packet_desc[i];
          if (packet->actual_length > 0) {
            // We don't need to copy as long as all packets until now provide
            // all the data the packet can hold.
            if (actual_length < packet_buffer_start) {
              CHECK(packet_buffer_start + packet->actual_length <=
                    transfer.length);
              memmove(buffer->data() + actual_length,
                      buffer->data() + packet_buffer_start,
                      packet->actual_length);
            }
            actual_length += packet->actual_length;
          }

          packet_buffer_start += packet->length;
        }
      }
      break;

    case USB_TRANSFER_BULK:
    case USB_TRANSFER_INTERRUPT:
      break;

    default:
      NOTREACHED() << "Invalid usb transfer type";
      break;
  }

  transfer.message_loop_proxy->PostTask(
      FROM_HERE,
      base::Bind(transfer.callback,
                 ConvertTransferStatus(handle->status),
                 buffer,
                 actual_length));

  // Must release interface first before actually delete this.
  transfer.claimed_interface = NULL;
}

bool UsbDeviceHandle::ClaimInterface(const int interface_number) {
  DCHECK(thread_checker_.CalledOnValidThread());
  if (!device_) return false;
  if (ContainsKey(claimed_interfaces_, interface_number)) return true;

  scoped_refptr<InterfaceClaimer> claimer =
      new InterfaceClaimer(this, interface_number);

  if (claimer->Claim()) {
    claimed_interfaces_[interface_number]= claimer;
    RefreshEndpointMap();
    return true;
  }
  return false;
}

bool UsbDeviceHandle::ReleaseInterface(const int interface_number) {
  DCHECK(thread_checker_.CalledOnValidThread());
  if (!device_) return false;
  if (!ContainsKey(claimed_interfaces_, interface_number)) return false;

  // Cancel all the transfers on that interface.
  InterfaceClaimer* interface_claimer =
      claimed_interfaces_[interface_number].get();
  for (TransferMap::iterator it = transfers_.begin();
      it != transfers_.end(); ++it) {
    if (it->second.claimed_interface.get() == interface_claimer)
      libusb_cancel_transfer(it->first);
  }
  claimed_interfaces_.erase(interface_number);

  RefreshEndpointMap();
  return true;
}

bool UsbDeviceHandle::SetInterfaceAlternateSetting(
    const int interface_number,
    const int alternate_setting) {
  DCHECK(thread_checker_.CalledOnValidThread());
  if (!device_) return false;
  if (!ContainsKey(claimed_interfaces_, interface_number)) return false;
  const int rv = libusb_set_interface_alt_setting(handle_,
      interface_number, alternate_setting);
  if (rv == 0) {
    claimed_interfaces_[interface_number]->
      set_alternate_setting(alternate_setting);
    RefreshEndpointMap();
    return true;
  }
  return false;
}

bool UsbDeviceHandle::ResetDevice() {
  DCHECK(thread_checker_.CalledOnValidThread());
  if (!device_) return false;

  return libusb_reset_device(handle_) == 0;
}

bool UsbDeviceHandle::GetSerial(base::string16* serial) {
  DCHECK(thread_checker_.CalledOnValidThread());
  PlatformUsbDevice device = libusb_get_device(handle_);
  libusb_device_descriptor desc;

  if (libusb_get_device_descriptor(device, &desc) != LIBUSB_SUCCESS)
    return false;

  if (desc.iSerialNumber == 0)
    return false;

  // Getting supported language ID.
  uint16 langid[128] = { 0 };

  int size = libusb_get_string_descriptor(
      handle_, 0, 0,
      reinterpret_cast<unsigned char*>(&langid[0]), sizeof(langid));
  if (size < 0)
    return false;

  int language_count = (size - 2) / 2;

  for (int i = 1; i <= language_count; ++i) {
    // Get the string using language ID.
    char16 text[256] = { 0 };
    size = libusb_get_string_descriptor(
        handle_, desc.iSerialNumber, langid[i],
        reinterpret_cast<unsigned char*>(&text[0]), sizeof(text));
    if (size <= 2)
      continue;
    if ((text[0] >> 8) != LIBUSB_DT_STRING)
      continue;
    if ((text[0] & 255) > size)
      continue;

    size = size / 2 - 1;
    *serial = base::string16(text + 1, size);
    return true;
  }
  return false;
}

void UsbDeviceHandle::ControlTransfer(const UsbEndpointDirection direction,
    const TransferRequestType request_type, const TransferRecipient recipient,
    const uint8 request, const uint16 value, const uint16 index,
    net::IOBuffer* buffer, const size_t length, const unsigned int timeout,
    const UsbTransferCallback& callback) {
  if (!device_) {
    callback.Run(USB_TRANSFER_DISCONNECT, buffer, 0);
    return;
  }

  const size_t resized_length = LIBUSB_CONTROL_SETUP_SIZE + length;
  scoped_refptr<net::IOBuffer> resized_buffer(new net::IOBufferWithSize(
      resized_length));
  memcpy(resized_buffer->data() + LIBUSB_CONTROL_SETUP_SIZE, buffer->data(),
         length);

  PlatformUsbTransferHandle const transfer = libusb_alloc_transfer(0);
  const uint8 converted_type = CreateRequestType(direction, request_type,
                                                 recipient);
  libusb_fill_control_setup(reinterpret_cast<uint8*>(resized_buffer->data()),
                            converted_type, request, value, index, length);
  libusb_fill_control_transfer(
      transfer,
      handle_,
      reinterpret_cast<uint8*>(resized_buffer->data()),
      PlatformTransferCompletionCallback,
      this,
      timeout);

  BrowserThread::PostTask(
      BrowserThread::FILE,
      FROM_HERE,
      base::Bind(&UsbDeviceHandle::SubmitTransfer,
                 this,
                 transfer,
                 USB_TRANSFER_CONTROL,
                 resized_buffer,
                 resized_length,
                 base::MessageLoopProxy::current(),
                 callback));
}

void UsbDeviceHandle::BulkTransfer(const UsbEndpointDirection direction,
    const uint8 endpoint, net::IOBuffer* buffer, const size_t length,
    const unsigned int timeout, const UsbTransferCallback& callback) {
  if (!device_) {
    callback.Run(USB_TRANSFER_DISCONNECT, buffer, 0);
    return;
  }

  PlatformUsbTransferHandle const transfer = libusb_alloc_transfer(0);
  const uint8 new_endpoint = ConvertTransferDirection(direction) | endpoint;
  libusb_fill_bulk_transfer(transfer, handle_, new_endpoint,
      reinterpret_cast<uint8*>(buffer->data()), length,
      PlatformTransferCompletionCallback, this, timeout);

  BrowserThread::PostTask(
      BrowserThread::FILE,
      FROM_HERE,
      base::Bind(&UsbDeviceHandle::SubmitTransfer,
                 this,
                 transfer,
                 USB_TRANSFER_BULK,
                 make_scoped_refptr(buffer),
                 length,
                 base::MessageLoopProxy::current(),
                 callback));
}

void UsbDeviceHandle::InterruptTransfer(const UsbEndpointDirection direction,
    const uint8 endpoint, net::IOBuffer* buffer, const size_t length,
    const unsigned int timeout, const UsbTransferCallback& callback) {
  if (!device_) {
    callback.Run(USB_TRANSFER_DISCONNECT, buffer, 0);
    return;
  }

  PlatformUsbTransferHandle const transfer = libusb_alloc_transfer(0);
  const uint8 new_endpoint = ConvertTransferDirection(direction) | endpoint;
  libusb_fill_interrupt_transfer(transfer, handle_, new_endpoint,
      reinterpret_cast<uint8*>(buffer->data()), length,
      PlatformTransferCompletionCallback, this, timeout);
  BrowserThread::PostTask(
      BrowserThread::FILE,
      FROM_HERE,
      base::Bind(&UsbDeviceHandle::SubmitTransfer,
                 this,
                 transfer,
                 USB_TRANSFER_INTERRUPT,
                 make_scoped_refptr(buffer),
                 length,
                 base::MessageLoopProxy::current(),
                 callback));
}

void UsbDeviceHandle::IsochronousTransfer(const UsbEndpointDirection direction,
    const uint8 endpoint, net::IOBuffer* buffer, const size_t length,
    const unsigned int packets, const unsigned int packet_length,
    const unsigned int timeout, const UsbTransferCallback& callback) {
  if (!device_) {
    callback.Run(USB_TRANSFER_DISCONNECT, buffer, 0);
    return;
  }

  const uint64 total_length = packets * packet_length;
  CHECK(packets <= length && total_length <= length) <<
      "transfer length is too small";

  PlatformUsbTransferHandle const transfer = libusb_alloc_transfer(packets);
  const uint8 new_endpoint = ConvertTransferDirection(direction) | endpoint;
  libusb_fill_iso_transfer(transfer, handle_, new_endpoint,
      reinterpret_cast<uint8*>(buffer->data()), length, packets,
      PlatformTransferCompletionCallback, this, timeout);
  libusb_set_iso_packet_lengths(transfer, packet_length);

  BrowserThread::PostTask(
      BrowserThread::FILE,
      FROM_HERE,
      base::Bind(&UsbDeviceHandle::SubmitTransfer,
                 this,
                 transfer,
                 USB_TRANSFER_ISOCHRONOUS,
                 make_scoped_refptr(buffer),
                 length,
                 base::MessageLoopProxy::current(),
                 callback));
}

void UsbDeviceHandle::RefreshEndpointMap() {
  DCHECK(thread_checker_.CalledOnValidThread());
  endpoint_map_.clear();
  for (ClaimedInterfaceMap::iterator it = claimed_interfaces_.begin();
      it != claimed_interfaces_.end(); ++it) {
    scoped_refptr<const UsbInterfaceDescriptor> interface_desc =
        interfaces_->GetInterface(it->first)->GetAltSetting(
            it->second->alternate_setting());
    for (size_t i = 0; i < interface_desc->GetNumEndpoints(); i++) {
      scoped_refptr<const UsbEndpointDescriptor> endpoint =
          interface_desc->GetEndpoint(i);
      endpoint_map_[endpoint->GetAddress()] = it->first;
    }
  }
}

scoped_refptr<UsbDeviceHandle::InterfaceClaimer>
    UsbDeviceHandle::GetClaimedInterfaceForEndpoint(unsigned char endpoint) {
  unsigned char address = endpoint & LIBUSB_ENDPOINT_ADDRESS_MASK;
  if (ContainsKey(endpoint_map_, address))
    return claimed_interfaces_[endpoint_map_[address]];
  return NULL;
}

void UsbDeviceHandle::SubmitTransfer(
    PlatformUsbTransferHandle handle,
    UsbTransferType transfer_type,
    net::IOBuffer* buffer,
    const size_t length,
    scoped_refptr<base::MessageLoopProxy> message_loop_proxy,
    const UsbTransferCallback& callback) {
  DCHECK(thread_checker_.CalledOnValidThread());
  if (!device_) {
    message_loop_proxy->PostTask(
        FROM_HERE,
        base::Bind(callback, USB_TRANSFER_DISCONNECT,
                   make_scoped_refptr(buffer), 0));
  }

  Transfer transfer;
  transfer.transfer_type = transfer_type;
  transfer.buffer = buffer;
  transfer.length = length;
  transfer.callback = callback;
  transfer.message_loop_proxy = message_loop_proxy;

  // It's OK for this method to return NULL. libusb_submit_transfer will fail if
  // it requires an interface we didn't claim.
  transfer.claimed_interface = GetClaimedInterfaceForEndpoint(handle->endpoint);

  if (libusb_submit_transfer(handle) == LIBUSB_SUCCESS) {
    transfers_[handle] = transfer;
  } else {
    message_loop_proxy->PostTask(
        FROM_HERE,
        base::Bind(callback, USB_TRANSFER_ERROR,
                   make_scoped_refptr(buffer), 0));
  }
}

void UsbDeviceHandle::InternalClose() {
  DCHECK(thread_checker_.CalledOnValidThread());
  if (!device_) return;

  // Cancel all the transfers.
  for (TransferMap::iterator it = transfers_.begin();
      it != transfers_.end(); ++it) {
    // The callback will be called some time later.
    libusb_cancel_transfer(it->first);
  }

  // Attempt-release all the interfaces.
  // It will be retained until the transfer cancellation is finished.
  claimed_interfaces_.clear();

  // Cannot close device handle here. Need to wait for libusb_cancel_transfer to
  // finish.
  device_ = NULL;
}


text:
<form class="form-horizontal">
    <fieldset>
        <legend> Create a New Recipe </legend>

            Title

                <input type="email" class="form-control" id="title" placeholder="Enter the name of your recipe.">

            Image URL (optional)

                <input type="text" class="form-control" id="image" placeholder="Place a .jpg/.png-ending link to an image here.">

            Prep Time

                        <input type="email" class="form-control" id="preptime" placeholder="Enter the prep time of this recipe.">

                    <select class="form-control" id="preptimeunit">
                        <option>sec(s)</option>
                        <option>min(s)</option>
                        <option>hr(s)</option>
                        <option>day(s)</option>
                        <option>week(s)</option>
                    </select>

            Cook Time

                        <input type="email" class="form-control" id="cooktime" placeholder="Enter the cook time of this recipe.">

                    <select class="form-control" id="cooktimeunit">
                        <option>sec(s)</option>
                        <option>min(s)</option>
                        <option>hr(s)</option>
                        <option>day(s)</option>
                        <option>week(s)</option>
                    </select>

            Notes

                Enter comments or notes about the recipe below.
                <textarea class="form-control" rows="4" id="notes"></textarea>

            Ingredients
            Add Ingredients

                        <input type="text" class="form-control" id="name" placeholder="Enter the name of your ingredient.">
                        <input type="text" class="form-control" id="url" placeholder="Optional: Enter URL link to ingredient">

                                    <input type="text" class="form-control" id="amount" placeholder="Enter amount of ingredient here.">

                                    <input type="text" class="form-control" id="amountunit" placeholder="Enter amount unit here.">

            Steps
            Add Steps

                        <input type="text" class="form-control" id="instruction" placeholder="Enter the instruction for this step of the recipe.">

                                    <input type="text" class="form-control" id="time" placeholder="Enter amount of time.">

                                    <select class="form-control" id="timeunit">
                                        <option>sec(s)</option>
                                        <option>min(s)</option>
                                        <option>hr(s)</option>
                                        <option>day(s)</option>
                                        <option>week(s)</option>
                                    </select>

            Tags
            Add Tags

                        <input type="text" class="form-control" id="name" placeholder="Enter the tag you would like to add.">

            Private
            <input id="private" type="checkbox">

                    Create

                    Cancel

    </fieldset>
</form>


text:
/**
* Get a Report Default File
*
* @license MIT
*
* @author Steven Velozo <steven@velozo.com>
* @module Tidings
*/
/**
* Get the Default File for a particular report
*/
module.exports = (pRequest, pResponse, fNext) =>
{
	const tmpUUID = pRequest.params.UUID;
	if ((typeof(tmpUUID) !== 'string') || (tmpUUID.length < 1))
	{
		// Invalid UUID
		return pRequest.Tidings.commonservices.sendCodedError('Error retrieving report File: invalid UUID', {}, pRequest, pResponse, fNext);
	}

	pRequest.Tidings.commonservices.log.info('Delivering the default file for ' + tmpUUID);
	// Get the manifest
	pRequest.Tidings.getReportStatus(tmpUUID,
		(pManifestError, pManifestData) =>
		{
			if (pManifestError)
			{
				return pRequest.Tidings.commonservices.sendCodedError('Error retrieving report Manifest for default file: invalid UUID', {}, pRequest, pResponse, fNext);
			}

			const tmpManifest = JSON.parse(pManifestData);
			pRequest.Tidings.libraries.DropBag.readFile({Stream: true, File: tmpManifest.Metadata.DefaultFile, Path: pRequest.Tidings.fable.settings.Tidings.ReportOutputFolder + tmpUUID + '/Stage' },
				(pError, pData) =>
				{
					if (pError)
					{
						return pRequest.Tidings.commonservices.sendCodedError('Error retrieving report default File: ' + pError, {}, pRequest, pResponse, fNext);
					}

					pResponse.header('Content-Type', pData.contentType);
					pResponse.header('Content-Length', pData.length);

					const tmpStream = pData.getStream();

					tmpStream.pipe(pResponse);
					tmpStream.on('error', (pError) =>
					{
						return fNext(pError);
					});
					tmpStream.once
					(
						'end',
						fNext
					);
				}
			);
		}
	);
};


text:
module Giftrocket
  class Gift

    attr_accessor :id, :order_id, :amount, :catalog, :message, :style_id, :status, :recipient, :sender, :events, :redemption_methods, :raw

    def initialize(attributes)
      attributes = attributes.with_indifferent_access
      self.raw = attributes
      self.id = attributes[:id]
      self.order_id = attributes[:order_id]
      self.amount = attributes[:amount]
      self.message = attributes[:message]
      self.style_id = attributes[:style_id]
      self.status = attributes[:status]
      self.sender = attributes[:sender]
      self.recipient = Giftrocket::User.new(attributes[:recipient])
      self.events = attributes[:events]
      self.catalog = attributes[:catalog]
      self.redemption_methods = attributes[:redemption_methods]
    end

    def self.list(filters={})
      response = Giftrocket::Request.get(
        'gifts',
        query: filters.merge(Giftrocket.default_options),
        format: 'json'
      )[:gifts].map do |gift_attributes|
        Giftrocket::Gift.new(gift_attributes)
      end
    end

    def self.retrieve(id)
      response = Giftrocket::Request.get "gifts/#{id}",
                                         query: Giftrocket.default_options,
                                         format: 'json'
      Giftrocket::Gift.new(response[:gift])
    end
  end
end


text:
//  Copyright 2004 The Apache Software Foundation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package org.apache.tapestry.workbench.tree.examples.fsmodel;

import java.util.Date;

import org.apache.tapestry.contrib.tree.model.ITreeNode;

/**
 * @author ceco
 */
public interface IFileSystemTreeNode extends ITreeNode {
    String getAbsolutePath();
    AssetsHolder getAssets();
    Date getDate();
}


text:
author: JeremyKelley
ms.author: JeremyKe
ms.date: 09/10/2017
title: Audio - OneDrive API
ms.localizationpriority: Medium
---
# Audio facet

The **Audio** resource groups audio-related properties on an item into a single structure.

If a [**DriveItem**](driveitem.md) has a non-null **audio** facet, the item represents an audio file.
The properties of the **Audio** resource are populated by extracting metadata from the file.

## JSON representation

<!-- { "blockType": "resource", "@odata.type": "microsoft.graph.audio" } -->
```json
{
  "album": "string",
  "albumArtist": "string",
  "artist": "string",
  "bitrate": 128,
  "composers": "string",
  "copyright": "string",
  "disc": 0,
  "discCount": 0,
  "duration": 567,
  "genre": "string",
  "hasDrm": false,
  "isVariableBitrate": false,
  "title": "string",
  "track": 1,
  "trackCount": 16,
  "year": 2014
}
```

## Properties

| Property name         | Type    | Description                                                          |
|:----------------------|:--------|:---------------------------------------------------------------------|
| **album**             | string  | The title of the album for this audio file.                          |
| **albumArtist**       | string  | The artist named on the album for the audio file.                    |
| **artist**            | string  | The performing artist for the audio file.                            |
| **bitrate**           | Int64   | Bitrate expressed in kbps.                                           |
| **composers**         | string  | The name of the composer of the audio file.                          |
| **copyright**         | string  | Copyright information for the audio file.                            |
| **disc**              | Int16   | The number of the disc this audio file came from.                    |
| **discCount**         | Int16   | The total number of discs in this album.                             |
| **duration**          | Int64   | Duration of the audio file, expressed in milliseconds                |
| **genre**             | string  | The genre of this audio file.                                        |
| **hasDrm**            | boolean | Indicates if the file is protected with digital rights management.   |
| **isVariableBitrate** | boolean | Indicates if the file is encoded with a variable bitrate.            |
| **title**             | string  | The title of the audio file.                                         |
| **track**             | Int32   | The number of the track on the original disc for this audio file.    |
| **trackCount**        | Int32   | The total number of tracks on the original disc for this audio file. |
| **year**              | Int32   | The year the audio file was recorded.                                |

[item-resource]: ../resources/driveitem.md

## Remarks

For more information about the facets on a DriveItem, see [DriveItem](driveitem.md).

Audio facet is not supported on SharePoint Server 2016.

<!-- {
  "type": "#page.annotation",
  "description": "The audio facet provides information about music or audio metadata.",
  "keywords": "music,audio,metadata,onedrive",
  "section": "documentation",
  "tocPath": "Facets/Audio"
} -->