コード例 #1
0
//-- Mark given widget as focussed
void FormWidget::SetFocussed( Widget *widget )
{
    C_assert( &widget->GetEnvironment()->GetForm() == this );
    //C_assert( _actual_focus != widget);
    _dont_cycle = true; 
    Widget *previous = _actual_focus;
    if ( _cycler->Set(widget) && GetEnvironment() && widget!=_actual_focus )
    {
        if ( !HasFocus() )
        {
            Form &parent_form= GetEnvironment()->GetForm();
            parent_form.SetFocussed(this); 
        }
        _actual_focus = _cycler->Who();
        _actual_focus->OnFocus.Send();
        C_assert( _actual_focus != previous);
        if ( previous ) { previous->OffFocus.Send(); }
    }
    _dont_cycle = false;
}
コード例 #2
0
 bool WidgetTableWidget::Remove ( int column, int row)
 {
     Widget *client = WidgetTableWidget::Retrieve( column, row);
     if (client)
     {
         if ( const WidgetEnvironment *penv = GetEnvironment() ) { penv->GetTrashCan().Trash(client); }
         else { delete client; }
         return true;
     }
     return false;
 }
コード例 #3
0
ファイル: libopenrave_c.cpp プロジェクト: ahundt/openrave
int ORCEnvironmentGetRobots(void* env, void** robots)
{
    EnvironmentBasePtr penv = GetEnvironment(env);
    std::vector<RobotBasePtr> vrobots;
    penv->GetRobots(vrobots);
    if( !robots ) {
        return static_cast<int>(vrobots.size());
    }
    for(size_t i = 0; i < vrobots.size(); ++i) {
        robots[i] = new InterfaceBasePtr(vrobots[i]);
    }
    return vrobots.size();
}
コード例 #4
0
ファイル: libopenrave_c.cpp プロジェクト: ahundt/openrave
int ORCEnvironmentGetBodies(void* env, void** bodies)
{
    EnvironmentBasePtr penv = GetEnvironment(env);
    std::vector<KinBodyPtr> vbodies;
    penv->GetBodies(vbodies);
    if( !bodies ) {
        return static_cast<int>(vbodies.size());
    }
    for(size_t i = 0; i < vbodies.size(); ++i) {
        bodies[i] = new InterfaceBasePtr(vbodies[i]);
    }
    return vbodies.size();
}
コード例 #5
0
String JniDeviceInfo::GetRegion()
{
	jclass javaClass = GetJavaClass();
	if (!javaClass)
		return "";

	intermediateStr = "";
	jmethodID mid = GetMethodID(javaClass, "GetRegion", "()V");
	if (mid)
		GetEnvironment()->CallStaticVoidMethod(javaClass, mid, 0);
	ReleaseJavaClass(javaClass);

	return intermediateStr;
}
コード例 #6
0
ファイル: htmldoc.cpp プロジェクト: prestocore/browser
/* virtual */ ES_PutState
DOM_HTMLDocument::PutNameRestart(OpAtom property_name, ES_Value* value, ES_Runtime* origining_runtime, ES_Object *restart_object)
{
	if (property_name == OP_ATOM_body)
		return ((DOM_HTMLElement *) root)->PutChildElement(OP_ATOM_body, value, (DOM_Runtime *) origining_runtime, restart_object);
	else if (property_name == OP_ATOM_title)
		if (HTML_Element *element = GetElement(HE_TITLE))
		{
			DOM_Node *node;
			PUT_FAILED_IF_ERROR(GetEnvironment()->ConstructNode(node, element, this));
			return node->PutNameRestart(OP_ATOM_text, value, origining_runtime, restart_object);
		}
		else
			return PUT_SUCCESS;
	else
		return PUT_FAILED;
}
コード例 #7
0
bool JniMailSender::SendEmail(const String& email, const String& subject, const String& messageText)
{
	jmethodID mid = GetMethodID("SendEMail", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)Z");
	bool res = false;
	if (mid)
	{
		jstring jEMail = GetEnvironment()->NewStringUTF(email.c_str());
		jstring jSubject = GetEnvironment()->NewStringUTF(subject.c_str());
		jstring jMessageText = GetEnvironment()->NewStringUTF(messageText.c_str());
		res = GetEnvironment()->CallStaticBooleanMethod(javaClass, mid, jEMail, jSubject, jMessageText);
		GetEnvironment()->DeleteLocalRef(jEMail);
		GetEnvironment()->DeleteLocalRef(jSubject);
		GetEnvironment()->DeleteLocalRef(jMessageText);
	}
	return res;
}
コード例 #8
0
ファイル: htmldoc.cpp プロジェクト: prestocore/browser
ES_PutState
DOM_HTMLDocument::SetTitle(ES_Value *value, ES_Runtime *origining_runtime)
{
	HTML_Element *title_element = GetElement(HE_TITLE);
	DOM_EnvironmentImpl *environment = GetEnvironment();

	if (!title_element)
	{
		/* Invent <title> on the spot... */
		HTML_Element *head_element = GetElement(HE_HEAD);
		if (!head_element)
		{
			/* ..and its <head> parent, if not there. */

			if (!GetRootElement())
				/* nowhere to add, quietly ignore title update. */
				return PUT_SUCCESS;

			PUT_FAILED_IF_ERROR(HTML_Element::DOMCreateElement(head_element, environment, UNI_L("head"), NS_IDX_HTML));
			PUT_FAILED_IF_ERROR(GetRootElement()->GetThisElement()->DOMInsertChild(environment, head_element, NULL));
			/* the element has been added to the tree, hence no leak - error stems from signalling the insertion. */
		}

		if (head_element)
		{
			PUT_FAILED_IF_ERROR(HTML_Element::DOMCreateElement(title_element, environment, UNI_L("title"), NS_IDX_HTML));
			PUT_FAILED_IF_ERROR(head_element->DOMInsertChild(environment, title_element, NULL));
		}

		/* Note/FIXME: the insertion of a <title> element, and possibly <head>, is synchronous and does not issue any mutation events, like
		   would be done when using e.g., DOM_Node::insertBefore(). Doing so would be preferable, but would turn SetTitle() into an async operation
		   to handle the invocation of mutation event listeners. Leave as is for now, but may (have to) revisit. */
	}

	if (title_element)
	{
		DOM_Node *title_node;
		PUT_FAILED_IF_ERROR(environment->ConstructNode(title_node, title_element, this));
		return title_node->PutName(OP_ATOM_text, value, origining_runtime);
	}

	return PUT_SUCCESS;
}
コード例 #9
0
ファイル: domstringmap.cpp プロジェクト: prestocore/browser
/* virtual */ ES_DeleteStatus
DOM_DOMStringMap::DeleteName(const uni_char* property_name, ES_Runtime *origining_runtime)
{
	TempBuffer attribute_name;
	OP_STATUS status = MapPropertyToAttributeName(property_name, attribute_name);
	if (OpStatus::IsMemoryError(status))
		return DELETE_NO_MEMORY;
	if (OpStatus::IsSuccess(status))
	{
		DOM_EnvironmentImpl *environment = GetEnvironment();
		int index;
		BOOL case_sensitive = owner->HasCaseSensitiveNames();
		HTML_Element *element = owner->GetThisElement();
		if (element->DOMHasAttribute(environment, ATTR_XML, attribute_name.GetStorage(), NS_IDX_ANY_NAMESPACE, case_sensitive, index))
			DELETE_FAILED_IF_MEMORY_ERROR(element->DOMRemoveAttribute(environment, attribute_name.GetStorage(), NS_IDX_ANY_NAMESPACE, case_sensitive));
	}

	return DELETE_OK;
}
コード例 #10
0
bool HubWidget::Insert(Widget *widget, int x, int y, int z)
{
    assert(widget&&"HubWidget::Insert(): NULL pointer passed");

    ZWidgetList::ConstIterator iter;
    if ( _z_indices.FindID(widget, &iter) ) { _z_indices.RemoveAt(iter); }

    widget->SetPosition( Pos(x,y) );
    _z_indices.Insert( z, widget );
    DBG_Insert;

    widget->SetParent( this );
    if ( !!GetEnvironment() )
    {
        widget->SetEnvironment( GetChildrenEnvironment() );
        widget->SetDirty();
    }
    return true;
}
コード例 #11
0
JILMediaElement * DOM_JILMediaPlayer::GetJILMediaElement(BOOL construct)
{
	JILMediaElement *media_element = NULL;
	if (!m_element && construct)
	{
		DOM_HTMLElement * new_element;
		// The document node should exist here, but just to make sure...
		RETURN_VALUE_IF_ERROR(GetEnvironment()->ConstructDocumentNode(), NULL);
		RETURN_VALUE_IF_ERROR(DOM_HTMLElement::CreateElement(new_element, static_cast<DOM_Node*>(GetEnvironment()->GetDocument()), UNI_L("object")), NULL);

		// If this fails node node will be garbage collected next time garbage collector is run.
		OP_STATUS result = SetWindowInternal(static_cast<DOM_Element*>(new_element));
		if (OpStatus::IsError(result))
			return NULL;
	}
	HTML_Element *element = m_element ? m_element->GetThisElement() : NULL;
	if (element)
		media_element = static_cast<JILMediaElement*>(element->GetSpecialAttr(Markup::MEDA_COMPLEX_JIL_MEDIA_ELEMENT, ITEM_TYPE_COMPLEX, NULL, SpecialNs::NS_MEDIA));

	return media_element;
}
コード例 #12
0
void JniCrashReporter::ThrowJavaExpetion(const Vector<CrashStep>& chashSteps)
{
	jmethodID mid = GetMethodID("ThrowJavaExpetion", "([Ljava/lang/String;[Ljava/lang/String;[I)V");
	if (mid)
	{
		jobjectArray jModuleArray = GetEnvironment()->NewObjectArray(chashSteps.size(), gStringClass, 0);
		jobjectArray jFunctionArray = GetEnvironment()->NewObjectArray(chashSteps.size(), gStringClass, 0);
		jintArray jFileLineArray = GetEnvironment()->NewIntArray(chashSteps.size());

		int* fileLines = new int[chashSteps.size()];
		for (uint i = 0; i < chashSteps.size(); ++i)
		{
			GetEnvironment()->SetObjectArrayElement(jModuleArray, i, GetEnvironment()->NewStringUTF(chashSteps[i].module.c_str()));
			GetEnvironment()->SetObjectArrayElement(jFunctionArray, i, GetEnvironment()->NewStringUTF(chashSteps[i].function.c_str()));
			fileLines[i] = chashSteps[i].fileLine;
		}
		GetEnvironment()->SetIntArrayRegion(jFileLineArray, 0, chashSteps.size(), fileLines);

		env->CallStaticVoidMethod(GetJavaClass(), mid, jModuleArray, jFunctionArray, jFileLineArray);

		delete [] fileLines;
	}
}
コード例 #13
0
ファイル: Widget.cpp プロジェクト: BackupTheBerlios/utgs-svn
// Methos allocates space for widget
void Widget::SetBoundingRect( const Rect &r )
{
    Rect previous = _bound;
    _bound = r;
    bool anything_changed=false;

    if ( GetEnvironment() )
    {
        _parent->SetDirty( previous | _bound );
    }
    if ( _bound.GetX() != previous.GetX() || _bound.GetY() != previous.GetY() )
    {
        OnReposition.Send_1( Pos( _bound.GetX(), _bound.GetY() ));
        anything_changed=true;
    }
    if ( _bound.GetW() != previous.GetW() || _bound.GetH() != previous.GetH() )
    {
        OnResize.Send_2( _bound.GetW(), _bound.GetH() );
        anything_changed=true;
    }
    if ( anything_changed )
        NotifyAncestors(true);
}
コード例 #14
0
ファイル: htmldoc.cpp プロジェクト: prestocore/browser
OP_STATUS
DOM_HTMLDocument::GetBodyNode(DOM_Element *&element)
{
	HTML_Element *body = NULL;

	if (IsMainDocument())
		if (HLDocProfile *hld_profile = GetHLDocProfile())
			if ((body = hld_profile->GetBodyElm()) != NULL)
				if (!body->IsIncludedActual())
					body = NULL;

	if (!body && placeholder)
	{
		HTML_Element *child = placeholder->FirstChildActual();
		while (child)
			if (child->IsMatchingType(HE_BODY, NS_HTML) || child->IsMatchingType(HE_FRAMESET, NS_HTML))
			{
				body = child;
				break;
			}
			else
				child = child->NextActual();
	}

	if (body)
	{
		DOM_Node *node;

		RETURN_IF_ERROR(GetEnvironment()->ConstructNode(node, body, this));

		element = static_cast<DOM_Element *>(node);
	}
	else
		element = NULL;

	return OpStatus::OK;
}
コード例 #15
0
ファイル: domstringmap.cpp プロジェクト: prestocore/browser
/* virtual */ ES_GetState
DOM_DOMStringMap::GetName(const uni_char* property_name, int property_code, ES_Value* value, ES_Runtime* origining_runtime)
{
	TempBuffer attribute_name;
	OP_STATUS status = MapPropertyToAttributeName(property_name, attribute_name);
	if (OpStatus::IsMemoryError(status))
		return GET_NO_MEMORY;
	if (OpStatus::IsSuccess(status))
	{
		OP_ASSERT(attribute_name.GetStorage());
		DOM_EnvironmentImpl *environment = GetEnvironment();
		int index;
		BOOL case_sensitive = owner->HasCaseSensitiveNames();
		HTML_Element *element = owner->GetThisElement();
		if (element->DOMHasAttribute(environment, ATTR_XML, attribute_name.GetStorage(), NS_IDX_ANY_NAMESPACE, case_sensitive, index))
		{
			if (value)
				DOMSetString(value, element->DOMGetAttribute(environment, ATTR_XML, attribute_name.GetStorage(), NS_IDX_ANY_NAMESPACE, case_sensitive, FALSE, index));
			return GET_SUCCESS;
		}
	}

	return DOM_Object::GetName(property_name, property_code, value, origining_runtime);
}
コード例 #16
0
void FormWidget::HandleKey( int key_code )
{
    if ( Widget **p = _accelerators.Find(key_code) )
    {
        if ( (*p)->IsRealyVisible() )
        {
            (*p)->Accept( Widget::InputAccel(key_code) );
        }
    }

    if ( key_code == _submit_key )
    {
        OnSubmit.Switch( true );
    }
    else if ( key_code == _cancel_key )
    {
        OnSubmit.Switch( false );
    }

    else if ( key_code == Keys::TAB )
    {
        bool backwards = IsKeyPressed( Keys::LSHIFT ) || IsKeyPressed( Keys::RSHIFT );
        bool context = IsKeyPressed( Keys::LCTRL ) || IsKeyPressed( Keys::RCTRL );
        Form *pform = (context)? &GetEnvironment()->GetForm() : this;
        assert( pform );
        pform->CycleFocus( (backwards)? PREVIOUS : NEXT );
    }
    else if ( key_code==Keys::UP || key_code==Keys::LEFT )
    {
        CycleFocus( PREVIOUS );
    }
    else if ( key_code == Keys::DOWN || key_code==Keys::RIGHT )
    {
        CycleFocus( NEXT );
    }
}
コード例 #17
0
ファイル: QueryCommand.cpp プロジェクト: danluu/BitFunnel
    void Query::Execute()
    {
        std::ostream& output = GetEnvironment().GetOutputStream();

        if (m_isSingleQuery)
        {
            output
                << "Processing query \""
                << m_query
                << "\"" << std::endl;
            auto instrumentation =
                QueryRunner::Run(m_query.c_str(),
                                 GetEnvironment().GetSimpleIndex(),
                                 GetEnvironment().GetCompilerMode(),
                                 GetEnvironment().GetCacheLineCountMode());

            output << "Results:" << std::endl;
            CsvTsv::CsvTableFormatter formatter(output);
            QueryInstrumentation::Data::FormatHeader(formatter);
            instrumentation.Format(formatter);
        }
        else
        {
            CHECK_NE(*GetEnvironment().GetOutputDir().c_str(), '\0')
                << "Output directory not set. "
                << "Please use the 'cd' command to set an "
                << "output directory";

            output
                << "Processing queries from log at \""
                << m_query
                << "\"" << std::endl;

            std::string const & filename = m_query;
            auto fileSystem = Factories::CreateFileSystem();  // TODO: Use environment file system
            auto queries = ReadLines(*fileSystem, filename.c_str());
            const size_t c_threadCount = GetEnvironment().GetThreadCount();
            const size_t c_iterations = 1;
            auto statistics =
                QueryRunner::Run(GetEnvironment().GetSimpleIndex(),
                                 GetEnvironment().GetOutputDir().c_str(),
                                 c_threadCount,
                                 queries,
                                 c_iterations,
                                 GetEnvironment().GetCompilerMode(),
                                 GetEnvironment().GetCacheLineCountMode());
            output << "Results:" << std::endl;
            statistics.Print(output);

            // TODO: unify this with the fileManager that's passed into
            // QueryRunner::Run.
            auto outFileManager =
                Factories::CreateFileManager(GetEnvironment().GetOutputDir().c_str(),
                                             GetEnvironment().GetOutputDir().c_str(),
                                             GetEnvironment().GetOutputDir().c_str(),
                                             GetEnvironment().GetSimpleIndex().GetFileSystem());

            auto outSummary = outFileManager->QuerySummaryStatistics().OpenForWrite();
            statistics.Print(*outSummary);
        }
    }
コード例 #18
0
ファイル: ShowCommand.cpp プロジェクト: BitFunnel/BitFunnel
    void Show::Execute()
    {
        std::ostream& output = GetEnvironment().GetOutputStream();

        if (m_mode == Mode::Cache)
        {
            auto & environment = GetEnvironment();
            Term term(m_term.c_str(), 0, environment.GetConfiguration());
            auto & cache = environment.GetIngestor().GetDocumentCache();

            output << "DocId, Contains" << std::endl;
            for (auto entry : cache)
            {
                output
                    << "  DocId(" << entry.second << ") ";
                if (entry.first.Contains(term))
                {
                    output << "contains ";
                }
                else
                {
                    output << "does not contain ";
                }
                output << m_term << std::endl;
            }
        }
        else
        {
            // TODO: Consider parsing phrase terms here.
            auto & environment = GetEnvironment();
            Term term(m_term.c_str(), 0, environment.GetConfiguration());

            output
                << "Term("
                << "\"" << m_term << "\""
                << ")" << std::endl;

            IIngestor & ingestor = GetEnvironment().GetIngestor();

            auto maxshard = environment.GetMaxShard();
            for (auto shardId = environment.GetMinShard(); shardId <= maxshard; ++shardId)
            {

                output
                    << "Shard: " << shardId << std::endl;

                // Gather DocIds for first 64 documents in shard
                IShard& shard = ingestor.GetShard(shardId);
                std::vector<DocId> ids;
                auto itPtr = shard.GetIterator();
                auto & it = *itPtr;
                for (size_t i = 0; i < 64 && !it.AtEnd(); ++it, ++i)
                {
                    ids.push_back((*it).GetDocId());
                }

                // Print out 100s digit of DocId.
                output << "                 d ";
                for (auto id : ids)
                {
                    output << ((id / 100) % 10);
                }
                output << std::endl;

                // Print ouf 10s digit of DocId.
                output << "                 o ";
                for (auto id : ids)
                {
                    output << ((id / 10) % 10);
                }
                output << std::endl;

                // Print out 1s digit of DocId.
                output << "                 c ";
                for (auto id : ids)
                {
                    output << (id % 10);
                }
                output << std::endl;

                // Print out RowIds and their bits.
                RowIdSequence rows(term, environment.GetTermTable(shardId));
                for (auto row : rows)
                {
                    output
                        << "  RowId("
                        << row.GetRank()
                        << ", "
                        << std::setw(5)
                        << row.GetIndex()
                        << ")";

                    if (m_mode == Mode::Rows)
                    {
                        output << ": ";
                        for (auto id : ids)
                        {
                            if (ingestor.Contains(id))
                            {
                                auto handle = ingestor.GetHandle(id);
                                output << (handle.GetBit(row) ? "1" : "0");
                            }
                        }
                    }

                    output << std::endl;
                }
            }
        }
    }
コード例 #19
0
ファイル: ProcessAsUser.cpp プロジェクト: JetBrains/runAs
Result<ExitCode> ProcessAsUser::Run(const Settings& settings, ProcessTracker& processTracker) const
{
	Trace trace(settings.GetLogLevel());
	trace < L"ProcessAsUser::Attempt to log a user on to the local computer";
	StringBuffer userName(settings.GetUserName());
	StringBuffer domain(settings.GetDomain());
	StringBuffer password(settings.GetPassword());
	StringBuffer workingDirectory(settings.GetWorkingDirectory());
	StringBuffer commandLine(settings.GetCommandLine());

	SecurityManager securityManager;
	auto setPrivilegesResult = securityManager.SetPrivileges(trace, { SE_TCB_NAME, SE_ASSIGNPRIMARYTOKEN_NAME }, true);
	if(setPrivilegesResult.HasError())
	{
		return setPrivilegesResult.GetError();
	}

	auto newUserSecurityTokenHandle = Handle(L"New user security token");
	unsigned long logonTypeCount = sizeof(allLogonTypes) / sizeof(allLogonTypes[0]);
	for (unsigned long logonTypeIndex = 0; logonTypeIndex < logonTypeCount; logonTypeIndex++)
	{
		auto logonType = allLogonTypes[logonTypeIndex];
		trace < L"::LogonUser using logon type ";
		switch (logonType)
		{
			case LOGON32_LOGON_INTERACTIVE:
				trace << L"LOGON32_LOGON_INTERACTIVE";
				break;

			case LOGON32_LOGON_NETWORK:
				trace << L"LOGON32_LOGON_NETWORK";
				break;

			case LOGON32_LOGON_BATCH:
				trace << L"LOGON32_LOGON_BATCH";
				break;

			case LOGON32_LOGON_SERVICE:
				trace << L"LOGON32_LOGON_SERVICE";
				break;
		}

		if (LogonUser(
			userName.GetPointer(),
			domain.GetPointer(),
			password.GetPointer(),
			logonType,
			LOGON32_PROVIDER_DEFAULT,
			&newUserSecurityTokenHandle))
		{
			break;
		}
		
		auto error = Error(L"LogonUser");
		trace << L" - ";
		trace << error.GetDescription();

		if(logonTypeIndex == logonTypeCount -1)
		{
			return error;
		}
	}

	trace < L"ProcessAsUser::InitializeConsoleRedirection a new security descriptor";
	trace < L"::InitializeSecurityDescriptor";
	SECURITY_DESCRIPTOR securityDescriptor = {};
	if (!InitializeSecurityDescriptor(
		&securityDescriptor,
		SECURITY_DESCRIPTOR_REVISION))
	{
		return Error(L"InitializeSecurityDescriptor");
	}

	trace < L"::SetSecurityDescriptorDacl";
	if (!SetSecurityDescriptorDacl(
		&securityDescriptor,
		true,
		nullptr,
		false))
	{
		return Error(L"SetSecurityDescriptorDacl");
	}

	trace < L"ProcessAsUser::Creates a new access primary token that duplicates new process's token";
	auto primaryNewUserSecurityTokenHandle = Handle(L"Primary new user security token");
	SECURITY_ATTRIBUTES processSecAttributes = {};
	processSecAttributes.lpSecurityDescriptor = &securityDescriptor;
	processSecAttributes.nLength = sizeof(SECURITY_DESCRIPTOR);
	processSecAttributes.bInheritHandle = true;
	trace < L"::DuplicateTokenEx";
	if (!DuplicateTokenEx(
		newUserSecurityTokenHandle,
		0, // MAXIMUM_ALLOWED
		&processSecAttributes,
		SecurityImpersonation,
		TokenPrimary,
		&primaryNewUserSecurityTokenHandle))
	{
		return Error(L"DuplicateTokenEx");
	}	

	SECURITY_ATTRIBUTES threadSecAttributes = {};
	threadSecAttributes.lpSecurityDescriptor = nullptr;
	threadSecAttributes.nLength = 0;
	threadSecAttributes.bInheritHandle = false;	
	STARTUPINFO startupInfo = {};	

	trace < L"ProcessTracker::InitializeConsoleRedirection";
	auto error = processTracker.InitializeConsoleRedirection(processSecAttributes, startupInfo);
	if(error.HasError())
	{
		return Result<ExitCode>(error.GetError());
	}

	trace < L"::LoadUserProfile";
	PROFILEINFO profileInfo = {};
	profileInfo.dwSize = sizeof(PROFILEINFO);
	profileInfo.lpUserName = userName.GetPointer();
	if (!LoadUserProfile(primaryNewUserSecurityTokenHandle, &profileInfo))
	{
		return Error(L"LoadUserProfile");
	}

	auto newProcessEnvironmentResult = GetEnvironment(settings, primaryNewUserSecurityTokenHandle, settings.GetInheritanceMode(), trace);
	if (newProcessEnvironmentResult.HasError())
	{
		UnloadUserProfile(primaryNewUserSecurityTokenHandle, profileInfo.hProfile);
		return Result<ExitCode>(newProcessEnvironmentResult.GetError());
	}

	auto setIntegrityLevelResult = securityManager.SetIntegrityLevel(settings.GetIntegrityLevel(), primaryNewUserSecurityTokenHandle, trace);
	if (setIntegrityLevelResult.HasError())
	{
		return Result<ExitCode>(setIntegrityLevelResult.GetError());
	}

	trace < L"ProcessAsUser::Create a new process and its primary thread. The new process runs in the security context of the user represented by the specified token.";
	PROCESS_INFORMATION processInformation = {};
	startupInfo.dwFlags = STARTF_USESHOWWINDOW;
	startupInfo.wShowWindow = ShowModeConverter::ToShowWindowFlag(settings.GetShowMode());
	auto cmdLine = settings.GetCommandLine();
	trace < L"::CreateProcessAsUser";	
	if (!CreateProcessAsUser(
		primaryNewUserSecurityTokenHandle,
		nullptr,
		commandLine.GetPointer(),
		&processSecAttributes,
		&threadSecAttributes,
		true,
		CREATE_UNICODE_ENVIRONMENT,
		newProcessEnvironmentResult.GetResultValue().CreateEnvironment(),
		workingDirectory.GetPointer(),
		&startupInfo,
		&processInformation))
	{		
		auto result = Error(L"CreateProcessAsUser");
		UnloadUserProfile(primaryNewUserSecurityTokenHandle, profileInfo.hProfile);
		return result;
	}

	// ReSharper disable CppInitializedValueIsAlwaysRewritten
	// ReSharper disable CppEntityAssignedButNoRead
	
	auto processHandle = Handle(L"Service Process");
	processHandle = processInformation.hProcess;
	
	auto threadHandle = Handle(L"Thread");
	threadHandle = processInformation.hThread;

	auto exitCode = processTracker.WaiteForExit(processInformation.hProcess, trace);
	UnloadUserProfile(primaryNewUserSecurityTokenHandle, profileInfo.hProfile);	

	return exitCode;
}
コード例 #20
0
ファイル: htmldoc.cpp プロジェクト: prestocore/browser
/* virtual */ ES_GetState
DOM_HTMLDocument::GetName(OpAtom property_name, ES_Value* value, ES_Runtime* origining_runtime)
{
	DOM_EnvironmentImpl *environment = GetEnvironment();
	DOM_Runtime *runtime = environment->GetDOMRuntime();
	FramesDocument *frames_doc = environment->GetFramesDocument();

	switch(property_name)
	{
	case OP_ATOM_title:
		return GetTitle(value);

	case OP_ATOM_domain:
		if (value)
		{
			DOMSetString(value);
			if (!runtime->GetMutableOrigin()->IsUniqueOrigin())
			{
				const uni_char *domain;
				runtime->GetDomain(&domain, NULL, NULL);
				DOMSetString(value, domain);
			}
		}
		return GET_SUCCESS;

	case OP_ATOM_URL:
		if (value)
		{
			const uni_char *url;

			if (frames_doc)
				url = frames_doc->GetURL().GetAttribute(URL::KUniName_With_Fragment_Username_Password_Hidden).CStr();
			else
				url = NULL;

			DOMSetString(value, url);
		}
		return GET_SUCCESS;

	case OP_ATOM_head:
		if (value)
		{
			HTML_Element *element = GetPlaceholderElement();
			if (element)
			{
				element = element->FirstChildActual();
				while (element && !element->IsMatchingType(HE_HTML, NS_HTML))
					element = element->SucActual();

				if (element)
				{
					element = element->FirstChildActual();
					while (element && !element->IsMatchingType(HE_HEAD, NS_HTML))
						element = element->SucActual();
				}
			}
			return DOMSetElement(value, element);
		}
		return GET_SUCCESS;

	case OP_ATOM_body:
		if (value)
		{
			DOM_Element *element;

			GET_FAILED_IF_ERROR(GetBodyNode(element));

			DOMSetObject(value, element);
		}
		return GET_SUCCESS;

	case OP_ATOM_bgColor:
	case OP_ATOM_fgColor:
	case OP_ATOM_linkColor:
	case OP_ATOM_alinkColor:
	case OP_ATOM_vlinkColor:
		if (value)
		{
			DOM_Element *element;

			GET_FAILED_IF_ERROR(GetBodyNode(element));

			if (element && element->GetThisElement()->IsMatchingType(HE_BODY, NS_HTML))
			{
				if (property_name == OP_ATOM_fgColor)
					property_name = OP_ATOM_text;
				else if (property_name == OP_ATOM_linkColor)
					property_name = OP_ATOM_link;
				else if (property_name == OP_ATOM_alinkColor)
					property_name = OP_ATOM_aLink;
				else if (property_name == OP_ATOM_vlinkColor)
					property_name = OP_ATOM_vLink;

				return element->GetName(property_name, value, origining_runtime);
			}
			else
				DOMSetString(value);
		}
		return GET_SUCCESS;

	case OP_ATOM_images:
	case OP_ATOM_applets:
	case OP_ATOM_links:
	case OP_ATOM_forms:
	case OP_ATOM_anchors:
	case OP_ATOM_embeds:
	case OP_ATOM_plugins:
	case OP_ATOM_scripts:
	case OP_ATOM_all:
		return GetCollection(value, property_name);

	case OP_ATOM_frames:
		DOMSetObject(value, environment->GetWindow());
		return GET_SUCCESS;

	case OP_ATOM_compatMode:
		if (value)
			if (HLDocProfile *hld_profile = GetHLDocProfile())
			{
				if (hld_profile->IsInStrictMode())
					DOMSetString(value, UNI_L("CSS1Compat"));
				else
					DOMSetString(value, UNI_L("BackCompat"));
			}
		return GET_SUCCESS;

	case OP_ATOM_activeElement:
		if (value)
			if (frames_doc && IsMainDocument())
				return DOMSetElement(value, frames_doc->DOMGetActiveElement());
			else
				DOMSetNull(value);
		return GET_SUCCESS;
	}

	return DOM_Document::GetName(property_name, value, origining_runtime);
}
コード例 #21
0
//-- Tell parent form to focus other widget
//-- Method releases focus
void FormWidget::CycleParentForm( int mode )
{
    Form *pform = &GetEnvironment()->GetForm();
    pform->CycleFocus( mode );
}
コード例 #22
0
ファイル: libopenrave_c.cpp プロジェクト: ahundt/openrave
int ORCEnvironmentAddModule(void* env, void* module, const char* args)
{
    return GetEnvironment(env)->AddModule(GetModule(module), args);
}
コード例 #23
0
//-- Obtain children environmnet
//-- method used by CompoundWidget when setting env. for each child
const WidgetEnvironment* FormWidget::GetChildrenEnvironment() const
{
    return (!GetEnvironment())? NULL : &_child_env; 
}
コード例 #24
0
ファイル: xsm.c プロジェクト: aosm/X11
Status
StartSession(char *name, Bool use_default)
{
    int database_read = 0;
    Dimension width;
    char title[256];


    /*
     * If we're not using the default session, lock it.
     * If using the default session, it will be locked as
     * soon as the user assigns the session a name.
     */

    if (!use_default && !LockSession (name, True))
	return (0);


    /*
     * Get important environment variables.
     */

    GetEnvironment ();


    /*
     * Set the main window's title to the session name.
     */

    sprintf (title, "xsm: %s", name);

    XtVaSetValues (topLevel,
	XtNtitle, title,		/* session name */
	NULL);

    XtRealizeWidget (topLevel);


    /*
     * Set WM_DELETE_WINDOW support on main window.  If the user tries
     * to delete the main window, the shutdown prompt will come up.
     */

    SetWM_DELETE_WINDOW (topLevel, "DelMainWinAction()");


    /*
     * Read the session save file.  Make sure the session manager
     * has an SM_CLIENT_ID, so that other managers (like the WM) can
     * identify it.
     */

    set_session_save_file_name (name);

    if (use_default)
	need_to_name_session = True;
    else
    {
	database_read = ReadSave (name, &sm_id);
	need_to_name_session = !database_read;
    }

    if (!sm_id)
    {
	sm_id = SmsGenerateClientID (NULL);
	if (!sm_id) return (0);
    }
    XChangeProperty (XtDisplay (topLevel), XtWindow (topLevel),
	XInternAtom (XtDisplay (topLevel), "SM_CLIENT_ID", False),
	XA_STRING, 8, PropModeReplace,
	(unsigned char *) sm_id, strlen (sm_id));


    /*
     * Adjust some label widths
     */

    XtVaGetValues (clientInfoButton,
	XtNwidth, &width,
	NULL);

    XtVaSetValues (checkPointButton,
	XtNwidth, width,
	NULL);

    XtVaGetValues (logButton,
	XtNwidth, &width,
	NULL);

    XtVaSetValues (shutdownButton,
	XtNwidth, width,
	NULL);
    

    XtMapWidget (topLevel);


    if (!database_read)
    {
	/*
	 * Start default apps (e.g. twm, smproxy)
	 */

	StartDefaultApps ();
    }
    else
    {
	/*
	 * Restart window manager first.  When the session manager
	 * gets a WM_STATE stored on its top level window, we know
	 * the window manager is running.  At that time, we can start
	 * the rest of the applications.
	 */

	XtAddEventHandler (topLevel, PropertyChangeMask, False,
	    PropertyChangeXtHandler, NULL);

	if (!Restart (RESTART_MANAGERS))
	{
	    XtRemoveEventHandler (topLevel, PropertyChangeMask, False,
	        PropertyChangeXtHandler, NULL);

	    /*
	     * Restart the rest of the session aware clients.
	     */

	    Restart (RESTART_REST_OF_CLIENTS);

	    /*
	     * Start apps that aren't session aware that were specified
	     * by the user.
	     */
	    
	    StartNonSessionAwareApps ();
	}
    }

    return (1);
}
コード例 #25
0
ファイル: cgiapp.cpp プロジェクト: swuecho/igblast
int CCgiApplication::Run(void)
{
    // Value to return from this method Run()
    int result;

    // Try to run as a Fast-CGI loop
    if ( x_RunFastCGI(&result) ) {
        return result;
    }

    /// Run as a plain CGI application

    // Make sure to restore old diagnostic state after the Run()
    CDiagRestorer diag_restorer;

#if defined(NCBI_OS_UNIX)
    // Disable SIGPIPE if not allowed.
    if ( !TParamAllowSigpipe::GetDefault() ) {
        signal(SIGPIPE, SIG_IGN);
        struct sigaction sigterm,  sigtermold;
        memset(&sigterm, 0, sizeof(sigterm));
        sigterm.sa_handler = SigTermHandler;
        sigterm.sa_flags = SA_RESETHAND;
        if (sigaction(SIGTERM, &sigterm, &sigtermold) == 0
            &&  sigtermold.sa_handler != SIG_DFL) {
            sigaction(SIGTERM, &sigtermold, 0);
        }
    }

    // Compose diagnostics prefix
    PushDiagPostPrefix(NStr::IntToString(getpid()).c_str());
#endif
    PushDiagPostPrefix(GetEnvironment().Get(m_DiagPrefixEnv).c_str());

    // Timing
    CTime start_time(CTime::eCurrent);

    // Logging for statistics
    bool is_stat_log = GetConfig().GetBool("CGI", "StatLog", false,
                                           0, CNcbiRegistry::eReturn);
    bool skip_stat_log = false;
    auto_ptr<CCgiStatistics> stat(is_stat_log ? CreateStat() : 0);

    CNcbiOstream* orig_stream = NULL;
    //int orig_fd = -1;
    CNcbiStrstream result_copy;
    auto_ptr<CNcbiOstream> new_stream;

    try {
        _TRACE("(CGI) CCgiApplication::Run: calling ProcessRequest");
        GetDiagContext().SetAppState(eDiagAppState_RequestBegin);

        m_Context.reset( CreateContext() );
        _ASSERT(m_Context.get());
        m_Context->CheckStatus();

        ConfigureDiagnostics(*m_Context);
        x_AddLBCookie();
        try {
            // Print request start message
            x_OnEvent(eStartRequest, 0);

            VerifyCgiContext(*m_Context);
            ProcessHttpReferer();
            LogRequest();

            try {
                m_Cache.reset( GetCacheStorage() );
            } catch( exception& ex ) {
                ERR_POST_X(1, "Couldn't create cache : " << ex.what());
            }
            bool skip_process_request = false;
            bool caching_needed = IsCachingNeeded(m_Context->GetRequest());
            if (m_Cache.get() && caching_needed) {
                skip_process_request = GetResultFromCache(m_Context->GetRequest(),
                                                           m_Context->GetResponse().out());
            }
            if (!skip_process_request) {
                if( m_Cache.get() ) {
                    list<CNcbiOstream*> slist;
                    orig_stream = m_Context->GetResponse().GetOutput();
                    slist.push_back(orig_stream);
                    slist.push_back(&result_copy);
                    new_stream.reset(new CWStream(new CMultiWriter(slist), 0,0,
                                                  CRWStreambuf::fOwnWriter));
                    m_Context->GetResponse().SetOutput(new_stream.get());
                }
                GetDiagContext().SetAppState(eDiagAppState_Request);
                result = CCgiContext::ProcessCORSRequest(
                    m_Context->GetRequest(), m_Context->GetResponse()) ?
                    0 : ProcessRequest(*m_Context);
                GetDiagContext().SetAppState(eDiagAppState_RequestEnd);
                m_Context->GetResponse().Finalize();
                if (result != 0) {
                    SetHTTPStatus(500);
                    m_ErrorStatus = true;
                } else {
                    if (m_Cache.get()) {
                        m_Context->GetResponse().Flush();
                        if (m_IsResultReady) {
                            if(caching_needed)
                                SaveResultToCache(m_Context->GetRequest(), result_copy);
                            else {
                                auto_ptr<CCgiRequest> request(GetSavedRequest(m_RID));
                                if (request.get()) 
                                    SaveResultToCache(*request, result_copy);
                            }
                        } else if (caching_needed) {
                            SaveRequest(m_RID, m_Context->GetRequest());
                        }
                    }
                }
            }
        }
        catch (CCgiException& e) {
            if ( x_DoneHeadRequest() ) {
                // Ignore errors after HEAD request has been finished.
                GetDiagContext().SetAppState(eDiagAppState_RequestEnd);
            }
            else {
                if ( e.GetStatusCode() <  CCgiException::e200_Ok  ||
                     e.GetStatusCode() >= CCgiException::e400_BadRequest ) {
                    throw;
                }
                GetDiagContext().SetAppState(eDiagAppState_RequestEnd);
                // If for some reason exception with status 2xx was thrown,
                // set the result to 0, update HTTP status and continue.
                m_Context->GetResponse().SetStatus(e.GetStatusCode(),
                                                   e.GetStatusMessage());
            }
            result = 0;
        }

#ifdef NCBI_OS_MSWIN
        // Logging - on MSWin this must be done before flushing the output.
        if ( is_stat_log  &&  !skip_stat_log ) {
            stat->Reset(start_time, result);
            stat->Submit(stat->Compose());
        }
        is_stat_log = false;
#endif

        _TRACE("CCgiApplication::Run: flushing");
        m_Context->GetResponse().Flush();
        _TRACE("CCgiApplication::Run: return " << result);
        x_OnEvent(result == 0 ? eSuccess : eError, result);
        x_OnEvent(eExit, result);
    }
    catch (exception& e) {
        GetDiagContext().SetAppState(eDiagAppState_RequestEnd);
        if ( x_DoneHeadRequest() ) {
            // Ignore errors after HEAD request has been finished.
            result = 0;
            x_OnEvent(eSuccess, result);
        }
        else {
            // Call the exception handler and set the CGI exit code
            result = OnException(e, NcbiCout);
            x_OnEvent(eException, result);

            // Logging
            {{
                string msg = "(CGI) CCgiApplication::ProcessRequest() failed: ";
                msg += e.what();

                if ( is_stat_log ) {
                    stat->Reset(start_time, result, &e);
                    msg = stat->Compose();
                    stat->Submit(msg);
                    skip_stat_log = true; // Don't print the same message again
                }
            }}

            // Exception reporting. Use different severity for broken connection.
            ios_base::failure* fex = dynamic_cast<ios_base::failure*>(&e);
            CNcbiOstream* os = m_Context.get() ? m_Context->GetResponse().GetOutput() : NULL;
            if ((fex  &&  os  &&  !os->good())  ||  m_OutputBroken) {
                if ( !TClientConnIntOk::GetDefault() ) {
                    ERR_POST_X(13, Severity(TClientConnIntSeverity::GetDefault()) <<
                        "Connection interrupted");
                }
            }
            else {
                NCBI_REPORT_EXCEPTION_X(13, "(CGI) CCgiApplication::Run", e);
            }
        }
    }

#ifndef NCBI_OS_MSWIN
    // Logging
    if ( is_stat_log  &&  !skip_stat_log ) {
        stat->Reset(start_time, result);
        stat->Submit(stat->Compose());
    }
#endif

    x_OnEvent(eEndRequest, 120);
    x_OnEvent(eExit, result);

    if (m_Context.get()) {
        m_Context->GetResponse().SetOutput(NULL);
    }
    return result;
}
コード例 #26
0
ファイル: libopenrave_c.cpp プロジェクト: ahundt/openrave
void ORCEnvironmentRemove(void* env, void* pinterface)
{
    GetEnvironment(env)->Remove(GetInterface(pinterface));
}
コード例 #27
0
ファイル: libopenrave_c.cpp プロジェクト: ahundt/openrave
bool ORCEnvironmentLoad(void* env, const char* filename)
{
    return GetEnvironment(env)->Load(filename);
}
コード例 #28
0
/* virtual */ OP_STATUS
DOM_ApplicationCacheProgressEvent::DefaultAction(BOOL cancelled)
{
	if (cancelled || prevent_default)
		return OpStatus::OK;

	WindowCommander *wnd_commander = g_application_cache_manager->GetWindowCommanderFromCacheHost(GetEnvironment());
	OpApplicationCacheListener *listener  = NULL;

	if (wnd_commander && (listener = wnd_commander->GetApplicationCacheListener()))
		listener->OnAppCacheProgress(wnd_commander);

	return OpStatus::OK;
}
コード例 #29
0
/* virtual */ OP_STATUS
DOM_ApplicationCacheEvent::DefaultAction(BOOL cancelled)
{
	if (cancelled || prevent_default)
		return OpStatus::OK;

	WindowCommander *wnd_commander = g_application_cache_manager->GetWindowCommanderFromCacheHost(GetEnvironment());
	OpApplicationCacheListener *listener  = NULL;
	if (wnd_commander && (listener = wnd_commander->GetApplicationCacheListener()))
	{
		switch (known_type)
		{
			case APPCACHECHECKING:
				listener->OnAppCacheChecking(wnd_commander);
				break;
			case APPCACHEDOWNLOADING:
				listener->OnAppCacheDownloading(wnd_commander);
				break;
			case APPCACHECACHED:
				listener->OnAppCacheCached(wnd_commander);
				break;
			case APPCACHEUPDATEREADY:
				listener->OnAppCacheUpdateReady(wnd_commander);
				break;
			case APPCACHENOUPDATE:
				listener->OnAppCacheNoUpdate(wnd_commander);
				break;
			case APPCACHEOBSOLETE:
				listener->OnAppCacheObsolete(wnd_commander);
				break;
			case ONERROR:
				listener->OnAppCacheError(wnd_commander);
				break;
			default:
				OP_ASSERT(!"Unexpected event type!");
		}
	}

	return OpStatus::OK;
}
コード例 #30
0
ファイル: domselection.cpp プロジェクト: prestocore/browser
OP_STATUS
DOM_WindowSelection::UpdateRangeFromSelection()
{
	range = NULL;
	UpdateFromRangeAutoLocker locker(lock_updates_from_range);
	if (HTML_Document *htmldoc = owner_document->GetHTML_Document())
	{
		OP_STATUS oom = OpStatus::OK;
		SelectionBoundaryPoint anchorPoint, focusPoint;
		if (htmldoc->GetSelection(anchorPoint, focusPoint))
		{
			RETURN_IF_ERROR(DOM_Range::Make(range, owner_document));
			range->selection = this;
			unsigned anchorOffset = anchorPoint.GetElementCharacterOffset();
			unsigned focusOffset = focusPoint.GetElementCharacterOffset();
			HTML_Element *anchorElement = anchorPoint.GetElement();
			HTML_Element *focusElement = focusPoint.GetElement();

			RETURN_IF_ERROR(MoveOutOfGeneratedContent(anchorElement, anchorOffset));
			RETURN_IF_ERROR(MoveOutOfGeneratedContent(focusElement, focusOffset));

			MoveOutToTextGroup(anchorElement, anchorOffset);
			MoveOutToTextGroup(focusElement, focusOffset);

			DOM_Range::BoundaryPoint anchorBP;
			DOM_Range::BoundaryPoint focusBP;
			DOM_EnvironmentImpl *environment = GetEnvironment();

			RETURN_IF_ERROR(DOM_SetBoundaryPoint(environment, owner_document, anchorBP, anchorElement, anchorOffset, FALSE));
			RETURN_IF_ERROR(DOM_SetBoundaryPoint(environment, owner_document, focusBP, focusElement, focusOffset, TRUE));

			DOM_Object::DOMException dummy_exception = DOM_Object::DOMEXCEPTION_NO_ERR;
			if (anchorElement == focusElement && anchorBP.offset <= focusBP.offset || anchorElement->Precedes(focusElement))
			{
				oom = range->SetStartAndEnd(anchorBP, focusBP, dummy_exception);
				forwards = TRUE;
			}
			else
			{
				oom = range->SetStartAndEnd(focusBP, anchorBP, dummy_exception);
				forwards = FALSE;
			}
		}
		else
		{
			HTML_Element* caret_elm = htmldoc->GetElementWithSelection();
			if (caret_elm)
			{
				RETURN_IF_ERROR(DOM_Range::Make(range, owner_document));
				range->selection = this;

				// Put an empty DOM_Range at the caret. And where is the caret?
				DOM_Range::BoundaryPoint caretBP;
				RETURN_IF_ERROR(GetEnvironment()->ConstructNode(caretBP.node, caret_elm, owner_document));

				DOM_Object::DOMException dummy_exception = DOM_Object::DOMEXCEPTION_NO_ERR;
				oom = range->SetStartAndEnd(caretBP, caretBP, dummy_exception);
			}
		}
		return oom;
	}

	return OpStatus::OK;
}