Esempio n. 1
0
NS_IMETHODIMP
nsTextControlFrame::GetSelectionRange(PRInt32* aSelectionStart,
                                      PRInt32* aSelectionEnd,
                                      SelectionDirection* aDirection)
{
  // make sure we have an editor
  nsresult rv = EnsureEditorInitialized();
  NS_ENSURE_SUCCESS(rv, rv);

  if (aSelectionStart) {
    *aSelectionStart = 0;
  }
  if (aSelectionEnd) {
    *aSelectionEnd = 0;
  }
  if (aDirection) {
    *aDirection = eNone;
  }

  nsCOMPtr<nsITextControlElement> txtCtrl = do_QueryInterface(GetContent());
  NS_ASSERTION(txtCtrl, "Content not a text control element");
  nsISelectionController* selCon = txtCtrl->GetSelectionController();
  NS_ENSURE_TRUE(selCon, NS_ERROR_FAILURE);
  nsCOMPtr<nsISelection> selection;
  rv = selCon->GetSelection(nsISelectionController::SELECTION_NORMAL, getter_AddRefs(selection));  
  NS_ENSURE_SUCCESS(rv, rv);
  NS_ENSURE_TRUE(selection, NS_ERROR_FAILURE);

  PRInt32 numRanges = 0;
  selection->GetRangeCount(&numRanges);

  if (numRanges < 1)
    return NS_OK;

  // We only operate on the first range in the selection!

  if (aDirection) {
    nsCOMPtr<nsISelectionPrivate> selPriv = do_QueryInterface(selection);
    if (selPriv) {
      nsDirection direction = selPriv->GetSelectionDirection();
      if (direction == eDirNext) {
        *aDirection = eForward;
      } else if (direction == eDirPrevious) {
        *aDirection = eBackward;
      } else {
        NS_NOTREACHED("Invalid nsDirection enum value");
      }
    }
  }

  if (!aSelectionStart || !aSelectionEnd) {
    return NS_OK;
  }

  nsCOMPtr<nsIDOMRange> firstRange;
  rv = selection->GetRangeAt(0, getter_AddRefs(firstRange));
  NS_ENSURE_SUCCESS(rv, rv);
  NS_ENSURE_TRUE(firstRange, NS_ERROR_FAILURE);

  nsCOMPtr<nsIDOMNode> startNode, endNode;
  PRInt32 startOffset = 0, endOffset = 0;

  // Get the start point of the range.

  rv = firstRange->GetStartContainer(getter_AddRefs(startNode));
  NS_ENSURE_SUCCESS(rv, rv);
  NS_ENSURE_TRUE(startNode, NS_ERROR_FAILURE);

  rv = firstRange->GetStartOffset(&startOffset);
  NS_ENSURE_SUCCESS(rv, rv);

  // Get the end point of the range.

  rv = firstRange->GetEndContainer(getter_AddRefs(endNode));
  NS_ENSURE_SUCCESS(rv, rv);
  NS_ENSURE_TRUE(endNode, NS_ERROR_FAILURE);

  rv = firstRange->GetEndOffset(&endOffset);
  NS_ENSURE_SUCCESS(rv, rv);

  // Convert the start point to a selection offset.

  rv = DOMPointToOffset(startNode, startOffset, aSelectionStart);
  NS_ENSURE_SUCCESS(rv, rv);

  // Convert the end point to a selection offset.

  return DOMPointToOffset(endNode, endOffset, aSelectionEnd);
}
Esempio n. 2
0
void AMessageForm::InitControls()
{
	AutoDisableLayout adl(m_pUICore);

	int delta = 5;
	int iIconWidth = 48;
	//初始化图标
	AContainer* pContent = GetContent();
	
	
	int iconID=0;
	switch(m_iMessageType)
	{
	case MESSAGE_TYPE_INFOR:iconID = IDI_ICON_INFOR; break;
	case MESSAGE_TYPE_WARN:iconID = IDI_ICON_WARNING;break;
	case MESSAGE_TYPE_QUESTION:iconID = IDI_ICON_QUESTION;break;
	case MESSAGE_TYPE_ERROR:iconID = IDI_ICON_ERROR;break;
	case MESSAGE_TYPE_WAIT:iconID = IDI_ICON_WAITING;break;
	default:
		break;
	}
	if( iconID != 0 )
	{
		AImageControl* pImageControl = new AImageControl(pContent);
		pImageControl->SetLeft(delta);
		pImageControl->SetTop(delta);
		pImageControl->SetWidth(iIconWidth);
		pImageControl->SetHeight(iIconWidth);
		//pImageControl->SetDrawStyle(idsStretch);

		AImage* pImage = AImage::CreateImage();
		pImage->LoadIcon( ::LoadIcon(g_hInstance,MAKEINTRESOURCE(iconID)) );
		pImageControl->SetGraphic(pImage);
	}
	

	//初始化文本
	ACanvas* cs = m_pUICore->GetCanvas();
	AStringArray sa;
	sa.FromString(m_sUserText,_T("\n"));
	ASize szText(0,0);
	AFont f;//缺省字体
	int iw=0;
	int ih=0;
	for(int i=0;i<sa.GetCount();i++)
	{
		
		ASize sz( (sa[i].Length()) * f.GetSize(),f.GetSize());//缺省度量
		if( cs ) sz = cs->MeasureText(sa[i]);
		if( sz.cx > szText.cx ) szText.cx = sz.cx;
		szText.cy += sz.cy + 6;
	}
	szText.cy += 23;
	ALabel* pTextLabel = new ALabel(pContent);
	if( m_iMessageType == MESSAGE_TYPE_INPUT )
	{
		pTextLabel->SetLeft(16);
		pTextLabel->SetTop(10);
		pTextLabel->SetWidth(300);
		pTextLabel->SetHeight(20);

		AEdit* pEdit = new AEdit(pContent);
		pEdit->SetLeft(16);
		pEdit->SetTop(40);
		pEdit->SetWidth(200);
		pEdit->SetHeight(22);
		pEdit->SetName(_T("Input"));
	}
	else
	{
		pTextLabel->SetLeft(delta*2+96);
		pTextLabel->SetTop(delta);
		pTextLabel->SetWidth(szText.cx);
		pTextLabel->SetHeight(szText.cy+2 * delta);
	}
	
	pTextLabel->SetText(m_sUserText);
	pTextLabel->SetTextAlign(taLeftMiddle);
	//pTextLabel->Font.SetSize(16);
	//pTextLabel->SetUseSkin(false);

	int iWidth = delta * 3 + 32 + szText.cx+100;
	if( iWidth < 320 ) iWidth = 320;
	if( m_iMessageType == MESSAGE_TYPE_INPUT ) iWidth = 320;
	this->SetWidth(iWidth);
	this->SetHeight(28+(iIconWidth > szText.cy ? iIconWidth : szText.cy )+46+delta*2);
	if( m_iMessageType == MESSAGE_TYPE_INPUT ) this->SetHeight(160);

	//初始化按钮
	int iButtonCount = 0;
	if( m_dbs & dbOK) iButtonCount ++;
	if( m_dbs & dbCancel ) iButtonCount ++;
	if( m_dbs & dbYes ) iButtonCount ++;
	if( m_dbs & dbNo ) iButtonCount ++;
	int iButtonWidth = 72;
	int iButtonHeight = 22;
	if( iButtonCount > 0 )
	{
		int iButtonSpace = 10;//间隔距离
		int iLeft = iButtonSpace * (iButtonCount-1) + iButtonWidth * iButtonCount;
		iLeft = (iWidth - iLeft)/2;
		int index=0;
		AContainer* pButtonContainer = GetBottomContainer();
		
		if( m_dbs & dbOK )
		{
			m_pOKButton = new AButton(pButtonContainer);
			m_pOKButton->SetWidth( iButtonWidth );
			m_pOKButton->SetLeft( iLeft );
			m_pOKButton->SetHeight( iButtonHeight );
			m_pOKButton->SetTop( 10 );
			m_pOKButton->SetText(_T("确定"));
			EVENT_CONNECT(m_pOKButton,OnClick,OnOKClick);
			iLeft += iButtonWidth+iButtonSpace;
		}

		if( m_dbs & dbYes )
		{
			m_pYesButton = new AButton(pButtonContainer);
			m_pYesButton->SetWidth( iButtonWidth );
			m_pYesButton->SetLeft( iLeft );
			m_pYesButton->SetHeight( iButtonHeight );
			m_pYesButton->SetTop( 10 );
			m_pYesButton->SetText(_T("是"));
			EVENT_CONNECT(m_pYesButton,OnClick,OnYesClick);
			iLeft += iButtonWidth+iButtonSpace;
		}

		if( m_dbs & dbNo )
		{
			m_pNoButton = new AButton(pButtonContainer);
			m_pNoButton->SetWidth( iButtonWidth );
			m_pNoButton->SetLeft( iLeft );
			m_pNoButton->SetHeight( iButtonHeight );
			m_pNoButton->SetTop( 10 );
			m_pNoButton->SetText(_T("否"));
			EVENT_CONNECT(m_pNoButton,OnClick,OnNoClick);
			iLeft += iButtonWidth+iButtonSpace;
		}

		if( m_dbs & dbCancel )
		{
			m_pCancelButton = new AButton(pButtonContainer);
			m_pCancelButton->SetWidth( iButtonWidth );
			m_pCancelButton->SetLeft( iLeft );
			m_pCancelButton->SetHeight( iButtonHeight );
			m_pCancelButton->SetTop( 10 );
			m_pCancelButton->SetText(_T("取消"));
			EVENT_CONNECT(m_pCancelButton,OnClick,OnCancelClick);
			iLeft += iButtonWidth+iButtonSpace;
		}
	}

	//初始化标题
	switch(m_iMessageType)
	{
	case MESSAGE_TYPE_INFOR:this->SetText(_T("提示"));break;
	case MESSAGE_TYPE_WARN:this->SetText(_T("警告"));break;
	case MESSAGE_TYPE_QUESTION:this->SetText(_T("询问"));break;
	case MESSAGE_TYPE_ERROR:this->SetText(_T("错误"));break;
	case MESSAGE_TYPE_WAIT:this->SetText(_T("等待"));break;
	default:
		break;
	}
}
Esempio n. 3
0
/**
 * This is called when our browse button is clicked
 */
nsresult 
nsFileControlFrame::MouseClick(nsIDOMEvent* aMouseEvent)
{
  // only allow the left button
  nsCOMPtr<nsIDOMMouseEvent> mouseEvent = do_QueryInterface(aMouseEvent);
  nsCOMPtr<nsIDOMNSUIEvent> uiEvent = do_QueryInterface(aMouseEvent);
  NS_ENSURE_STATE(uiEvent);
  PRBool defaultPrevented = PR_FALSE;
  uiEvent->GetPreventDefault(&defaultPrevented);
  if (defaultPrevented) {
    return NS_OK;
  }

  PRUint16 whichButton;
  if (NS_FAILED(mouseEvent->GetButton(&whichButton)) || whichButton != 0) {
    return NS_OK;
  }

  PRInt32 clickCount;
  if (NS_FAILED(mouseEvent->GetDetail(&clickCount)) || clickCount > 1) {
    return NS_OK;
  }

  nsresult result;

  // Get parent nsIDOMWindowInternal object.
  nsIContent* content = GetContent();
  if (!content)
    return NS_ERROR_FAILURE;

  nsCOMPtr<nsIDocument> doc = content->GetDocument();
  if (!doc)
    return NS_ERROR_FAILURE;

  // Get Loc title
  nsXPIDLString title;
  nsContentUtils::GetLocalizedString(nsContentUtils::eFORMS_PROPERTIES,
                                     "FileUpload", title);

  nsCOMPtr<nsIFilePicker> filePicker = do_CreateInstance("@mozilla.org/filepicker;1");
  if (!filePicker)
    return NS_ERROR_FAILURE;

  result = filePicker->Init(doc->GetWindow(), title, nsIFilePicker::modeOpen);
  if (NS_FAILED(result))
    return result;

  // Set filter "All Files"
  filePicker->AppendFilters(nsIFilePicker::filterAll);

  // Set default directry and filename
  nsAutoString defaultName;
  GetFormProperty(nsGkAtoms::value, defaultName);

  nsCOMPtr<nsILocalFile> currentFile = do_CreateInstance("@mozilla.org/file/local;1");
  if (currentFile && !defaultName.IsEmpty()) {
    result = currentFile->InitWithPath(defaultName);
    if (NS_SUCCEEDED(result)) {
      nsAutoString leafName;
      currentFile->GetLeafName(leafName);
      if (!leafName.IsEmpty()) {
        filePicker->SetDefaultString(leafName);
      }

      // set directory
      nsCOMPtr<nsIFile> parentFile;
      currentFile->GetParent(getter_AddRefs(parentFile));
      if (parentFile) {
        nsCOMPtr<nsILocalFile> parentLocalFile = do_QueryInterface(parentFile, &result);
        if (parentLocalFile)
          filePicker->SetDisplayDirectory(parentLocalFile);
      }
    }
  }

  // Tell our textframe to remember the currently focused value
  mTextFrame->InitFocusedValue();

  // Open dialog
  PRInt16 mode;
  result = filePicker->Show(&mode);
  if (NS_FAILED(result))
    return result;
  if (mode == nsIFilePicker::returnCancel)
    return NS_OK;

  if (!mTextFrame) {
    // We got destroyed while the filepicker was up.  Don't do anything here.
    return NS_OK;
  }
  
  // Set property
  nsCOMPtr<nsILocalFile> localFile;
  result = filePicker->GetFile(getter_AddRefs(localFile));
  if (localFile) {
    nsAutoString unicodePath;
    result = localFile->GetPath(unicodePath);
    if (!unicodePath.IsEmpty()) {
      // Tell mTextFrame that this update of the value is a user initiated
      // change. Otherwise it'll think that the value is being set by a script
      // and not fire onchange when it should.
      PRBool oldState = mTextFrame->GetFireChangeEventState();
      mTextFrame->SetFireChangeEventState(PR_TRUE);
      nsCOMPtr<nsIFileControlElement> fileControl = do_QueryInterface(mContent);
      if (fileControl) {
        fileControl->SetFileName(unicodePath);
      }
      
      mTextFrame->SetFireChangeEventState(oldState);
      // May need to fire an onchange here
      mTextFrame->CheckFireOnChange();
      return NS_OK;
    }
  }

  return NS_FAILED(result) ? result : NS_ERROR_FAILURE;
}
Esempio n. 4
0
HRESULT FakeDevice::FindNext(
                const DWORD                           dwNumObjectsRequested,
    _In_        WpdObjectEnumeratorContext*           pEnumContext,
    _In_        IPortableDevicePropVariantCollection* pObjectIDCollection,
    _Out_opt_   DWORD*                                pdwNumObjectsEnumerated)
{
    HRESULT hr                   = S_OK;
    DWORD   NumObjectsEnumerated = 0;

    if ((pEnumContext        == NULL) ||
        (pObjectIDCollection == NULL))
    {
        hr = E_POINTER;
        CHECK_HR(hr, "Cannot have NULL parameter");
        return hr;
    }

    if (pdwNumObjectsEnumerated)
    {
        *pdwNumObjectsEnumerated = 0;
    }

    // If the enumeration context reports that their are more objects to return, then continue, if not,
    // return an empty results set.
    if (pEnumContext->HasMoreChildrenToEnumerate())
    {
        if (pEnumContext->m_strParentObjectID.CompareNoCase(L"") == 0)
        {
            // We are being asked for the device
            hr = AddStringValueToPropVariantCollection(pObjectIDCollection, m_DeviceContent.ObjectID);
            CHECK_HR(hr, "Failed to add 'DEVICE' object ID to enumeration collection");

            // Update the the number of children we are returning for this enumeration call
            NumObjectsEnumerated++;
        }
        else
        {
            FakeContent* pContent = NULL;
            HRESULT hrGet = GetContent(pEnumContext->m_Scope, pEnumContext->m_strParentObjectID, &pContent);
            CHECK_HR(hrGet, "Failed to get content '%ws'", pEnumContext->m_strParentObjectID);

            if (hrGet == S_OK)
            {
                DWORD dwStartIndex = pEnumContext->m_ChildrenEnumerated;
                for (DWORD i=0; i<dwNumObjectsRequested; i++)
                {
                    FakeContent* pChild = NULL;
                    if (pContent->FindNext(pEnumContext->m_Scope, dwStartIndex, &pChild))
                    {
                        hr = AddStringValueToPropVariantCollection(pObjectIDCollection, pChild->ObjectID);
                        CHECK_HR(hr, "Failed to add object [%ws]", pChild->ObjectID);

                        if (hr == S_OK)
                        {
                            // Update the the number of children we are returning for this enumeration call
                            dwStartIndex++;
                            NumObjectsEnumerated++;
                        }
                    }
                    else
                    {
                        // no more children
                        break;
                    }
                }
            }
        }
    }

    if (hr == S_OK && pdwNumObjectsEnumerated)
    {
        *pdwNumObjectsEnumerated = NumObjectsEnumerated;
    }

    return hr;
}
Esempio n. 5
0
HRESULT FakeDevice::CreatePropertiesOnlyObject(
                ACCESS_SCOPE           Scope,
    _In_        IPortableDeviceValues* pObjectProperties,
    _In_        IPortableDeviceValues* pEventParams,
    _Outptr_result_nullonfailure_      LPWSTR*  ppszNewObjectID)
{
    HRESULT      hr;
    LPWSTR       pszParentID = NULL;
    FakeContent* pParent     = NULL;
    FakeContent* pNewObject  = NULL;

    if ((pObjectProperties == NULL) ||
        (pEventParams      == NULL) ||
        (ppszNewObjectID   == NULL))
    {
        hr = E_POINTER;
        CHECK_HR(hr, "Cannot have NULL parameter");
        return hr;
    }

    *ppszNewObjectID = NULL;

    // Get WPD_OBJECT_PARENT_ID
    hr = pObjectProperties->GetStringValue(WPD_OBJECT_PARENT_ID, &pszParentID);
    CHECK_HR(hr, "Failed to get WPD_OBJECT_PARENT_ID");

    // Check if it is within our current access scope
    if (SUCCEEDED(hr))
    {
        hr = GetContent(Scope, pszParentID, &pParent);
        CHECK_HR(hr, "Failed to get content '%ws'", pszParentID);
    }

    if (SUCCEEDED(hr))
    {
        hr = pParent->CreatePropertiesOnlyObject(pObjectProperties, &m_dwLastObjectID, &pNewObject);
        CHECK_HR(hr, "Failed to create properties only object with parent '%ws'", pszParentID);
    }

    if (SUCCEEDED(hr))
    {
        *ppszNewObjectID = AtlAllocTaskWideString(pNewObject->ObjectID);
        if (*ppszNewObjectID == NULL)
        {
            hr = E_OUTOFMEMORY;
            CHECK_HR(hr, "Failed to allocate memory for created object ID");
        }

        HRESULT hrEvent = pEventParams->SetGuidValue(WPD_EVENT_PARAMETER_EVENT_ID, WPD_EVENT_OBJECT_ADDED);
        CHECK_HR(hrEvent, "Failed to add WPD_EVENT_PARAMETER_EVENT_ID");

        if (hrEvent == S_OK)
        {
            hrEvent = pEventParams->SetStringValue(WPD_OBJECT_PERSISTENT_UNIQUE_ID, pNewObject->PersistentUniqueID);
            CHECK_HR(hrEvent, "Failed to add WPD_OBJECT_PERSISTENT_UNIQUE_ID");
        }

        if (hrEvent == S_OK)
        {
            hrEvent = pEventParams->SetStringValue(WPD_EVENT_PARAMETER_OBJECT_PARENT_PERSISTENT_UNIQUE_ID, pNewObject->ParentPersistentUniqueID);
            CHECK_HR(hrEvent, "Failed to add WPD_EVENT_PARAMETER_OBJECT_PARENT_PERSISTENT_UNIQUE_ID");
        }

        if (hrEvent == S_OK)
        {
            // Adding this event parameter will allow WPD to scope this event to the container functional object
            hrEvent = pEventParams->SetStringValue(WPD_OBJECT_CONTAINER_FUNCTIONAL_OBJECT_ID, pNewObject->ContainerFunctionalObjectID);
            CHECK_HR(hrEvent, "Failed to add WPD_OBJECT_CONTAINER_FUNCTIONAL_OBJECT_ID");
        }
    }

    CoTaskMemFree(pszParentID);
    return hr;
}
Esempio n. 6
0
nsresult
nsTextControlFrame::EnsureEditorInitialized()
{
  // This method initializes our editor, if needed.

  // This code used to be called from CreateAnonymousContent(), but
  // when the editor set the initial string, it would trigger a
  // PresShell listener which called FlushPendingNotifications()
  // during frame construction. This was causing other form controls
  // to display wrong values.  Additionally, calling this every time
  // a text frame control is instantiated means that we're effectively
  // instantiating the editor for all text fields, even if they
  // never get used.  So, now this method is being called lazily only
  // when we actually need an editor.

  // Check if this method has been called already.
  // If so, just return early.
  if (mUseEditor)
    return NS_OK;

  NS_TIME_FUNCTION;

  nsIDocument* doc = mContent->GetCurrentDoc();
  NS_ENSURE_TRUE(doc, NS_ERROR_FAILURE);

  nsWeakFrame weakFrame(this);

  // Flush out content on our document.  Have to do this, because script
  // blockers don't prevent the sink flushing out content and notifying in the
  // process, which can destroy frames.
  doc->FlushPendingNotifications(Flush_ContentAndNotify);
  NS_ENSURE_TRUE(weakFrame.IsAlive(), NS_ERROR_FAILURE);

  // Make sure that editor init doesn't do things that would kill us off
  // (especially off the script blockers it'll create for its DOM mutations).
  nsAutoScriptBlocker scriptBlocker;

  // Time to mess with our security context... See comments in GetValue()
  // for why this is needed.
  nsCxPusher pusher;
  pusher.PushNull();

  // Make sure that we try to focus the content even if the method fails
  class EnsureSetFocus {
  public:
    explicit EnsureSetFocus(nsTextControlFrame* aFrame)
      : mFrame(aFrame) {}
    ~EnsureSetFocus() {
      if (nsContentUtils::IsFocusedContent(mFrame->GetContent()))
        mFrame->SetFocus(true, false);
    }
  private:
    nsTextControlFrame *mFrame;
  };
  EnsureSetFocus makeSureSetFocusHappens(this);

#ifdef DEBUG
  // Make sure we are not being called again until we're finished.
  // If reentrancy happens, just pretend that we don't have an editor.
  const EditorInitializerEntryTracker tracker(*this);
  NS_ASSERTION(!tracker.EnteredMoreThanOnce(),
               "EnsureEditorInitialized has been called while a previous call was in progress");
#endif

  // Create an editor for the frame, if one doesn't already exist
  nsCOMPtr<nsITextControlElement> txtCtrl = do_QueryInterface(GetContent());
  NS_ASSERTION(txtCtrl, "Content not a text control element");
  nsresult rv = txtCtrl->CreateEditor();
  NS_ENSURE_SUCCESS(rv, rv);

  // Turn on mUseEditor so that subsequent calls will use the
  // editor.
  mUseEditor = true;

  // Set the selection to the beginning of the text field.
  if (weakFrame.IsAlive()) {
    SetSelectionEndPoints(0, 0);
  }

  return NS_OK;
}
Esempio n. 7
0
//IMPLEMENTING NS_IFORMCONTROLFRAME
void nsTextControlFrame::SetFocus(bool aOn, bool aRepaint)
{
  nsCOMPtr<nsITextControlElement> txtCtrl = do_QueryInterface(GetContent());
  NS_ASSERTION(txtCtrl, "Content not a text control element");

  // Revoke the previous scroll event if one exists
  mScrollEvent.Revoke();

  if (!aOn) {
    return;
  }

  nsISelectionController* selCon = txtCtrl->GetSelectionController();
  if (!selCon)
    return;

  nsCOMPtr<nsISelection> ourSel;
  selCon->GetSelection(nsISelectionController::SELECTION_NORMAL, 
    getter_AddRefs(ourSel));
  if (!ourSel) return;

  nsIPresShell* presShell = PresContext()->GetPresShell();
  nsRefPtr<nsCaret> caret = presShell->GetCaret();
  if (!caret) return;

  // Scroll the current selection into view
  nsISelection *caretSelection = caret->GetCaretDOMSelection();
  const bool isFocusedRightNow = ourSel == caretSelection;
  if (!isFocusedRightNow) {
    // Don't scroll the current selection if we've been focused using the mouse.
    PRUint32 lastFocusMethod = 0;
    nsIDocument* doc = GetContent()->GetCurrentDoc();
    if (doc) {
      nsIFocusManager* fm = nsFocusManager::GetFocusManager();
      if (fm) {
        fm->GetLastFocusMethod(doc->GetWindow(), &lastFocusMethod);
      }
    }
    if (!(lastFocusMethod & nsIFocusManager::FLAG_BYMOUSE)) {
      nsRefPtr<ScrollOnFocusEvent> event = new ScrollOnFocusEvent(this);
      nsresult rv = NS_DispatchToCurrentThread(event);
      if (NS_SUCCEEDED(rv)) {
        mScrollEvent = event;
      }
    }
  }

  // tell the caret to use our selection
  caret->SetCaretDOMSelection(ourSel);

  // mutual-exclusion: the selection is either controlled by the
  // document or by the text input/area. Clear any selection in the
  // document since the focus is now on our independent selection.

  nsCOMPtr<nsISelectionController> selcon = do_QueryInterface(presShell);
  nsCOMPtr<nsISelection> docSel;
  selcon->GetSelection(nsISelectionController::SELECTION_NORMAL,
    getter_AddRefs(docSel));
  if (!docSel) return;

  bool isCollapsed = false;
  docSel->GetIsCollapsed(&isCollapsed);
  if (!isCollapsed)
    docSel->RemoveAllRanges();
}
TEST_F(EntityFixture, PlayerTest) {
    GetInput().assignKey(sf::Keyboard::W, Input::Up);
    GetInput().assignKey(sf::Keyboard::A, Input::Left);
    GetInput().assignKey(sf::Keyboard::S, Input::Down);
    GetInput().assignKey(sf::Keyboard::D, Input::Right);
    GetInput().assignMouseButton(sf::Mouse::Left, Input::Shoot);
    GetInput().setMouseLock(true);
    GetWindow().setMouseCursorVisible(false);

    dot.setFillColor(sf::Color::Red);

    // Add behaviors
    playerUpdater = da::BehaviorPtr(new PlayerUpdater(GetView(), GetInput()));
    GetManager().addBehavior(playerUpdater);
    GetManager().addBehavior(velocitiesUpdater);
    GetManager().addBehavior(walker);
    GetManager().addBehavior(poseUpdater);
    GetManager().addBehavior(xformHistorian);

    // Add spatial
    GetRenderer().registerSpatial<SpriteSpatial>();

    // Create entity
    entity = GetManager().create();
    entity->addAttribute(new da::Transform);
    entity->addAttribute(new da::Depth);

    da::TexturePtr texture = GetContent().load<sf::Texture>("mans.png");
    entity->addAttribute(new Sprite(texture));
    entity->addAttribute(new TransformHistory);
    entity->addAttribute(new Collider);
    entity->addAttribute(new Velocities);

    Poses *poses = new Poses;

    Pose pose(6);
    for (unsigned int j = 0; j < DirectionCount; j++) {
        for (unsigned int i = 0; i < pose.getFrameCount(); i++) {
            Pose::Frame frame = {
                sf::IntRect(i * 16, j * 24, 16, 24),
                sf::Vector2f(8, 20)
            };

            pose.setFrame((CardinalDirection)j, i, frame);
        }
    }
    poses->addPose("walk", pose);

    poses->isLoop = true;
    poses->timePerFrame = sf::seconds(0.25f);
    poses->setPose("walk", 0);
    entity->addAttribute(poses);

    Player *player = new Player;
    player->walkSpeed = 100.f;
    player->viewDistance = 40.f;
    entity->addAttribute(player);

    GetManager().refresh(entity);

    Run(update, emptyHandler, draw);
}
Esempio n. 9
0
NS_IMETHODIMP
nsTextControlFrame::GetSelectionRange(PRInt32* aSelectionStart, PRInt32* aSelectionEnd)
{
  // make sure we have an editor
  nsresult rv = EnsureEditorInitialized();
  NS_ENSURE_SUCCESS(rv, rv);

  *aSelectionStart = 0;
  *aSelectionEnd = 0;

  nsCOMPtr<nsITextControlElement> txtCtrl = do_QueryInterface(GetContent());
  NS_ASSERTION(txtCtrl, "Content not a text control element");
  nsISelectionController* selCon = txtCtrl->GetSelectionController();
  NS_ENSURE_TRUE(selCon, NS_ERROR_FAILURE);
  nsCOMPtr<nsISelection> selection;
  rv = selCon->GetSelection(nsISelectionController::SELECTION_NORMAL, getter_AddRefs(selection));  
  NS_ENSURE_SUCCESS(rv, rv);
  NS_ENSURE_TRUE(selection, NS_ERROR_FAILURE);

  PRInt32 numRanges = 0;
  selection->GetRangeCount(&numRanges);

  if (numRanges < 1)
    return NS_OK;

  // We only operate on the first range in the selection!

  nsCOMPtr<nsIDOMRange> firstRange;
  rv = selection->GetRangeAt(0, getter_AddRefs(firstRange));
  NS_ENSURE_SUCCESS(rv, rv);
  NS_ENSURE_TRUE(firstRange, NS_ERROR_FAILURE);

  nsCOMPtr<nsIDOMNode> startNode, endNode;
  PRInt32 startOffset = 0, endOffset = 0;

  // Get the start point of the range.

  rv = firstRange->GetStartContainer(getter_AddRefs(startNode));
  NS_ENSURE_SUCCESS(rv, rv);
  NS_ENSURE_TRUE(startNode, NS_ERROR_FAILURE);

  rv = firstRange->GetStartOffset(&startOffset);
  NS_ENSURE_SUCCESS(rv, rv);

  // Get the end point of the range.

  rv = firstRange->GetEndContainer(getter_AddRefs(endNode));
  NS_ENSURE_SUCCESS(rv, rv);
  NS_ENSURE_TRUE(endNode, NS_ERROR_FAILURE);

  rv = firstRange->GetEndOffset(&endOffset);
  NS_ENSURE_SUCCESS(rv, rv);

  // Convert the start point to a selection offset.

  rv = DOMPointToOffset(startNode, startOffset, aSelectionStart);
  NS_ENSURE_SUCCESS(rv, rv);

  // Convert the end point to a selection offset.

  return DOMPointToOffset(endNode, endOffset, aSelectionEnd);
}
Esempio n. 10
0
BOOL SpeedDialThumbnail::OnInputAction(OpInputAction* action)
{
	switch (action->GetAction())
	{
		case OpInputAction::ACTION_GET_ACTION_STATE:
		{
			OpInputAction* child_action = action->GetChildAction();
			switch (child_action->GetAction())
			{
				case OpInputAction::ACTION_SET_AUTOMATIC_RELOAD:
				{
					INTPTR timeout = child_action->GetActionData();
					SpeedDialData::ReloadPolicy policy = m_entry->GetReloadPolicy();

					if (timeout == 0) // Custom time
					{
						int reload_timeout = m_entry->GetReloadTimeout();
						child_action->SetSelected(policy == SpeedDialData::Reload_UserDefined && !IsStandardTimeoutMenuItem(reload_timeout));
					}
					else if (timeout == SPEED_DIAL_RELOAD_INTERVAL_DEFAULT) // Never
					{
						child_action->SetSelected(policy == SpeedDialData::Reload_NeverSoft || policy == SpeedDialData::Reload_NeverHard);
					}
					else // Fixed time
					{
						int reload_timeout = m_entry->GetReloadTimeout();
						child_action->SetSelected(policy == SpeedDialData::Reload_UserDefined && reload_timeout == timeout);
					}
					return TRUE;
				}

				// Kind of weird wording: This means "let the page decide itself when to reload"
				case OpInputAction::ACTION_DISABLE_AUTOMATIC_RELOAD:
				{
					int reload_timeout = m_entry->GetPreviewRefreshTimeout();
					SpeedDialData::ReloadPolicy policy = m_entry->GetReloadPolicy();
					child_action->SetSelected(policy == SpeedDialData::Reload_PageDefined);
					child_action->SetEnabled(reload_timeout > 0);
					return TRUE;
				}
				case OpInputAction::ACTION_MANAGE:
				{
					const uni_char *type = child_action->GetActionDataString();
					if(type && uni_stricmp(type, UNI_L("extensions")) == 0)
					{
						// action data is set to the id of the speed dial automatically, but we need to override it
						// to get the shortcuts (based on action data = 0) to show up. See DSK-337833.
						child_action->SetActionData(0);
						child_action->SetEnabled(TRUE);
					}
					else
						child_action->SetEnabled(FALSE);

					return TRUE;
				}
			}
			break;
		}

		case OpInputAction::ACTION_RELOAD_THUMBNAIL:
			GetContent()->Refresh();
			return TRUE;


		case OpInputAction::ACTION_SET_AUTOMATIC_RELOAD:
		{
			int timeout = action->GetActionData();

			if (timeout == 0)
			{
				AutoWindowReloadController* controller = OP_NEW(AutoWindowReloadController, (NULL,m_entry));

				RETURN_VALUE_IF_ERROR(ShowDialog(controller, g_global_ui_context, g_application->GetActiveDesktopWindow()),FALSE);	
			}
			else if (timeout == SPEED_DIAL_RELOAD_INTERVAL_DEFAULT) // This means "Never reload"
			{
				DesktopSpeedDial new_entry;
				new_entry.Set(*m_entry);
				new_entry.SetReload(SpeedDialData::Reload_NeverHard, 0, true);
				OpStatus::Ignore(g_speeddial_manager->ReplaceSpeedDial(m_entry, &new_entry));
			}
			else
			{
				DesktopSpeedDial new_entry;
				new_entry.Set(*m_entry);
				new_entry.SetReload(SpeedDialData::Reload_UserDefined, timeout, TRUE);
				OpStatus::Ignore(g_speeddial_manager->ReplaceSpeedDial(m_entry, &new_entry));
			}
			return TRUE;
		}

		// Kind of weird wording: This means "let the page decide itself when to reload"
		case OpInputAction::ACTION_DISABLE_AUTOMATIC_RELOAD:
		{
			int timeout = m_entry->GetPreviewRefreshTimeout();
			DesktopSpeedDial new_entry;
			new_entry.Set(*m_entry);
			new_entry.SetReload(SpeedDialData::Reload_PageDefined, timeout, TRUE);
			OpStatus::Ignore(g_speeddial_manager->ReplaceSpeedDial(m_entry, &new_entry));
			return TRUE;
		}

		case OpInputAction::ACTION_DELETE:
			g_input_manager->InvokeAction(
					OpInputAction::ACTION_THUMB_CLOSE_PAGE,
					g_speeddial_manager->GetSpeedDialActionData(m_entry));
			return TRUE;

		case OpInputAction::ACTION_EDIT_PROPERTIES:
			g_input_manager->InvokeAction(
					OpInputAction::ACTION_THUMB_CONFIGURE,
					g_speeddial_manager->GetSpeedDialActionData(m_entry));
			return TRUE;

		case OpInputAction::ACTION_RELOAD_EXTENSION:
			RETURN_VALUE_IF_ERROR(GetContent()->Refresh(), FALSE);
			return TRUE;
	}

	return GenericThumbnail::OnInputAction(action);
}
Esempio n. 11
0
void SpeedDialThumbnail::SetFocus(FOCUS_REASON reason)
{
	GetContent()->GetButton()->SetFocus(reason);
}
Esempio n. 12
0
void SpeedDialThumbnail::OnSpeedDialEntryScaleChanged()
{
	OpStatus::Ignore(GetContent()->Zoom());
}
Esempio n. 13
0
void SpeedDialThumbnail::OnSpeedDialExpired()
{
	OpStatus::Ignore(GetContent()->Refresh());
}
Esempio n. 14
0
Script::Script(const std::string& filename) : File(filename + ".icarus"), Parsed(false)
{
    //ctor
    if(GetContent() == "Error reading file") mPath = filename + ".txt";
}
Esempio n. 15
0
////NSIFRAME
NS_IMETHODIMP
nsTextControlFrame::AttributeChanged(PRInt32         aNameSpaceID,
                                     nsIAtom*        aAttribute,
                                     PRInt32         aModType)
{
  nsCOMPtr<nsITextControlElement> txtCtrl = do_QueryInterface(GetContent());
  NS_ASSERTION(txtCtrl, "Content not a text control element");
  nsISelectionController* selCon = txtCtrl->GetSelectionController();
  const bool needEditor = nsGkAtoms::maxlength == aAttribute ||
                            nsGkAtoms::readonly == aAttribute ||
                            nsGkAtoms::disabled == aAttribute ||
                            nsGkAtoms::spellcheck == aAttribute;
  nsCOMPtr<nsIEditor> editor;
  if (needEditor) {
    GetEditor(getter_AddRefs(editor));
  }
  if ((needEditor && !editor) || !selCon)
    return nsBoxFrame::AttributeChanged(aNameSpaceID, aAttribute, aModType);;

  nsresult rv = NS_OK;

  if (nsGkAtoms::maxlength == aAttribute) 
  {
    PRInt32 maxLength;
    bool maxDefined = GetMaxLength(&maxLength);
    
    nsCOMPtr<nsIPlaintextEditor> textEditor = do_QueryInterface(editor);
    if (textEditor)
    {
      if (maxDefined) 
      {  // set the maxLength attribute
          textEditor->SetMaxTextLength(maxLength);
        // if maxLength>docLength, we need to truncate the doc content
      }
      else { // unset the maxLength attribute
          textEditor->SetMaxTextLength(-1);
      }
    }
    rv = NS_OK; // don't propagate the error
  } 
  else if (nsGkAtoms::readonly == aAttribute) 
  {
    PRUint32 flags;
    editor->GetFlags(&flags);
    if (AttributeExists(nsGkAtoms::readonly))
    { // set readonly
      flags |= nsIPlaintextEditor::eEditorReadonlyMask;
      if (nsContentUtils::IsFocusedContent(mContent))
        selCon->SetCaretEnabled(false);
    }
    else 
    { // unset readonly
      flags &= ~(nsIPlaintextEditor::eEditorReadonlyMask);
      if (!(flags & nsIPlaintextEditor::eEditorDisabledMask) &&
          nsContentUtils::IsFocusedContent(mContent))
        selCon->SetCaretEnabled(true);
    }
    editor->SetFlags(flags);
  }
  else if (nsGkAtoms::disabled == aAttribute) 
  {
    PRUint32 flags;
    editor->GetFlags(&flags);
    if (AttributeExists(nsGkAtoms::disabled))
    { // set disabled
      flags |= nsIPlaintextEditor::eEditorDisabledMask;
      selCon->SetDisplaySelection(nsISelectionController::SELECTION_OFF);
      if (nsContentUtils::IsFocusedContent(mContent))
        selCon->SetCaretEnabled(false);
    }
    else 
    { // unset disabled
      flags &= ~(nsIPlaintextEditor::eEditorDisabledMask);
      selCon->SetDisplaySelection(nsISelectionController::SELECTION_HIDDEN);
      if (nsContentUtils::IsFocusedContent(mContent)) {
        selCon->SetCaretEnabled(true);
      }
    }
    editor->SetFlags(flags);
  }
  else if (!mUseEditor && nsGkAtoms::value == aAttribute) {
    UpdateValueDisplay(true);
  }
  // Allow the base class to handle common attributes supported
  // by all form elements... 
  else {
    rv = nsBoxFrame::AttributeChanged(aNameSpaceID, aAttribute, aModType);
  }

  return rv;
}
Esempio n. 16
0
void autobots_toutiao::onStart()
{
  // 检查输入
  if (!CheckInput())
  {
    return;
  }

  // 更新界面输入
  UpdateData();
  
//   if (m_account_list.size() < m_comment_list.size())
//   {
//     QMessageBox::critical(this, QStringLiteral("提示"), QStringLiteral("用户账户太少")); 
//     return;
//   }

  control_status = true;

  // 循环发帖
  for (int i = 0; i < m_comment_list.size(); ++i)
  {
    if (!control_status)
    {
      break;
    }

    if (m_account_order >= m_account_list.size())
    {
      ui.lineEdit_msg->setText(QStringLiteral("账号不够用了"));
      return;
    }

    // 尝试登陆
    bool login_status = false;
    while (m_account_order < m_account_list.size())
    {
      QNetworkCookieJar* cookie = new QNetworkCookieJar();

      network.GetManager().setCookieJar(cookie);

      GetContent();

//       if (!RequestForRenren())
//       {
//         ui.lineEdit_msg->setText(QStringLiteral("请求失败..."));
//         continue;
//       }

      AccountParam ac = m_account_list.at(m_account_order);

      if (!AuthorByRenren(ac._id, ac._password))
      {
        ui.lineEdit_msg->setText(QStringLiteral("登陆失败..."));
        ui.tableWidget_account_id->item(m_account_order, 0)->setBackgroundColor(QColor(255,0,0, 180));
        m_account_order++;
        continue;
      }
      else
      {
        ui.lineEdit_msg->setText(QStringLiteral("登陆成功"));
        ui.tableWidget_account_id->item(m_account_order, 0)->setBackgroundColor(QColor(0,255,0, 180));
        m_account_order++;
        login_status = true;
        break;
      }
    }

    if (!login_status)
    {
      ui.lineEdit_msg->setText(QStringLiteral("账号登陆不成功,无法继续"));
      return;
    }

    QElapsedTimer t2;
    t2.start();
    while(t2.elapsed()<1000 )  
      QCoreApplication::processEvents();

    if (DoPostFatie(m_comment_list[i]))
    {
      m_comment_item_list[i]->setCheckState(Qt::Checked);
      //m_comment_item_list[i]->setBackgroundColor(QColor(0,255,0, 180));
    }
    else
    {
      continue;
    }

    t2.restart();
    while(t2.elapsed()<1000 )  
      QCoreApplication::processEvents();

    Logout();

    QString msg;
    msg.setNum(i+1);

    ui.lineEdit_msg->setText(QStringLiteral("第") + msg + QStringLiteral("次完成"));

    t2.restart();
    while(t2.elapsed()< m_interval*1000 )  // 时间间隔
    {
      ui.lineEdit_msg->setText(QString::number(t2.elapsed()));
      QCoreApplication::processEvents();   
    }
  }

  ui.lineEdit_msg->setText(QStringLiteral("已完成"));
}
Esempio n. 17
0
nsresult
nsTextControlFrame::UpdateValueDisplay(bool aNotify,
                                       bool aBeforeEditorInit,
                                       const nsAString *aValue)
{
  if (!IsSingleLineTextControl()) // textareas don't use this
    return NS_OK;

  nsCOMPtr<nsITextControlElement> txtCtrl = do_QueryInterface(GetContent());
  NS_ASSERTION(txtCtrl, "Content not a text control element");
  nsIContent* rootNode = txtCtrl->GetRootEditorNode();

  NS_PRECONDITION(rootNode, "Must have a div content\n");
  NS_PRECONDITION(!mUseEditor,
                  "Do not call this after editor has been initialized");
  NS_ASSERTION(!mUsePlaceholder || txtCtrl->GetPlaceholderNode(),
               "A placeholder div must exist");

  nsIContent *textContent = rootNode->GetChildAt(0);
  if (!textContent) {
    // Set up a textnode with our value
    nsCOMPtr<nsIContent> textNode;
    nsresult rv = NS_NewTextNode(getter_AddRefs(textNode),
                                 mContent->NodeInfo()->NodeInfoManager());
    NS_ENSURE_SUCCESS(rv, rv);

    NS_ASSERTION(textNode, "Must have textcontent!\n");

    rootNode->AppendChildTo(textNode, aNotify);
    textContent = textNode;
  }

  NS_ENSURE_TRUE(textContent, NS_ERROR_UNEXPECTED);

  // Get the current value of the textfield from the content.
  nsAutoString value;
  if (aValue) {
    value = *aValue;
  } else {
    txtCtrl->GetTextEditorValue(value, true);
  }

  // Update the display of the placeholder value if needed.
  // We don't need to do this if we're about to initialize the
  // editor, since EnsureEditorInitialized takes care of this.
  if (mUsePlaceholder && !aBeforeEditorInit)
  {
    nsWeakFrame weakFrame(this);
    txtCtrl->SetPlaceholderClass(value.IsEmpty(), aNotify);
    NS_ENSURE_STATE(weakFrame.IsAlive());
  }

  if (aBeforeEditorInit && value.IsEmpty()) {
    rootNode->RemoveChildAt(0, true);
    return NS_OK;
  }

  if (!value.IsEmpty() && IsPasswordTextControl()) {
    nsTextEditRules::FillBufWithPWChars(&value, value.Length());
  }
  return textContent->SetText(value, aNotify);
}
Esempio n. 18
0
NS_IMETHODIMP
nsResizerFrame::HandleEvent(nsPresContext* aPresContext,
                            nsGUIEvent* aEvent,
                            nsEventStatus* aEventStatus)
{
  NS_ENSURE_ARG_POINTER(aEventStatus);
  if (nsEventStatus_eConsumeNoDefault == *aEventStatus) {
    return NS_OK;
  }

  nsWeakFrame weakFrame(this);
  bool doDefault = true;

  switch (aEvent->message) {
    case NS_MOUSE_BUTTON_DOWN: {
      if (aEvent->eventStructType == NS_MOUSE_EVENT &&
        static_cast<nsMouseEvent*>(aEvent)->button == nsMouseEvent::eLeftButton)
      {
        nsCOMPtr<nsIBaseWindow> window;
        nsIPresShell* presShell = aPresContext->GetPresShell();
        nsIContent* contentToResize =
          GetContentToResize(presShell, getter_AddRefs(window));
        if (contentToResize) {
          nsIFrame* frameToResize = contentToResize->GetPrimaryFrame();
          if (!frameToResize)
            break;

          // cache the content rectangle for the frame to resize
          // GetScreenRectInAppUnits returns the border box rectangle, so
          // adjust to get the desired content rectangle.
          nsRect rect = frameToResize->GetScreenRectInAppUnits();
          switch (frameToResize->GetStylePosition()->mBoxSizing) {
            case NS_STYLE_BOX_SIZING_CONTENT:
              rect.Deflate(frameToResize->GetUsedPadding());
            case NS_STYLE_BOX_SIZING_PADDING:
              rect.Deflate(frameToResize->GetUsedBorder());
            default:
              break;
          }

          mMouseDownRect = rect.ToNearestPixels(aPresContext->AppUnitsPerDevPixel());
          doDefault = false;
        }
        else {
          // If there is no window, then resizing isn't allowed.
          if (!window)
            break;

          doDefault = false;
            
          // ask the widget implementation to begin a resize drag if it can
          Direction direction = GetDirection();
          nsresult rv = aEvent->widget->BeginResizeDrag(aEvent,
                        direction.mHorizontal, direction.mVertical);
          // for native drags, don't set the fields below
          if (rv != NS_ERROR_NOT_IMPLEMENTED)
             break;
             
          // if there's no native resize support, we need to do window
          // resizing ourselves
          window->GetPositionAndSize(&mMouseDownRect.x, &mMouseDownRect.y,
                                     &mMouseDownRect.width, &mMouseDownRect.height);
        }

        // we're tracking
        mTrackingMouseMove = true;

        // remember current mouse coordinates
        mMouseDownPoint = aEvent->refPoint + aEvent->widget->WidgetToScreenOffset();

        nsIPresShell::SetCapturingContent(GetContent(), CAPTURE_IGNOREALLOWED);
      }
    }
    break;

  case NS_MOUSE_BUTTON_UP: {

    if (mTrackingMouseMove && aEvent->eventStructType == NS_MOUSE_EVENT &&
        static_cast<nsMouseEvent*>(aEvent)->button == nsMouseEvent::eLeftButton)
    {
      // we're done tracking.
      mTrackingMouseMove = false;

      nsIPresShell::SetCapturingContent(nsnull, 0);

      doDefault = false;
    }
  }
  break;

  case NS_MOUSE_MOVE: {
    if (mTrackingMouseMove)
    {
      nsCOMPtr<nsIBaseWindow> window;
      nsIPresShell* presShell = aPresContext->GetPresShell();
      nsCOMPtr<nsIContent> contentToResize =
        GetContentToResize(presShell, getter_AddRefs(window));

      // check if the returned content really is a menupopup
      nsMenuPopupFrame* menuPopupFrame = nsnull;
      if (contentToResize) {
        nsIFrame* frameToResize = contentToResize->GetPrimaryFrame();
        if (frameToResize && frameToResize->GetType() == nsGkAtoms::menuPopupFrame) {
          menuPopupFrame = static_cast<nsMenuPopupFrame *>(frameToResize);
        }
      }

      // both MouseMove and direction are negative when pointing to the
      // top and left, and positive when pointing to the bottom and right

      // retrieve the offset of the mousemove event relative to the mousedown.
      // The difference is how much the resize needs to be
      nsIntPoint screenPoint(aEvent->refPoint + aEvent->widget->WidgetToScreenOffset());
      nsIntPoint mouseMove(screenPoint - mMouseDownPoint);

      // Determine which direction to resize by checking the dir attribute.
      // For windows and menus, ensure that it can be resized in that direction.
      Direction direction = GetDirection();
      if (window || menuPopupFrame) {
        if (menuPopupFrame) {
          menuPopupFrame->CanAdjustEdges(
            (direction.mHorizontal == -1) ? NS_SIDE_LEFT : NS_SIDE_RIGHT,
            (direction.mVertical == -1) ? NS_SIDE_TOP : NS_SIDE_BOTTOM, mouseMove);
        }
      }
      else if (!contentToResize) {
        break; // don't do anything if there's nothing to resize
      }

      nsIntRect rect = mMouseDownRect;
      AdjustDimensions(&rect.x, &rect.width, mouseMove.x, direction.mHorizontal);
      AdjustDimensions(&rect.y, &rect.height, mouseMove.y, direction.mVertical);

      // Don't allow resizing a window or a popup past the edge of the screen,
      // so adjust the rectangle to fit within the available screen area.
      if (window) {
        nsCOMPtr<nsIScreen> screen;
        nsCOMPtr<nsIScreenManager> sm(do_GetService("@mozilla.org/gfx/screenmanager;1"));
        if (sm) {
          nsIntRect frameRect = GetScreenRect();
          sm->ScreenForRect(frameRect.x, frameRect.y, 1, 1, getter_AddRefs(screen));
          if (screen) {
            nsIntRect screenRect;
            screen->GetRect(&screenRect.x, &screenRect.y,
                            &screenRect.width, &screenRect.height);
            rect.IntersectRect(rect, screenRect);
          }
        }
      }
      else if (menuPopupFrame) {
        nsRect frameRect = menuPopupFrame->GetScreenRectInAppUnits();
        nsIFrame* rootFrame = aPresContext->PresShell()->FrameManager()->GetRootFrame();
        nsRect rootScreenRect = rootFrame->GetScreenRectInAppUnits();

        nsRect screenRect = menuPopupFrame->GetConstraintRect(frameRect, rootScreenRect);
        // round using ToInsidePixels as it's better to be a pixel too small
        // than be too large. If the popup is too large it could get flipped
        // to the opposite side of the anchor point while resizing.
        nsIntRect screenRectPixels = screenRect.ToInsidePixels(aPresContext->AppUnitsPerDevPixel());
        rect.IntersectRect(rect, screenRectPixels);
      }

      if (contentToResize) {
        // convert the rectangle into css pixels. When changing the size in a
        // direction, don't allow the new size to be less that the resizer's
        // size. This ensures that content isn't resized too small as to make
        // the resizer invisible.
        nsRect appUnitsRect = rect.ToAppUnits(aPresContext->AppUnitsPerDevPixel());
        if (appUnitsRect.width < mRect.width && mouseMove.x)
          appUnitsRect.width = mRect.width;
        if (appUnitsRect.height < mRect.height && mouseMove.y)
          appUnitsRect.height = mRect.height;
        nsIntRect cssRect = appUnitsRect.ToInsidePixels(nsPresContext::AppUnitsPerCSSPixel());

        nsIntRect oldRect;
        nsWeakFrame weakFrame(menuPopupFrame);
        if (menuPopupFrame) {
          nsCOMPtr<nsIWidget> widget = menuPopupFrame->GetWidget();
          if (widget)
            widget->GetScreenBounds(oldRect);

          // convert the new rectangle into outer window coordinates
          nsIntPoint clientOffset = widget->GetClientOffset();
          rect.x -= clientOffset.x; 
          rect.y -= clientOffset.y; 
        }

        SizeInfo sizeInfo, originalSizeInfo;
        sizeInfo.width.AppendInt(cssRect.width);
        sizeInfo.height.AppendInt(cssRect.height);
        ResizeContent(contentToResize, direction, sizeInfo, &originalSizeInfo);
        MaybePersistOriginalSize(contentToResize, originalSizeInfo);

        if (weakFrame.IsAlive() &&
            (oldRect.x != rect.x || oldRect.y != rect.y) &&
            (!menuPopupFrame->IsAnchored() ||
             menuPopupFrame->PopupLevel() != ePopupLevelParent)) {
          menuPopupFrame->MoveTo(rect.x, rect.y, true);
        }
      }
      else {
        window->SetPositionAndSize(rect.x, rect.y, rect.width, rect.height, true); // do the repaint.
      }

      doDefault = false;
    }
  }
  break;

  case NS_MOUSE_CLICK:
    if (NS_IS_MOUSE_LEFT_CLICK(aEvent))
    {
      MouseClicked(aPresContext, aEvent);
    }
    break;

  case NS_MOUSE_DOUBLECLICK:
    if (aEvent->eventStructType == NS_MOUSE_EVENT &&
        static_cast<nsMouseEvent*>(aEvent)->button == nsMouseEvent::eLeftButton)
    {
      nsCOMPtr<nsIBaseWindow> window;
      nsIPresShell* presShell = aPresContext->GetPresShell();
      nsIContent* contentToResize =
        GetContentToResize(presShell, getter_AddRefs(window));
      if (contentToResize) {
        nsIFrame* frameToResize = contentToResize->GetPrimaryFrame();
        if (frameToResize && frameToResize->GetType() == nsGkAtoms::menuPopupFrame)
          break; // Don't restore original sizing for menupopup frames until
                 // we handle screen constraints here. (Bug 357725)

        RestoreOriginalSize(contentToResize);
      }
    }
    break;
  }

  if (!doDefault)
    *aEventStatus = nsEventStatus_eConsumeNoDefault;

  if (doDefault && weakFrame.IsAlive())
    return nsTitleBarFrame::HandleEvent(aPresContext, aEvent, aEventStatus);

  return NS_OK;
}
Esempio n. 19
0
nsresult
nsTextControlFrame::CreateAnonymousContent(nsTArray<ContentInfo>& aElements)
{
  NS_ASSERTION(mContent, "We should have a content!");

  mState |= NS_FRAME_INDEPENDENT_SELECTION;

  nsCOMPtr<nsITextControlElement> txtCtrl = do_QueryInterface(GetContent());
  NS_ASSERTION(txtCtrl, "Content not a text control element");

  // Bind the frame to its text control
  nsresult rv = txtCtrl->BindToFrame(this);
  NS_ENSURE_SUCCESS(rv, rv);

  nsIContent* rootNode = txtCtrl->GetRootEditorNode();
  NS_ENSURE_TRUE(rootNode, NS_ERROR_OUT_OF_MEMORY);

  if (!aElements.AppendElement(rootNode))
    return NS_ERROR_OUT_OF_MEMORY;

  // Do we need a placeholder node?
  nsAutoString placeholderTxt;
  mContent->GetAttr(kNameSpaceID_None, nsGkAtoms::placeholder,
                    placeholderTxt);
  nsContentUtils::RemoveNewlines(placeholderTxt);
  mUsePlaceholder = !placeholderTxt.IsEmpty();

  // Create the placeholder anonymous content if needed.
  if (mUsePlaceholder) {
    nsIContent* placeholderNode = txtCtrl->CreatePlaceholderNode();
    NS_ENSURE_TRUE(placeholderNode, NS_ERROR_OUT_OF_MEMORY);

    if (!aElements.AppendElement(placeholderNode))
      return NS_ERROR_OUT_OF_MEMORY;
  }

  rv = UpdateValueDisplay(false);
  NS_ENSURE_SUCCESS(rv, rv);

  // textareas are eagerly initialized
  bool initEagerly = !IsSingleLineTextControl();
  if (!initEagerly) {
    // Also, input elements which have a cached selection should get eager
    // editor initialization.
    nsCOMPtr<nsITextControlElement> txtCtrl = do_QueryInterface(GetContent());
    NS_ASSERTION(txtCtrl, "Content not a text control element");
    initEagerly = txtCtrl->HasCachedSelection();
  }
  if (!initEagerly) {
    nsCOMPtr<nsIDOMHTMLElement> element = do_QueryInterface(txtCtrl);
    if (element) {
      // so are input text controls with spellcheck=true
      element->GetSpellcheck(&initEagerly);
    }
  }

  if (initEagerly) {
    NS_ASSERTION(!nsContentUtils::IsSafeToRunScript(),
                 "Someone forgot a script blocker?");
    EditorInitializer* initializer = (EditorInitializer*) Properties().Get(TextControlInitializer());
    if (initializer) {
      initializer->Revoke();
    }
    initializer = new EditorInitializer(this);
    Properties().Set(TextControlInitializer(),initializer);
    if (!nsContentUtils::AddScriptRunner(initializer)) {
      initializer->Revoke(); // paranoia
      Properties().Delete(TextControlInitializer());
      delete initializer;
      return NS_ERROR_OUT_OF_MEMORY;
    }
  }

  return NS_OK;
}
Esempio n. 20
0
void 
HandleSocketMessage(gpointer data, gpointer user_data)
{
    int instance, type;
    char mMsgBuf[1024];
    char *msg = (char *)data;

    int i = sscanf(msg, "%d,%d,%s", &instance, &type, mMsgBuf);

    NS_ASSERTION(i >= 2, "Wrong message format\n");

    // In case that the last message string argument contains spaces, sscanf 
    // returns before the first space. Below line returns the complete message
    // string.
    char* mMsgString = (char*)strchr(msg, ',');
    mMsgString++;
    mMsgString = (char*)strchr(mMsgString, ',');
    mMsgString++;

    GtkBrowser *pBrowser;
    switch (type) {
    case JEVENT_INIT:
        break;
    case JEVENT_CREATEWINDOW:
        {
            // only create new browser window when the instance does not exist
            if (instance < gBrowserArray.GetSize() && gBrowserArray[instance] != NULL)
                break;
            if (i != 3)
                break;
            int javaXId = atoi(mMsgString);
            NS_ASSERTION(javaXId, "Invalid X window handle\n");
            pBrowser = g_new0(GtkBrowser, 1);
            pBrowser->topLevelWindow = gtk_plug_new(javaXId);
            pBrowser->mozEmbed = gtk_moz_embed_new();
            if (pBrowser->mozEmbed) {
                gtk_container_add(GTK_CONTAINER(pBrowser->topLevelWindow), pBrowser->mozEmbed);
                install_mozembed_cb(pBrowser);
                gtk_moz_embed_set_chrome_mask(GTK_MOZ_EMBED(pBrowser->mozEmbed),
                    GTK_MOZ_EMBED_FLAG_DEFAULTCHROME);
                gtk_widget_realize(pBrowser->topLevelWindow);
                gtk_widget_show_all(pBrowser->topLevelWindow);
                pBrowser->id = instance;
                gBrowserArray.SetAtGrow(instance, pBrowser);
                SendSocketMessage(instance, CEVENT_INIT_WINDOW_SUCC);
            }

            gtk_signal_connect(GTK_OBJECT(pBrowser->topLevelWindow), 
                  "set-focus", GTK_SIGNAL_FUNC(set_focus_cb), pBrowser);

        }
        break;
    case JEVENT_DESTROYWINDOW:
        pBrowser = (GtkBrowser *)gBrowserArray[instance];
        if(pBrowser != NULL){
            gtk_widget_destroy(pBrowser->mozEmbed);
            gtk_object_destroy((GtkObject *)pBrowser->topLevelWindow);
            gBrowserArray.SetAt(instance, NULL);
        }
        SendSocketMessage(instance, CEVENT_DISTORYWINDOW_SUCC);
        break;
    case JEVENT_SHUTDOWN:
        gtk_main_quit();
        break;
    case JEVENT_SET_BOUNDS:
        {
            NS_ASSERTION(i == 3, "Wrong message format\n");
            int x, y, w, h;
            i = sscanf(mMsgString, "%d,%d,%d,%d", &x, &y, &w, &h);
            if (i == 4) {
                pBrowser = (GtkBrowser *)gBrowserArray[instance];
                NS_ASSERTION(pBrowser, "Can't get native browser instance\n");
                gtk_widget_set_usize(pBrowser->topLevelWindow, w, h);
            }
        }
        break;
    case JEVENT_NAVIGATE:
        NS_ASSERTION(i == 3, "Wrong message format\n");
        pBrowser = (GtkBrowser *)gBrowserArray[instance];
        NS_ASSERTION(pBrowser, "Can't get native browser instance\n");
        gtk_moz_embed_load_url(GTK_MOZ_EMBED(pBrowser->mozEmbed), mMsgString);
        break;
    case JEVENT_NAVIGATE_POST:
        NS_ASSERTION(i == 3, "Wrong message format\n");
        strncpy(gCachedURL, mMsgString, sizeof(gCachedURL));
        break;
    case JEVENT_NAVIGATE_POSTDATA:
        NS_ASSERTION(i == 3, "Wrong message format\n");
        pBrowser = (GtkBrowser *)gBrowserArray[instance];
        OpenURL(pBrowser, gCachedURL, mMsgString, POST_HEADER);
        break;
    case JEVENT_GOBACK:
        pBrowser = (GtkBrowser *)gBrowserArray[instance];
        NS_ASSERTION(pBrowser, "Can't get native browser instance\n");
        gtk_moz_embed_go_back(GTK_MOZ_EMBED(pBrowser->mozEmbed));
        break;
    case JEVENT_GOFORWARD:
        pBrowser = (GtkBrowser *)gBrowserArray[instance];
        NS_ASSERTION(pBrowser, "Can't get native browser instance\n");
        gtk_moz_embed_go_forward(GTK_MOZ_EMBED(pBrowser->mozEmbed));
        break;
    case JEVENT_REFRESH:
        pBrowser = (GtkBrowser *)gBrowserArray[instance];
        NS_ASSERTION(pBrowser, "Can't get native browser instance\n");
        gtk_moz_embed_reload(GTK_MOZ_EMBED(pBrowser->mozEmbed), GTK_MOZ_EMBED_FLAG_RELOADNORMAL);
        break;
    case JEVENT_STOP:
        pBrowser = (GtkBrowser *)gBrowserArray[instance];
        NS_ASSERTION(pBrowser, "Can't get native browser instance\n");
        gtk_moz_embed_stop_load(GTK_MOZ_EMBED(pBrowser->mozEmbed));
        break;
    case JEVENT_GETURL:
        {
            pBrowser = (GtkBrowser *)gBrowserArray[instance];
            NS_ASSERTION(pBrowser, "Can't get native browser instance\n");
            nsCOMPtr<nsIWebBrowser> webBrowser;
            gtk_moz_embed_get_nsIWebBrowser(GTK_MOZ_EMBED(pBrowser->mozEmbed), getter_AddRefs(webBrowser));
            nsCOMPtr<nsIWebNavigation> webNavigation(do_QueryInterface(webBrowser));
            nsCOMPtr<nsIURI> currentURI;
            webNavigation->GetCurrentURI(getter_AddRefs(currentURI));
            if (currentURI == NULL)
                SendSocketMessage(instance, CEVENT_RETURN_URL, "");
            else { 
            	nsEmbedCString uriString;
                currentURI->GetAsciiSpec(uriString);
                SendSocketMessage(instance, CEVENT_RETURN_URL, uriString.get());
            }
        }
        break;

    case JEVENT_FOCUSGAINED:
    case JEVENT_FOCUSLOST:
        {
            pBrowser = (GtkBrowser *)gBrowserArray[instance];
            NS_ASSERTION(pBrowser, "Can't get native browser instance\n");

            if (!pBrowser->topLevelWindow) {
                ReportError("Top level Window is Null!\n");
                break;
            }

            GtkWidget *widget = GTK_WIDGET (pBrowser->topLevelWindow);
            GdkEvent event;

            GtkWindowClass *parent_class = (GtkWindowClass*) gtk_type_class (GTK_TYPE_WINDOW);

            if (!widget) {
                ReportError("Failed to get browser's toplevel window !\n");
                break;
            }
            if (!parent_class) {
                ReportError("Failed to get gtk window class !\n");
                break;
            }

            event.focus_change.type = GDK_FOCUS_CHANGE;
            event.focus_change.window = widget->window;
            event.focus_change.send_event = TRUE;

            if (type == JEVENT_FOCUSGAINED) {
                event.focus_change.in = TRUE;
                GTK_WIDGET_CLASS (parent_class)->focus_in_event
                            (widget, (GdkEventFocus *)&event);
            }
            else {
                event.focus_change.in = FALSE;
                GTK_WIDGET_CLASS (parent_class)->focus_out_event
                            (widget, (GdkEventFocus *)&event);
            }
        }
        break;
    case JEVENT_GETCONTENT:
        {
            pBrowser = (GtkBrowser *)gBrowserArray[instance];
            NS_ASSERTION(pBrowser, "Can't get native browser instance\n");
            nsCOMPtr<nsIWebBrowser> webBrowser;
            gtk_moz_embed_get_nsIWebBrowser(GTK_MOZ_EMBED(pBrowser->mozEmbed), 
                    getter_AddRefs(webBrowser));
            nsCOMPtr<nsIWebNavigation> 
                webNavigation(do_QueryInterface(webBrowser));
                                                                                                            
            char *retStr = GetContent(webNavigation);
            if (retStr == NULL)
                SendSocketMessage(instance, CEVENT_GETCONTENT, "");
            else
                SendSocketMessage(instance, CEVENT_GETCONTENT, retStr);
        } 
        break;
    case JEVENT_SETCONTENT:
        {
            NS_ASSERTION(i == 3, "Wrong message format\n");
            pBrowser = (GtkBrowser *)gBrowserArray[instance];
            NS_ASSERTION(pBrowser, "Can't get native browser instance\n");
            nsCOMPtr<nsIWebBrowser> webBrowser;
            gtk_moz_embed_get_nsIWebBrowser(GTK_MOZ_EMBED(pBrowser->mozEmbed), 
                    getter_AddRefs(webBrowser));
            nsCOMPtr<nsIWebNavigation> 
                webNavigation(do_QueryInterface(webBrowser));
            
            SetContent(webNavigation, mMsgString);
        }
        break;
    case JEVENT_EXECUTESCRIPT:
        {
            NS_ASSERTION(i == 3, "Wrong message format\n");
            pBrowser = (GtkBrowser *)gBrowserArray[instance];
            NS_ASSERTION(pBrowser, "Can't get native browser instance\n");
            nsCOMPtr<nsIWebBrowser> webBrowser;
            gtk_moz_embed_get_nsIWebBrowser(GTK_MOZ_EMBED(pBrowser->mozEmbed), 
                    getter_AddRefs(webBrowser));
            nsCOMPtr<nsIWebNavigation> 
                webNavigation(do_QueryInterface(webBrowser));
                                                                                                            
            char *retStr = ExecuteScript(webNavigation, mMsgString);
            if (retStr == NULL)
                SendSocketMessage(instance, CEVENT_EXECUTESCRIPT, "");
            else
                SendSocketMessage(instance, CEVENT_EXECUTESCRIPT, retStr);
        } 
        break;
    }
}
Esempio n. 21
0
ConceptionApp::ConceptionApp(InputManager & InputManager)
    : App(InputManager),
      m_CurrentProject(),
      m_TypingModule(new TypingModule())		// Gets cleaned up via unique_ptr when pushed back to m_Widgets
{
    PopulateConcepts();

    {
        auto MainCanvas = new Canvas(Vector2n(0, 0), true, true);
        //MainCanvas->MoveView(0, 336);
        MainCanvas->MoveView(1, -64);

#if 1
        {
            auto StdIncludesList = new ListWidget<ConceptId>(Vector2n::ZERO, m_CurrentProject.GetStdIncludes(), *m_TypingModule);
            StdIncludesList->m_TapAction = [=](Vector2n LocalPosition, std::vector<ConceptId> & m_List)
            {
                auto Entry = m_TypingModule->TakeString();

                if (!Entry.empty())
                {
                    auto ConceptId = FindOrCreateConcept(Entry);

                    //Insert(ConceptId);

                    // TEST
                    auto Spot = m_List.begin() + (LocalPosition.Y() / lineHeight);
                    m_List.insert(Spot, ConceptId);
                }
                else
                {
                    auto ListEntry = static_cast<decltype(m_List.size())>(LocalPosition.Y() / lineHeight);

                    if (ListEntry < m_List.size())
                    {
                        m_TypingModule->SetString(GetConcept(m_List[ListEntry]).GetContent());
                        m_List.erase(m_List.begin() + ListEntry);
                    }
                }
            };

            auto LabelledStdIncludesList = new FlowLayoutWidget(Vector2n(-280, -250), { std::shared_ptr<Widget>(new LabelWidget(Vector2n::ZERO, std::string("#include <"), LabelWidget::Background::None)),
                    std::shared_ptr<Widget>(StdIncludesList),
                    std::shared_ptr<Widget>(new LabelWidget(Vector2n::ZERO, std::string(">"), LabelWidget::Background::None))
                                                                                      }, {});
            LabelledStdIncludesList->AddBehavior(std::shared_ptr<Behavior>(new DraggablePositionBehavior(*LabelledStdIncludesList)));
            MainCanvas->AddWidget(LabelledStdIncludesList);
        }
#endif

        MainCanvas->AddWidget(new ButtonWidget(Vector2n(-100, -350), []() {
            std::cout << "Hi from anon func.\n";
        } ));
        MainCanvas->AddWidget(new ButtonWidget(Vector2n(-60, -350), []() {
            std::cout << "Second button.\n";
        } ));
        MainCanvas->AddWidget(new ToggleWidget(Vector2n(-20, -350), [](bool State) {
            std::cout << "Testing this toggle widget! It's now set to " << State << ".\n";
        }, true));
        MainCanvas->AddWidget(new LiveFunctionWidget(Vector2n(-100, 100), *m_TypingModule, m_CurrentProject));
        MainCanvas->AddWidget(new LiveProgramWidget(Vector2n(-100, -300), *m_TypingModule, m_CurrentProject));
        MainCanvas->AddWidget(new LiveProgramWidget(Vector2n(-100, -100), *m_TypingModule, m_CurrentProject));
        MainCanvas->AddWidget(new LiveGofmtWidget(Vector2n(-460, 200), *m_TypingModule, m_CurrentProject));
        MainCanvas->AddWidget(new TextFieldWidget(Vector2n(-460, 160), *m_TypingModule));
        MainCanvas->AddWidget(new ShellWidget(Vector2n(-460, 60), *m_TypingModule));
        MainCanvas->AddWidget(new SayWidget(Vector2n(-460, -100), *m_TypingModule));

        MainCanvas->AddWidget(new ConceptStringBoxWidget(Vector2n(-400, 100 + 400), *m_TypingModule));

        // TEST: Modify some Concept
        {
            auto Widget = new TextFieldWidget(Vector2n(-320, 470), *m_TypingModule);
            Widget->SetContent(GetConcept(47).GetContent());
            Widget->m_OnChange = [=]() {
                static_cast<ConceptBasic &>(ModifyConcept(47)).SetContentTEST(Widget->GetContent());
            };
            Widget->AddBehavior(std::shared_ptr<Behavior>(new DraggablePositionBehavior(*Widget)));
            MainCanvas->AddWidget(Widget);
        }

        // Label resizing test
        {
            auto SourceWidget = new TextFieldWidget(Vector2n::ZERO, *m_TypingModule);

            auto Content = [=]() -> std::string {
                return SourceWidget->GetContent();
            };
            auto LabelWidget = new class LabelWidget(Vector2n::ZERO, Content, LabelWidget::Background::Normal);

            MainCanvas->AddWidget(new FlowLayoutWidget(Vector2n(-100, -450), { std::shared_ptr<Widget>(SourceWidget), std::shared_ptr<Widget>(LabelWidget) }, {}));
        }

        // Time widget
        {
            auto Content = []() -> std::string {
                auto now = std::chrono::system_clock::now();

                auto duration = now.time_since_epoch();

                auto seconds = std::chrono::duration_cast<std::chrono::seconds>(duration).count();

                return std::to_string(seconds);
            };
            auto LabelWidget = new class LabelWidget(Vector2n(360, -340), Content, LabelWidget::Background::Normal);
            LabelWidget->AddBehavior(std::shared_ptr<Behavior>(new DraggablePositionBehavior(*LabelWidget)));

            MainCanvas->AddWidget(LabelWidget);
        }

        MainCanvas->AddWidget(new TimeWidget(Vector2n(360, -360)));		// Time widget

#if 0
        // "./GenProgram.go" file contents displayed (in real-time) in this Label Widget
        {
            auto Content = []() -> std::string {
                //return FromFileToString("./GenProgram.go");
                return FromFileToString("/Users/Dmitri/Desktop/goproj_play/src/gist.github.com/4670289.git/gistfile1.go");
            };
            auto LabelWidget = new class LabelWidget(Vector2n(-546, -186), Content, LabelWidget::Background::Normal);
            LabelWidget->AddBehavior(std::shared_ptr<Behavior>(new DraggablePositionBehavior(*LabelWidget)));

            MainCanvas->AddWidget(LabelWidget);
        }
#endif

#if 1
        {
            MainCanvas->AddWidget(new ListWidget<Concept *>(Vector2n(-730 - 450, -250), Concepts, *m_TypingModule));
        }
#endif

        m_Widgets.push_back(std::unique_ptr<Widget>(m_TypingModule));

        m_Widgets.push_back(std::unique_ptr<Widget>(MainCanvas));

        m_Widgets.push_back(std::unique_ptr<Widget>(new DebugOverlayWidget()));		// DEBUG: Print debug info
    }

    // Prepare and start the thread
    {
        m_CurrentProject.StartBackgroundThread();
    }

    {
        // Load program
        m_CurrentProject.LoadSampleGenProgram(*static_cast<Canvas *>(m_Widgets[0].get()));
    }
}
NS_IMETHODIMP
CVE_2013_1732_firefox12_0_nsBlockFrame::Reflow(nsPresContext*           aPresContext,
                     nsHTMLReflowMetrics&     aMetrics,
                     const nsHTMLReflowState& aReflowState,
                     nsReflowStatus&          aStatus)
{
  DO_GLOBAL_REFLOW_COUNT("nsBlockFrame");
  DISPLAY_REFLOW(aPresContext, this, aReflowState, aMetrics, aStatus);
#ifdef DEBUG
  if (gNoisyReflow) {
    IndentBy(stdout, gNoiseIndent);
    ListTag(stdout);
    printf(": begin reflow availSize=%d,%d computedSize=%d,%d\n",
           aReflowState.availableWidth, aReflowState.availableHeight,
           aReflowState.ComputedWidth(), aReflowState.ComputedHeight());
  }
  AutoNoisyIndenter indent(gNoisy);
  PRTime start = LL_ZERO; // Initialize these variablies to silence the compiler.
  PRInt32 ctc = 0;        // We only use these if they are set (gLameReflowMetrics).
  if (gLameReflowMetrics) {
    start = PR_Now();
    ctc = nsLineBox::GetCtorCount();
  }
#endif

  const nsHTMLReflowState *reflowState = &aReflowState;
  nsAutoPtr<nsHTMLReflowState> mutableReflowState;
  // If we have non-auto height, we're clipping our kids and we fit,
  // make sure our kids fit too.
  if (aReflowState.availableHeight != NS_UNCONSTRAINEDSIZE &&
      aReflowState.ComputedHeight() != NS_AUTOHEIGHT &&
      ApplyOverflowClipping(this, aReflowState.mStyleDisplay)) {
    nsMargin heightExtras = aReflowState.mComputedBorderPadding;
    if (GetSkipSides() & NS_SIDE_TOP) {
      heightExtras.top = 0;
    } else {
      // Bottom margin never causes us to create continuations, so we
      // don't need to worry about whether it fits in its entirety.
      heightExtras.top += aReflowState.mComputedMargin.top;
    }

    if (GetEffectiveComputedHeight(aReflowState) + heightExtras.TopBottom() <=
        aReflowState.availableHeight) {
      mutableReflowState = new nsHTMLReflowState(aReflowState);
      mutableReflowState->availableHeight = NS_UNCONSTRAINEDSIZE;
      reflowState = mutableReflowState;
    }
  }

  // See comment below about oldSize. Use *only* for the
  // abs-pos-containing-block-size-change optimization!
  nsSize oldSize = GetSize();

  // Should we create a float manager?
  nsAutoFloatManager autoFloatManager(const_cast<nsHTMLReflowState&>(*reflowState));

  // XXXldb If we start storing the float manager in the frame rather
  // than keeping it around only during reflow then we should create it
  // only when there are actually floats to manage.  Otherwise things
  // like tables will gain significant bloat.
  bool needFloatManager = nsBlockFrame::BlockNeedsFloatManager(this);
  if (needFloatManager)
    autoFloatManager.CreateFloatManager(aPresContext);

  // OK, some lines may be reflowed. Blow away any saved line cursor
  // because we may invalidate the nondecreasing
  // overflowArea.VisualOverflow().y/yMost invariant, and we may even
  // delete the line with the line cursor.
  ClearLineCursor();

  if (IsFrameTreeTooDeep(*reflowState, aMetrics, aStatus)) {
    return NS_OK;
  }

  bool marginRoot = BlockIsMarginRoot(this);
  nsBlockReflowState state(*reflowState, aPresContext, this, aMetrics,
                           marginRoot, marginRoot, needFloatManager);

#ifdef IBMBIDI
  if (GetStateBits() & NS_BLOCK_NEEDS_BIDI_RESOLUTION)
    static_cast<nsBlockFrame*>(GetFirstContinuation())->ResolveBidi();
#endif // IBMBIDI

  if (RenumberLists(aPresContext)) {
    AddStateBits(NS_FRAME_HAS_DIRTY_CHILDREN);
  }

  nsresult rv = NS_OK;

  // ALWAYS drain overflow. We never want to leave the previnflow's
  // overflow lines hanging around; block reflow depends on the
  // overflow line lists being cleared out between reflow passes.
  DrainOverflowLines();

  // Handle paginated overflow (see nsContainerFrame.h)
  nsOverflowAreas ocBounds;
  nsReflowStatus ocStatus = NS_FRAME_COMPLETE;
  if (GetPrevInFlow()) {
    ReflowOverflowContainerChildren(aPresContext, *reflowState, ocBounds, 0,
                                    ocStatus);
  }

  // Now that we're done cleaning up our overflow container lists, we can
  // give |state| its nsOverflowContinuationTracker.
  nsOverflowContinuationTracker tracker(aPresContext, this, false);
  state.mOverflowTracker = &tracker;

  // Drain & handle pushed floats
  DrainPushedFloats(state);
  nsOverflowAreas fcBounds;
  nsReflowStatus fcStatus = NS_FRAME_COMPLETE;
  rv = ReflowPushedFloats(state, fcBounds, fcStatus);
  NS_ENSURE_SUCCESS(rv, rv);

  // If we're not dirty (which means we'll mark everything dirty later)
  // and our width has changed, mark the lines dirty that we need to
  // mark dirty for a resize reflow.
  if (reflowState->mFlags.mHResize)
    PrepareResizeReflow(state);

  mState &= ~NS_FRAME_FIRST_REFLOW;

  // Now reflow...
  rv = ReflowDirtyLines(state);
  NS_ASSERTION(NS_SUCCEEDED(rv), "reflow dirty lines failed");
  if (NS_FAILED(rv)) return rv;

  NS_MergeReflowStatusInto(&state.mReflowStatus, ocStatus);
  NS_MergeReflowStatusInto(&state.mReflowStatus, fcStatus);

  // If we end in a BR with clear and affected floats continue,
  // we need to continue, too.
  if (NS_UNCONSTRAINEDSIZE != reflowState->availableHeight &&
      NS_FRAME_IS_COMPLETE(state.mReflowStatus) &&
      state.mFloatManager->ClearContinues(FindTrailingClear())) {
    NS_FRAME_SET_INCOMPLETE(state.mReflowStatus);
  }

  if (!NS_FRAME_IS_FULLY_COMPLETE(state.mReflowStatus)) {
    if (GetOverflowLines() || GetPushedFloats()) {
      state.mReflowStatus |= NS_FRAME_REFLOW_NEXTINFLOW;
    }

#ifdef DEBUG_kipp
    ListTag(stdout); printf(": block is not fully complete\n");
#endif
  }

  CheckFloats(state);

  // Place the "marker" (bullet) frame if it is placed next to a block
  // child.
  //
  // According to the CSS2 spec, section 12.6.1, the "marker" box
  // participates in the height calculation of the list-item box's
  // first line box.
  //
  // There are exactly two places a bullet can be placed: near the
  // first or second line. It's only placed on the second line in a
  // rare case: an empty first line followed by a second line that
  // contains a block (example: <LI>\n<P>... ). This is where
  // the second case can happen.
  if (mBullet && HaveOutsideBullet() && !mLines.empty() &&
      (mLines.front()->IsBlock() ||
       (0 == mLines.front()->mBounds.height &&
        mLines.front() != mLines.back() &&
        mLines.begin().next()->IsBlock()))) {
    // Reflow the bullet
    nsHTMLReflowMetrics metrics;
    // XXX Use the entire line when we fix bug 25888.
    nsLayoutUtils::LinePosition position;
    bool havePosition = nsLayoutUtils::GetFirstLinePosition(this, &position);
    nscoord lineTop = havePosition ? position.mTop
                                   : reflowState->mComputedBorderPadding.top;
    ReflowBullet(state, metrics, lineTop);
    NS_ASSERTION(!BulletIsEmpty() || metrics.height == 0,
                 "empty bullet took up space");

    if (havePosition && !BulletIsEmpty()) {
      // We have some lines to align the bullet with.  

      // Doing the alignment using the baseline will also cater for
      // bullets that are placed next to a child block (bug 92896)
    
      // Tall bullets won't look particularly nice here...
      nsRect bbox = mBullet->GetRect();
      bbox.y = position.mBaseline - metrics.ascent;
      mBullet->SetRect(bbox);
    }
    // Otherwise just leave the bullet where it is, up against our top padding.
  }

  // Compute our final size
  nscoord bottomEdgeOfChildren;
  ComputeFinalSize(*reflowState, state, aMetrics, &bottomEdgeOfChildren);
  nsRect areaBounds = nsRect(0, 0, aMetrics.width, aMetrics.height);
  ComputeOverflowAreas(areaBounds, reflowState->mStyleDisplay,
                       bottomEdgeOfChildren, aMetrics.mOverflowAreas);
  // Factor overflow container child bounds into the overflow area
  aMetrics.mOverflowAreas.UnionWith(ocBounds);
  // Factor pushed float child bounds into the overflow area
  aMetrics.mOverflowAreas.UnionWith(fcBounds);

  // Let the absolutely positioned container reflow any absolutely positioned
  // child frames that need to be reflowed, e.g., elements with a percentage
  // based width/height
  // We want to do this under either of two conditions:
  //  1. If we didn't do the incremental reflow above.
  //  2. If our size changed.
  // Even though it's the padding edge that's the containing block, we
  // can use our rect (the border edge) since if the border style
  // changed, the reflow would have been targeted at us so we'd satisfy
  // condition 1.
  // XXX checking oldSize is bogus, there are various reasons we might have
  // reflowed but our size might not have been changed to what we
  // asked for (e.g., we ended up being pushed to a new page)
  // When WillReflowAgainForClearance is true, we will reflow again without
  // resetting the size. Because of this, we must not reflow our abs-pos children
  // in that situation --- what we think is our "new size"
  // will not be our real new size. This also happens to be more efficient.
  if (HasAbsolutelyPositionedChildren()) {
    nsAbsoluteContainingBlock* absoluteContainer = GetAbsoluteContainingBlock();
    bool haveInterrupt = aPresContext->HasPendingInterrupt();
    if (reflowState->WillReflowAgainForClearance() ||
        haveInterrupt) {
      // Make sure that when we reflow again we'll actually reflow all the abs
      // pos frames that might conceivably depend on our size (or all of them,
      // if we're dirty right now and interrupted; in that case we also need
      // to mark them all with NS_FRAME_IS_DIRTY).  Sadly, we can't do much
      // better than that, because we don't really know what our size will be,
      // and it might in fact not change on the followup reflow!
      if (haveInterrupt && (GetStateBits() & NS_FRAME_IS_DIRTY)) {
        absoluteContainer->MarkAllFramesDirty();
      } else {
        absoluteContainer->MarkSizeDependentFramesDirty();
      }
    } else {
      nsSize containingBlockSize =
        CalculateContainingBlockSizeForAbsolutes(*reflowState,
                                                 nsSize(aMetrics.width,
                                                        aMetrics.height));

      // Mark frames that depend on changes we just made to this frame as dirty:
      // Now we can assume that the padding edge hasn't moved.
      // We need to reflow the absolutes if one of them depends on
      // its placeholder position, or the containing block size in a
      // direction in which the containing block size might have
      // changed.
      bool cbWidthChanged = aMetrics.width != oldSize.width;
      bool isRoot = !GetContent()->GetParent();
      // If isRoot and we have auto height, then we are the initial
      // containing block and the containing block height is the
      // viewport height, which can't change during incremental
      // reflow.
      bool cbHeightChanged =
        !(isRoot && NS_UNCONSTRAINEDSIZE == reflowState->ComputedHeight()) &&
        aMetrics.height != oldSize.height;

      absoluteContainer->Reflow(this, aPresContext, *reflowState,
                                state.mReflowStatus,
                                containingBlockSize.width,
                                containingBlockSize.height, true,
                                cbWidthChanged, cbHeightChanged,
                                &aMetrics.mOverflowAreas);

      //XXXfr Why isn't this rv (and others in this file) checked/returned?
    }
  }

  // Determine if we need to repaint our border, background or outline
  CheckInvalidateSizeChange(aMetrics);

  FinishAndStoreOverflow(&aMetrics);

  // Clear the float manager pointer in the block reflow state so we
  // don't waste time translating the coordinate system back on a dead
  // float manager.
  if (needFloatManager)
    state.mFloatManager = nsnull;

  aStatus = state.mReflowStatus;

#ifdef DEBUG
  // Between when we drain pushed floats and when we complete reflow,
  // we're allowed to have multiple continuations of the same float on
  // our floats list, since a first-in-flow might get pushed to a later
  // continuation of its containing block.  But it's not permitted
  // outside that time.
  nsLayoutUtils::AssertNoDuplicateContinuations(this, mFloats);

  if (gNoisyReflow) {
    IndentBy(stdout, gNoiseIndent);
    ListTag(stdout);
    printf(": status=%x (%scomplete) metrics=%d,%d carriedMargin=%d",
           aStatus, NS_FRAME_IS_COMPLETE(aStatus) ? "" : "not ",
           aMetrics.width, aMetrics.height,
           aMetrics.mCarriedOutBottomMargin.get());
    if (HasOverflowAreas()) {
      printf(" overflow-vis={%d,%d,%d,%d}",
             aMetrics.VisualOverflow().x,
             aMetrics.VisualOverflow().y,
             aMetrics.VisualOverflow().width,
             aMetrics.VisualOverflow().height);
      printf(" overflow-scr={%d,%d,%d,%d}",
             aMetrics.ScrollableOverflow().x,
             aMetrics.ScrollableOverflow().y,
             aMetrics.ScrollableOverflow().width,
             aMetrics.ScrollableOverflow().height);
    }
    printf("\n");
  }

  if (gLameReflowMetrics) {
    PRTime end = PR_Now();

    PRInt32 ectc = nsLineBox::GetCtorCount();
    PRInt32 numLines = mLines.size();
    if (!numLines) numLines = 1;
    PRTime delta, perLineDelta, lines;
    LL_I2L(lines, numLines);
    LL_SUB(delta, end, start);
    LL_DIV(perLineDelta, delta, lines);

    ListTag(stdout);
    char buf[400];
    PR_snprintf(buf, sizeof(buf),
                ": %lld elapsed (%lld per line) (%d lines; %d new lines)",
                delta, perLineDelta, numLines, ectc - ctc);
    printf("%s\n", buf);
  }
#endif

  NS_FRAME_SET_TRUNCATION(aStatus, (*reflowState), aMetrics);
  return rv;
}
Esempio n. 23
0
HRESULT FakeDevice::SetPropertyValues(
            ACCESS_SCOPE           Scope,
    _In_    LPCWSTR                wszObjectID,
    _In_    IPortableDeviceValues* pValues,
    _In_    IPortableDeviceValues* pResults,
    _In_    IPortableDeviceValues* pEventParams,
    _Out_   bool*                  pbObjectChanged)
{
    HRESULT      hr             = S_OK;
    FakeContent* pContent       = NULL;

    if ((wszObjectID     == NULL) ||
        (pValues         == NULL) ||
        (pResults        == NULL) ||
        (pEventParams    == NULL) ||
        (pbObjectChanged == NULL))
    {
        hr = E_POINTER;
        CHECK_HR(hr, "Cannot have NULL parameter");
        return hr;
    }

    *pbObjectChanged = false;

    hr = GetContent(Scope, wszObjectID, &pContent);
    CHECK_HR(hr, "Failed to get content '%ws'", wszObjectID);

    if (hr == S_OK)
    {
        hr = pContent->WriteValues(pValues, pResults, pbObjectChanged);
        CHECK_HR(hr, "Failed to write value for '%ws'", wszObjectID);

        if (SUCCEEDED(hr) && (*pbObjectChanged))  // hr can be S_OK or S_FALSE (if one or more property writes failed)
        {
            HRESULT hrEvent = pEventParams->SetGuidValue(WPD_EVENT_PARAMETER_EVENT_ID, WPD_EVENT_OBJECT_UPDATED);
            CHECK_HR(hrEvent, "Failed to add WPD_EVENT_PARAMETER_EVENT_ID");

            if (hrEvent == S_OK)
            {
                hrEvent = pEventParams->SetStringValue(WPD_OBJECT_PERSISTENT_UNIQUE_ID, pContent->PersistentUniqueID);
                CHECK_HR(hrEvent, "Failed to add WPD_OBJECT_PERSISTENT_UNIQUE_ID");
            }

            if (hrEvent == S_OK)
            {
                hrEvent = pEventParams->SetStringValue(WPD_EVENT_PARAMETER_OBJECT_PARENT_PERSISTENT_UNIQUE_ID, pContent->ParentPersistentUniqueID);
                CHECK_HR(hrEvent, "Failed to add WPD_EVENT_PARAMETER_OBJECT_PARENT_PERSISTENT_UNIQUE_ID");
            }

            if (hrEvent == S_OK)
            {
                // Adding this event parameter will allow WPD to scope this event to the container functional object
                hrEvent = pEventParams->SetStringValue(WPD_OBJECT_CONTAINER_FUNCTIONAL_OBJECT_ID, pContent->ContainerFunctionalObjectID);
                CHECK_HR(hrEvent, "Failed to add WPD_OBJECT_CONTAINER_FUNCTIONAL_OBJECT_ID");
            }
        }

    }

    return hr;
}
Esempio n. 24
0
NS_IMETHODIMP
nsResizerFrame::HandleEvent(nsPresContext* aPresContext,
                            nsGUIEvent* aEvent,
                            nsEventStatus* aEventStatus)
{
  NS_ENSURE_ARG_POINTER(aEventStatus);
  if (nsEventStatus_eConsumeNoDefault == *aEventStatus) {
    return NS_OK;
  }

  nsWeakFrame weakFrame(this);
  PRBool doDefault = PR_TRUE;

  switch (aEvent->message) {
    case NS_MOUSE_BUTTON_DOWN: {
      if (aEvent->eventStructType == NS_MOUSE_EVENT &&
        static_cast<nsMouseEvent*>(aEvent)->button == nsMouseEvent::eLeftButton)
      {
        nsCOMPtr<nsIBaseWindow> window;
        nsIPresShell* presShell = aPresContext->GetPresShell();
        nsIContent* contentToResize =
          GetContentToResize(presShell, getter_AddRefs(window));
        if (contentToResize) {
          nsIFrame* frameToResize = contentToResize->GetPrimaryFrame();
          if (!frameToResize)
            break;

          mMouseDownRect = frameToResize->GetScreenRect();
        }
        else {
          // ask the widget implementation to begin a resize drag if it can
          Direction direction = GetDirection();
          nsresult rv = aEvent->widget->BeginResizeDrag(aEvent,
                        direction.mHorizontal, direction.mVertical);
          if (rv == NS_ERROR_NOT_IMPLEMENTED && window) {
            // if there's no native resize support, we need to do window
            // resizing ourselves
            window->GetPositionAndSize(&mMouseDownRect.x, &mMouseDownRect.y,
                                       &mMouseDownRect.width, &mMouseDownRect.height);
          }
          else {
            // for native drags, don't set the fields below
            doDefault = PR_FALSE;
            break;
          }
        }

        // we're tracking
        mTrackingMouseMove = PR_TRUE;

        // remember current mouse coordinates
        mMouseDownPoint = aEvent->refPoint + aEvent->widget->WidgetToScreenOffset();

        nsIPresShell::SetCapturingContent(GetContent(), CAPTURE_IGNOREALLOWED);

        doDefault = PR_FALSE;
      }
    }
    break;

  case NS_MOUSE_BUTTON_UP: {

    if (mTrackingMouseMove && aEvent->eventStructType == NS_MOUSE_EVENT &&
        static_cast<nsMouseEvent*>(aEvent)->button == nsMouseEvent::eLeftButton)
    {
      // we're done tracking.
      mTrackingMouseMove = PR_FALSE;

      nsIPresShell::SetCapturingContent(nsnull, 0);

      doDefault = PR_FALSE;
    }
  }
  break;

  case NS_MOUSE_MOVE: {
    if (mTrackingMouseMove)
    {
      nsCOMPtr<nsIBaseWindow> window;
      nsIPresShell* presShell = aPresContext->GetPresShell();
      nsCOMPtr<nsIContent> contentToResize =
        GetContentToResize(presShell, getter_AddRefs(window));

      // check if the returned content really is a menupopup
      nsMenuPopupFrame* menuPopupFrame = nsnull;
      if (contentToResize) {
        nsIFrame* frameToResize = contentToResize->GetPrimaryFrame();
        if (frameToResize && frameToResize->GetType() == nsGkAtoms::menuPopupFrame) {
          menuPopupFrame = static_cast<nsMenuPopupFrame *>(frameToResize);
        }
      }

      // both MouseMove and direction are negative when pointing to the
      // top and left, and positive when pointing to the bottom and right

      // retrieve the offset of the mousemove event relative to the mousedown.
      // The difference is how much the resize needs to be
      nsIntPoint screenPoint(aEvent->refPoint + aEvent->widget->WidgetToScreenOffset());
      nsIntPoint mouseMove(screenPoint - mMouseDownPoint);

      // what direction should we go in? For content resizing, always use
      // 'bottomend'. For other windows, check the dir attribute.
      Direction direction;
      if (window || menuPopupFrame) {
        direction = GetDirection();
        if (menuPopupFrame) {
          menuPopupFrame->CanAdjustEdges(
            (direction.mHorizontal == -1) ? NS_SIDE_LEFT : NS_SIDE_RIGHT,
            (direction.mVertical == -1) ? NS_SIDE_TOP : NS_SIDE_BOTTOM, mouseMove);
        }
      }
      else if (contentToResize) {
        direction.mHorizontal =
          GetStyleVisibility()->mDirection == NS_STYLE_DIRECTION_RTL ? -1 : 1;
        direction.mVertical = 1;
      }
      else {
        break; // don't do anything if there's nothing to resize
      }

      nsIntRect rect = mMouseDownRect;
      AdjustDimensions(&rect.x, &rect.width, mouseMove.x, direction.mHorizontal);
      AdjustDimensions(&rect.y, &rect.height, mouseMove.y, direction.mVertical);

      // Don't allow resizing a window or a popup past the edge of the screen,
      // so adjust the rectangle to fit within the available screen area.
      if (window) {
        nsCOMPtr<nsIScreen> screen;
        nsCOMPtr<nsIScreenManager> sm(do_GetService("@mozilla.org/gfx/screenmanager;1"));
        if (sm) {
          nsIntRect frameRect = GetScreenRect();
          sm->ScreenForRect(frameRect.x, frameRect.y, 1, 1, getter_AddRefs(screen));
          if (screen) {
            nsIntRect screenRect;
            screen->GetRect(&screenRect.x, &screenRect.y,
                            &screenRect.width, &screenRect.height);
            rect.IntersectRect(rect, screenRect);
          }
        }
      }
      else if (menuPopupFrame) {
        nsPoint framePoint = menuPopupFrame->GetScreenRectInAppUnits().TopLeft();
        nsIFrame* rootFrame = aPresContext->PresShell()->FrameManager()->GetRootFrame();
        nsRect rootScreenRect = rootFrame->GetScreenRectInAppUnits();

        nsRect screenRect = menuPopupFrame->GetConstraintRect(framePoint, rootScreenRect);
        // round using ToInsidePixels as it's better to be a pixel too small
        // than be too large. If the popup is too large it could get flipped
        // to the opposite side of the anchor point while resizing.
        nsIntRect screenRectPixels = screenRect.ToInsidePixels(aPresContext->AppUnitsPerDevPixel());
        rect.IntersectRect(rect, screenRectPixels);
      }

      if (contentToResize) {
        nsIntRect cssRect =
          rect.ToAppUnits(aPresContext->AppUnitsPerDevPixel())
              .ToInsidePixels(nsPresContext::AppUnitsPerCSSPixel());

        nsAutoString widthstr, heightstr;
        widthstr.AppendInt(cssRect.width);
        heightstr.AppendInt(cssRect.height);

        // for XUL elements, just set the width and height attributes. For
        // other elements, set style.width and style.height
        if (contentToResize->IsXUL()) {
          nsIntRect oldRect;
          nsWeakFrame weakFrame(menuPopupFrame);
          if (menuPopupFrame) {
            nsCOMPtr<nsIWidget> widget;
            menuPopupFrame->GetWidget(getter_AddRefs(widget));
            if (widget)
              widget->GetScreenBounds(oldRect);
          }

          contentToResize->SetAttr(kNameSpaceID_None, nsGkAtoms::width, widthstr, PR_TRUE);
          contentToResize->SetAttr(kNameSpaceID_None, nsGkAtoms::height, heightstr, PR_TRUE);

          if (weakFrame.IsAlive() &&
              (oldRect.x != rect.x || oldRect.y != rect.y)) {
            // XXX This might go very wrong, since menu popups may add
            // offsets (e.g. from margins) to this position, so the popup's
            // widget won't end up at the desired position.
            menuPopupFrame->MoveTo(rect.x, rect.y, PR_TRUE);
          }
        }
        else {
          nsCOMPtr<nsIDOMElementCSSInlineStyle> inlineStyleContent =
            do_QueryInterface(contentToResize);
          if (inlineStyleContent) {
            widthstr += NS_LITERAL_STRING("px");
            heightstr += NS_LITERAL_STRING("px");

            nsCOMPtr<nsIDOMCSSStyleDeclaration> decl;
            inlineStyleContent->GetStyle(getter_AddRefs(decl));
            decl->SetProperty(NS_LITERAL_STRING("width"), widthstr, EmptyString());
            decl->SetProperty(NS_LITERAL_STRING("height"), heightstr, EmptyString());
          }
        }
      }
      else {
        window->SetPositionAndSize(rect.x, rect.y, rect.width, rect.height, PR_TRUE); // do the repaint.
      }

      doDefault = PR_FALSE;
    }
  }
  break;

  case NS_MOUSE_CLICK:
    if (NS_IS_MOUSE_LEFT_CLICK(aEvent))
    {
      MouseClicked(aPresContext, aEvent);
    }
    break;
  }

  if (!doDefault)
    *aEventStatus = nsEventStatus_eConsumeNoDefault;

  if (doDefault && weakFrame.IsAlive())
    return nsTitleBarFrame::HandleEvent(aPresContext, aEvent, aEventStatus);
  else
    return NS_OK;
}
Esempio n. 25
0
NS_IMETHODIMP
nsTitleBarFrame::HandleEvent(nsPresContext* aPresContext,
                                      nsGUIEvent* aEvent,
                                      nsEventStatus* aEventStatus)
{
  NS_ENSURE_ARG_POINTER(aEventStatus);
  if (nsEventStatus_eConsumeNoDefault == *aEventStatus) {
    return NS_OK;
  }

  bool doDefault = true;

  switch (aEvent->message) {

   case NS_MOUSE_BUTTON_DOWN:  {
       if (aEvent->eventStructType == NS_MOUSE_EVENT &&
           static_cast<nsMouseEvent*>(aEvent)->button ==
             nsMouseEvent::eLeftButton)
       {
         // titlebar has no effect in non-chrome shells
         nsCOMPtr<nsISupports> cont = aPresContext->GetContainer();
         nsCOMPtr<nsIDocShellTreeItem> dsti = do_QueryInterface(cont);
         if (dsti) {
           PRInt32 type = -1;
           if (NS_SUCCEEDED(dsti->GetItemType(&type)) &&
               type == nsIDocShellTreeItem::typeChrome) {
             // we're tracking.
             mTrackingMouseMove = true;

             // start capture.
             nsIPresShell::SetCapturingContent(GetContent(), CAPTURE_IGNOREALLOWED);

             // remember current mouse coordinates.
             mLastPoint = aEvent->refPoint;
           }
         }

         *aEventStatus = nsEventStatus_eConsumeNoDefault;
         doDefault = false;
       }
     }
     break;


   case NS_MOUSE_BUTTON_UP: {
       if(mTrackingMouseMove && aEvent->eventStructType == NS_MOUSE_EVENT &&
          static_cast<nsMouseEvent*>(aEvent)->button ==
            nsMouseEvent::eLeftButton)
       {
         // we're done tracking.
         mTrackingMouseMove = false;

         // end capture
         nsIPresShell::SetCapturingContent(nsnull, 0);

         *aEventStatus = nsEventStatus_eConsumeNoDefault;
         doDefault = false;
       }
     }
     break;

   case NS_MOUSE_MOVE: {
       if(mTrackingMouseMove)
       {
         nsIntPoint nsMoveBy = aEvent->refPoint - mLastPoint;

         nsIFrame* parent = GetParent();
         while (parent && parent->GetType() != nsGkAtoms::menuPopupFrame)
           parent = parent->GetParent();

         // if the titlebar is in a popup, move the popup frame, otherwise
         // move the widget associated with the window
         if (parent) {
           nsMenuPopupFrame* menuPopupFrame = static_cast<nsMenuPopupFrame*>(parent);
           nsCOMPtr<nsIWidget> widget;
           menuPopupFrame->GetWidget(getter_AddRefs(widget));
           nsIntRect bounds;
           widget->GetScreenBounds(bounds);
           menuPopupFrame->MoveTo(bounds.x + nsMoveBy.x, bounds.y + nsMoveBy.y, false);
         }
         else {
           nsIPresShell* presShell = aPresContext->PresShell();
           nsPIDOMWindow *window = presShell->GetDocument()->GetWindow();
           if (window) {
             window->MoveBy(nsMoveBy.x, nsMoveBy.y);
           }
         }

         *aEventStatus = nsEventStatus_eConsumeNoDefault;

         doDefault = false;
       }
     }
     break;



    case NS_MOUSE_CLICK:
      if (NS_IS_MOUSE_LEFT_CLICK(aEvent))
      {
        MouseClicked(aPresContext, aEvent);
      }
      break;
  }

  if ( doDefault )
    return nsBoxFrame::HandleEvent(aPresContext, aEvent, aEventStatus);
  else
    return NS_OK;
}
Esempio n. 26
0
FString FHttpResponseWinInet::GetContentAsString()
{
	TArray<uint8> ZeroTerminatedPayload(GetContent());
	ZeroTerminatedPayload.Add(0);
	return UTF8_TO_TCHAR(ZeroTerminatedPayload.GetData());
}