Пример #1
0
void CGeorgesEditDoc::OnEditUndo() 
{
	if (!_UndoBuffer.empty ())
	{
		// Get an action
		IAction *action = _UndoBuffer.back ();
		_UndoBuffer.pop_back ();

		// Undo it
		bool modified;
		action->doAction (*this, false, modified, false);

		// Put in the redo list
		_RedoBuffer.push_back (action);

		CMDIFrameWnd* pMainWnd = (CMDIFrameWnd*)AfxGetMainWnd();

		// Get the active MDI child window.
		CMDIChildWnd* pChild = (CMDIChildWnd*)pMainWnd->MDIGetActive();
		pChild->RecalcLayout();
		pChild->UpdateWindow();

		_UndoModify--;
		if ( (_UndoModify == 0) && IsModified () )
		{
			setModifiedState (false);
		}
		else if ( (_UndoModify != 0) && !IsModified () )
		{
			setModifiedState (true);
		}
	}
}
Пример #2
0
void CGeorgesEditDoc::OnEditRedo() 
{
	if (!_RedoBuffer.empty ())
	{
		// Get an action
		IAction *action = _RedoBuffer.back ();
		_RedoBuffer.pop_back ();

		// Undo it
		bool modified;
		action->doAction (*this, true, modified, false);

		// Put in the redo list
		_UndoBuffer.push_back (action);

		((CMainFrame*)(theApp.m_pMainWnd))->RecalcLayout ();

		_UndoModify++;
		if ( (_UndoModify == 0) && IsModified () )
		{
			setModifiedState (false);
		}
		else if ( (_UndoModify != 0) && !IsModified () )
		{
			setModifiedState (true);
		}
	}
}
Пример #3
0
void ActionList::LoadFromS11nBlock(const ActionListS11nBlock& block)
{
	block.guid.GetValueIfExists(m_guid);

	if (block.name.Exists())
		m_name = pfc::stringcvt::string_wide_from_utf8(block.name.GetValue()).get_ptr();

	if (block.actions.Exists())
	{
		for (int i = 0; i < block.actions.GetSize(); ++i)
		{
			const ActionS11nBlock& actionBlock = block.actions.GetAt(i);

			// actionGUID is a required field, unnecessary to check if it exists.
			IAction* pPrototype = ServiceManager::Instance().GetActionPrototypesManager().
				GetPrototypeByGUID(actionBlock.actionGUID.GetValue());

			if (!pPrototype)
				continue;

			std::auto_ptr<IAction> pAction(pPrototype->Clone());
			pAction->LoadFromS11nBlock(actionBlock);

			m_actions.push_back(pAction);
		}
	}
}
Пример #4
0
	void IToolBar::actionTriggeredSlot(bool checked)
	{
		IAction* action = dynamic_cast<IAction*> (sender());
		if(action)
		{
			action->execute();
		}					
	}
Пример #5
0
int main()
{
   std::cout << "action hello" << std::endl;
   Printer p;
   boost::function<void(std::string)> f = boost::bind(&Printer::printString, &p, _1);

   f(std::string("hello"));

   //boost::function<void(std::string)> f = boost::bind(&Printer::printString, &p);
   IAction* action = new TSingleArgAction<std::string>(ActionType::PRINT_STRING, f);

   TSingleArg<std::string> args("hello");
   action->call(args);
}
Пример #6
0
    bool NextStep() {
        if(actions_.Count() == 0) return false;
        List<Point>* prevPoints = points_[points_.Count() - 1];

        // Check if the next action should be executed.
        if(currentStep_ == currentAction_->Steps()) {
            // Skip over all connected actions.
            size_t nextPosition = currentPosition_ + 1;
            while(nextPosition < actions_.Count() && actions_[nextPosition]->WithPrevious()) {
                nextPosition++;
            }

            size_t i = nextPosition + 1;
            while((i < actions_.Count()) && actions_[i]->WithPrevious()) {
                actions_[i]->Initialize(*prevPoints);
                i++;
            }

            if(nextPosition < actions_.Count()) {
                // Advance to the next action.
                currentAction_ = actions_[nextPosition];
                currentAction_->Initialize(*prevPoints);
                currentPosition_ = nextPosition;
                currentStep_ = 0;
            }
            else {
                // All actions have been executed.
                return false; 
            }
        }

        // Compute the next state of the shape.
        // The generated points depend directly on the previous ones.
        List<Point>* newPoints = new List<Point>(*prevPoints);
        points_.Add(newPoints);

        // Apply to the points the current action and all actions liked with it.
        currentAction_->Execute(currentStep_, *newPoints);

        for(size_t i = currentPosition_ + 1; i < actions_.Count(); i++) {
            if(actions_[i]->WithPrevious()) {
                actions_[i]->Execute(currentStep_, *newPoints);
            }
            else break;
        }

        currentStep_++;
        return true;
    }
Пример #7
0
void QtMenu::destroyQAction(IAction& action)
{
	auto it = actions_.find(&action);
	if (it != actions_.end())
	{
		const std::string groupID(action.group());
		if (!groupID.empty())
		{
			auto groupItr = groups_.find(groupID);
			if (groupItr != groups_.end())
			{
				groupItr->second->removeAction(it->second.data());
				if (groupItr->second->actions().empty())
				{
					groups_.erase(groupItr);
				}
			}
		}
		actions_.erase(it);
	}

	auto findIt = connections_.find(&action);
	if (findIt != connections_.end())
	{
		connections_.erase(findIt);
	}
}
Пример #8
0
void QtMenuBar::addAction(IAction& action, const char* path)
{
	auto qAction = getQAction(action);
	if (qAction == nullptr)
	{
		qAction = createQAction(action);
	}
	assert(qAction != nullptr);

	path = relativePath(path);
	if (path == nullptr || strlen(path) == 0)
	{
		path = action.text();
	}

	auto tok = strchr(path, '.');
	auto menuPath = tok != nullptr ? QString::fromUtf8(path, tok - path) : path;
	QMenu* menu = qMenuBar_.findChild<QMenu*>(menuPath, Qt::FindDirectChildrenOnly);
	if (menu == nullptr)
	{
		menu = qMenuBar_.addMenu(menuPath);
		menu->setObjectName(menuPath);
	}
	path = tok != nullptr ? tok + 1 : nullptr;

	QtMenu::addMenuAction(*menu, *qAction, path);
	qMenuBar_.repaint();
}
Пример #9
0
void TestStoryboard() {
    List<Point> points;
    points.Add(Point(0, 0, 0));
    points.Add(Point(1, 1, 1));
    points.Add(Point(2, 2, 2));
    points.Add(Point(3, 3, 3));

    Shape shape(points);
    IAction* a = new TranslateAction(3, 3 , 3);
    IAction* b = new TranslateAction(2, 2 , 2);
    IAction* c = new TranslateAction(5, 5 , 5);
    a->SetSteps(3);
    b->SetSteps(3);
    c->SetSteps(4);
    b->SetWithPrevious(true);

    Storyboard sb;
    sb.Actions().Add(a);
    sb.Actions().Add(b);
    sb.Actions().Add(c);
    sb.SetShapeObject(shape);

    assert(sb.TotalSteps() == 10);
    assert(sb.CurrentAction() == NULL);

    sb.Play();
    for(size_t i = 0; i < sb.TotalSteps(); i++) {
        sb.NextStep();
    }
}
Пример #10
0
void Console::execute(const string& line) {
  vector<string> parts = StringUtil::split(line, ' ');
  if(parts.size() > 0) {
    string command = parts[0];
    IAction* action = basicLanguage[command];
    if(action) {
      string param;
      if(parts.size() > 1) {
        param = parts[1];
      }
      else {
        param = "";
      }

      action->execute(param);
    }
  }
}
Пример #11
0
  void ActionGroup::DoActions(IEntity* theEntity)
  {
    // Make sure clear all of our IAction classes
    std::map<const typeActionID, IAction*>::iterator anActionIter;

    // Start at the beginning of the list of IAction classes
    anActionIter = mActive.begin();
    while(anActionIter != mActive.end())
    {
      // Get the IAction to execute
      IAction* anAction = anActionIter->second;

      // Move on to the next iterator
      anActionIter++;

      // Call the IAction DoAction method and provide theEntity to it
      anAction->DoAction(theEntity);
    }
  }
void CInteractiveObjectRegistry::ApplyInteractionToObject(IEntity *pEntity, const TagID interactionTypeTag, const int interactionIndex) const
{
	if (m_pDatabaseObject && m_pControllerDef)
	{
		IMannequin &mannequinSys = gEnv->pGame->GetIGameFramework()->GetMannequinInterface();
		SAnimationContext animContext(*m_pControllerDef);

		IActionController *pActionController = mannequinSys.CreateActionController(pEntity, animContext);

		int scopeContextID = m_pControllerDef->m_scopeContexts.Find("SlaveObject");
		pActionController->SetScopeContext(scopeContextID, *pEntity, pEntity->GetCharacter(0), m_pDatabaseObject);
		TagState fragTags = TAG_STATE_EMPTY;
		const CTagDefinition *pTagDef = m_pControllerDef->GetFragmentTagDef(m_interactFragID);
		if (pTagDef)
		{
			pTagDef->Set(fragTags, interactionTypeTag, true);
		}
		IAction *pAction = new TAction<SAnimationContext>(0, m_interactFragID, fragTags);
		pAction->SetOptionIdx(interactionIndex);
		pActionController->Queue(pAction);

		// Set the time increments to non-zero to force the ActionController::Update() to drive the animation to the end.
		// When time increment is zero, animation position will not update. This will be changed to a simpler process by Tom Berry at some point.
		const uint32 totalScopes = pActionController->GetTotalScopes();
		for(uint32 s=0; s<totalScopes; ++s)
		{
			pActionController->GetScope(s)->IncrementTime(0.001f);
		}
		pActionController->Update(1000.0f);
		// "false" here leaves the anim on the transition queue in the animation system so it isn't cleared on pActionController->Release().
		pActionController->ClearScopeContext(scopeContextID, false);

		pActionController->Release();

		CRecordingSystem* pRecordingSystem = g_pGame->GetRecordingSystem();
		if (pRecordingSystem)
		{
			pRecordingSystem->OnInteractiveObjectFinishedUse(pEntity->GetId(), interactionTypeTag, interactionIndex);
		}

	}
}
Пример #13
0
EPriorityComparison CReplayObjectAction::ComparePriority( const IAction &actionCurrent ) const
{
	if (m_trumpsPrevious)
	{
		return ((IAction::Installed == actionCurrent.GetStatus() && IAction::Installing & ~actionCurrent.GetFlags()) ? Higher : BaseClass::ComparePriority(actionCurrent));
	}
	else
	{
		return Equal;
	}
}
Пример #14
0
void LayoutManager::addAction(IAction& action)
{
	actions_.push_back(&action);

	auto window = getWindow(action.windowId());
	if (window == nullptr)
	{
		return;
	}

	addAction(actions_.back(), *window);
}
Пример #15
0
void ActionChain::update(Time delta) {
    if(m_isAlive) {
        // Store currently used action for convenience
        IAction* action = m_actions[m_currentIndex];

        // Update the action
        action->update(delta);

        // Check if action is finished
        if(action->isFinished()) {
            action->close();

            // Iterate to the next action
            m_currentIndex++;

            // If the action was last one in the chain
            if(m_currentIndex == m_actions.size()) {
                // If the chain is looping, start over
                if(m_isLooping) {
                    for(IAction* action : m_actions) {
                        action->reset();
                    }

                    m_currentIndex = 0;

                    // Initialize first action
                    m_actions[m_currentIndex]->init();
                }
                // Otherwise destroy the chain
                else {
                    m_isAlive = false;
                }
            }
            else {
                // Initialize next action
                m_actions[m_currentIndex]->init();
            }
        }
    }
}
Пример #16
0
void QtMenuBar::removeAction(IAction& action)
{
	auto qAction = getQAction(action);
	if (qAction == nullptr)
	{
		NGT_ERROR_MSG("Target action '%s' '%s' does not exist\n", action.text(),
		              StringUtils::join(action.paths(), ';').c_str());
		return;
	}

	auto menus = qMenuBar_.findChildren<QMenu*>(QString(), Qt::FindDirectChildrenOnly);
	for (auto& menu : menus)
	{
		QtMenu::removeMenuAction(*menu, *qAction);
		if (menu->isEmpty())
		{
			delete menu;
		}
	}

	destroyQAction(action);
}
Пример #17
0
    void Play() {
        if(actions_.Count() == 0) return;

        currentAction_ = actions_[0];
        currentPosition_ = 0;
        currentStep_ = 0;

        List<Point> *firstPoints = new List<Point>(shape_->Points());
        points_.Add(firstPoints);

        // Initialize the start action and the ones connected to it.
        currentAction_->Initialize(*firstPoints);

        for(size_t i = 1; i < actions_.Count(); i++) {
            if(actions_[i]->WithPrevious() == false) return;
            actions_[i]->Initialize(*firstPoints);
        }
    }
Пример #18
0
void CActionList::Update(CCircuitAI* circuit)
{
	std::list<IAction*>::iterator itAction = actions.begin();
	while (itAction != actions.end()) {
		IAction* action = *itAction;
		if (action->IsActive()) {
			action->Update(circuit);
		}

		if (action->IsBlocking()) {
			break;
		}

		if (action->IsFinished()) {
			action->OnEnd();
			itAction = Remove(itAction);
		} else {
			++itAction;
		}
	}
}
Пример #19
0
void enumerateTasksForFolder(std::string path, QueryData& results) {
  void* vpService = nullptr;
  auto ret = CoCreateInstance(CLSID_TaskScheduler,
                              nullptr,
                              CLSCTX_INPROC_SERVER,
                              IID_ITaskService,
                              &vpService);
  if (FAILED(ret)) {
    VLOG(1) << "Failed to create COM instance " << ret;
    return;
  }

  auto pService = static_cast<ITaskService*>(vpService);
  ret =
      pService->Connect(_variant_t(), _variant_t(), _variant_t(), _variant_t());
  if (FAILED(ret)) {
    VLOG(1) << "Failed to connect to TaskService " << ret;
    pService->Release();
    return;
  }

  ITaskFolder* pRootFolder = nullptr;
  auto widePath = stringToWstring(path);
  ret = pService->GetFolder(BSTR(widePath.c_str()), &pRootFolder);
  pService->Release();
  if (FAILED(ret)) {
    VLOG(1) << "Failed to get root task folder " << ret;
    return;
  }

  IRegisteredTaskCollection* pTaskCollection = nullptr;
  ret = pRootFolder->GetTasks(TASK_ENUM_HIDDEN, &pTaskCollection);
  pRootFolder->Release();
  if (FAILED(ret)) {
    VLOG(1) << "Failed to get task collection for root folder " << ret;
    return;
  }

  long numTasks = 0;
  pTaskCollection->get_Count(&numTasks);
  for (size_t i = 0; i < numTasks; i++) {
    IRegisteredTask* pRegisteredTask = nullptr;
    // Collections are 1-based lists
    ret = pTaskCollection->get_Item(_variant_t(i + 1), &pRegisteredTask);
    if (FAILED(ret)) {
      VLOG(1) << "Failed to process task";
      continue;
    }

    Row r;
    BSTR taskName;
    ret = pRegisteredTask->get_Name(&taskName);
    std::wstring wTaskName(taskName, SysStringLen(taskName));
    r["name"] = ret == S_OK ? SQL_TEXT(wstringToString(wTaskName.c_str())) : "";

    VARIANT_BOOL enabled = false;
    pRegisteredTask->get_Enabled(&enabled);
    r["enabled"] = enabled ? INTEGER(1) : INTEGER(0);

    TASK_STATE taskState;
    pRegisteredTask->get_State(&taskState);
    r["state"] = kStateMap.count(taskState) > 0
                     ? kStateMap.at(taskState)
                     : kStateMap.at(TASK_STATE_UNKNOWN);

    BSTR taskPath;
    ret = pRegisteredTask->get_Path(&taskPath);
    std::wstring wTaskPath(taskPath, SysStringLen(taskPath));
    r["path"] = ret == S_OK ? wstringToString(wTaskPath.c_str()) : "";

    VARIANT_BOOL hidden = false;
    pRegisteredTask->get_Enabled(&hidden);
    r["hidden"] = hidden ? INTEGER(1) : INTEGER(0);

    HRESULT lastTaskRun = E_FAIL;
    pRegisteredTask->get_LastTaskResult(&lastTaskRun);
    _com_error err(lastTaskRun);
    r["last_run_message"] = err.ErrorMessage();
    r["last_run_code"] = INTEGER(lastTaskRun);

    // We conver the COM Date type to a unix epoch timestamp
    DATE dRunTime;
    SYSTEMTIME st;
    FILETIME ft;
    FILETIME locFt;

    pRegisteredTask->get_LastRunTime(&dRunTime);
    VariantTimeToSystemTime(dRunTime, &st);
    SystemTimeToFileTime(&st, &ft);
    LocalFileTimeToFileTime(&ft, &locFt);
    r["last_run_time"] = INTEGER(filetimeToUnixtime(locFt));

    pRegisteredTask->get_NextRunTime(&dRunTime);
    VariantTimeToSystemTime(dRunTime, &st);
    SystemTimeToFileTime(&st, &ft);
    LocalFileTimeToFileTime(&ft, &locFt);
    r["next_run_time"] = INTEGER(filetimeToUnixtime(locFt));

    ITaskDefinition* taskDef = nullptr;
    IActionCollection* tActionCollection = nullptr;
    pRegisteredTask->get_Definition(&taskDef);
    if (taskDef != nullptr) {
      taskDef->get_Actions(&tActionCollection);
    }

    long actionCount = 0;
    if (tActionCollection != nullptr) {
      tActionCollection->get_Count(&actionCount);
    }
    std::vector<std::string> actions;

    // Task collections are 1-indexed
    for (auto j = 1; j <= actionCount; j++) {
      IAction* act = nullptr;
      IExecAction* execAction = nullptr;
      tActionCollection->get_Item(j, &act);
      if (act == nullptr) {
        continue;
      }
      act->QueryInterface(IID_IExecAction,
                          reinterpret_cast<void**>(&execAction));
      if (execAction == nullptr) {
        continue;
      }

      BSTR taskExecPath;
      execAction->get_Path(&taskExecPath);
      std::wstring wTaskExecPath(taskExecPath, SysStringLen(taskExecPath));

      BSTR taskExecArgs;
      execAction->get_Arguments(&taskExecArgs);
      std::wstring wTaskExecArgs(taskExecArgs, SysStringLen(taskExecArgs));

      BSTR taskExecRoot;
      execAction->get_WorkingDirectory(&taskExecRoot);
      std::wstring wTaskExecRoot(taskExecRoot, SysStringLen(taskExecRoot));

      auto full = wTaskExecRoot + L" " + wTaskExecPath + L" " + wTaskExecArgs;
      actions.push_back(wstringToString(full.c_str()));
      act->Release();
    }
    if (tActionCollection != nullptr) {
      tActionCollection->Release();
    }
    if (taskDef != nullptr) {
      taskDef->Release();
    }
    r["action"] = !actions.empty() ? osquery::join(actions, ",") : "";

    results.push_back(r);
    pRegisteredTask->Release();
  }
  pTaskCollection->Release();
}
Пример #20
0
void CAxis::Update(short currentValue)
{
	// This whole thing goes in a do/while, so it happens once, but we can bail out of the block
	// and perform our cleanup code at the end.
	do
	{
		// Reset the binary flag if we've gotten back inside the threshold bounds.
		if(_lastValue < _threshold && _lastValue > (_threshold * -1))
		{
			if(!_triggerBinary && _centerMotion && _gestures && _processor->_gestures.size() != 0)
			{
				_processor->newMotion(new CMotion(_centerMotion));
			}
			_triggerBinary = true;
		}

		IAction* actionToPerform = NULL;
		// Determine if we're beyond the threshold, and if so, which action to take
		if(currentValue > _threshold )
		{
			if(_gestures && !_triggerBinary)
			{
				if(::GetTickCount() - _lastGestureSent > 1000)
				{					
					_processor->newMotion(new CMotion(_posMotion));
					_lastGestureSent = ::GetTickCount();
					_triggerBinary = false;
					continue;
				}
			}
			if(_gestures && _triggerBinary)
			{
				_processor->newMotion(new CMotion(_posMotion));
				_lastGestureSent = ::GetTickCount();
				_triggerBinary = false;
				continue;
			}
			else
				actionToPerform = _positiveAction;
		}
		else if (currentValue < (_threshold *-1))
		{
			if(_gestures && !_triggerBinary)
			{
				if(::GetTickCount() - _lastGestureSent > 1000)
				{					
					_processor->newMotion(new CMotion(_negMotion));
					_lastGestureSent = ::GetTickCount();
					_triggerBinary = false;
					continue;
				}
			}
			if(_gestures && _triggerBinary)
			{
				_processor->newMotion(new CMotion(_negMotion));				
				_lastGestureSent = ::GetTickCount();
				_triggerBinary = false;
				continue;
			}
			else
				actionToPerform = _negativeAction;
		}

		// Should bail out of the do/while
		if(actionToPerform == NULL)
			continue;

		if(_pulse)
		{
			// Determine the frequency
			int currentMotionRange = 512 - _threshold;
			double multiplier = currentValue * (1.0 / currentMotionRange);
			// Normalize the multiplier to a positive value
			multiplier = multiplier < 0 ? multiplier * -1.0 : multiplier;
			int currentFrequencyRange = _maximumPulseRate - _minimumPulseRate;
			double frequency = (currentFrequencyRange * multiplier) + _minimumPulseRate;
			unsigned int requiredTicksSinceLast = 1000 / frequency;
			DWORD currentTickCount = GetTickCount();
			DWORD tickDelta = currentTickCount - _lastPulseExecute;
			if(requiredTicksSinceLast < tickDelta)
			{
				actionToPerform->Execute();
				_lastPulseExecute = currentTickCount;
			}
		}
		else if(_triggerBinary)
		{
			actionToPerform->Execute();
			_triggerBinary = false;
		}
	} while(false);

	_lastValue = currentValue;
}
Пример #21
0
QSharedPointer<QAction> QtMenu::createSharedQAction(IAction& action)
{
	auto qAction = getSharedQAction(action);
	if (qAction)
	{
		return qAction;
	}

	qAction.reset(new QForwardingAction(action.text(), QApplication::instance()), &QObject::deleteLater);
	sharedQActions_[&action] = qAction;

	qAction->setProperty("order", action.order());
	qAction->setEnabled(action.enabled());
	qAction->setVisible(action.visible());

	if (action.isSeparator())
	{
		qAction->setSeparator(true);
	}
	else
	{
		std::vector<QIcon> qIcons;
		auto icons = StringUtils::split(std::string(action.icon()), '|');
		for(auto& icon : icons)
		{			
			StringUtils::trim_string(icon);
			qIcons.push_back(QtMenu_Locals::generateIcon(icon.c_str()));
		}

		if(!qIcons.empty())
		{
			qAction->setIcon(qIcons[0]);
		}

		qAction->setShortcut(QKeySequence(action.shortcut()));

		if (action.isCheckable())
		{
			qAction->setCheckable(true);
			qAction->setChecked(action.checked());
		}

		QObject::connect(qAction.data(), &QAction::triggered, [&action]() {
			if (!action.enabled())
			{
				return;
			}
			action.execute();
		});

		connections_[&action] = action.signalShortcutChanged.connect([qAction](const char* shortcut) {
			TF_ASSERT(qAction != nullptr);
			qAction->setShortcut(QKeySequence(shortcut));
		});

		connections_[&action] = action.signalTextChanged.connect([qAction](const char* text) {
			TF_ASSERT(qAction != nullptr);
			qAction->setText(text);
		});

		connections_[&action] = action.signalVisibilityChanged.connect([qAction](bool visible) {
			TF_ASSERT(qAction != nullptr);
			qAction->setVisible(visible);
		});

		connections_[&action] = action.signalIconChanged.connect([qAction, qIcons](int index) {
			TF_ASSERT(qAction != nullptr);
			if(index >= 0 && index < (int)qIcons.size())
			{
				qAction->setIcon(qIcons[index]);
			}
		});

		const std::string groupID(action.group());
		if (!groupID.empty())
		{
			auto itr = groups_.find(groupID);
			if (itr == groups_.end())
			{
				groups_[groupID].reset(new QActionGroup(&menu_));
			}

			groups_.at(groupID)->addAction(qAction.data());
			TF_ASSERT(qAction->actionGroup());
		}
	}

	return qAction;
}
int __cdecl wmain()
{
    //  ------------------------------------------------------
    //  Initialize COM.
    HRESULT hr = CoInitializeEx(NULL, COINIT_MULTITHREADED);
    if( FAILED(hr) )
    {
        printf("\nCoInitializeEx failed: %x", hr );
        return 1;
    }

    //  Set general COM security levels.
    hr = CoInitializeSecurity(
        NULL,
        -1,
        NULL,
        NULL,
        RPC_C_AUTHN_LEVEL_PKT_PRIVACY,
        RPC_C_IMP_LEVEL_IMPERSONATE,
        NULL,
        0,
        NULL);

    if( FAILED(hr) )
    {
        printf("\nCoInitializeSecurity failed: %x", hr );
        CoUninitialize();
        return 1;
    }

    //  ------------------------------------------------------
    //  Create a name for the task.
    LPCWSTR wszTaskName = L"Event Trigger Test Task";


    //  ------------------------------------------------------
    //  Create an instance of the Task Service. 
    ITaskService *pService = NULL;
    hr = CoCreateInstance( CLSID_TaskScheduler,
                           NULL,
                           CLSCTX_INPROC_SERVER,
                           IID_ITaskService,
                           (void**)&pService );  
    if (FAILED(hr))
    {
          printf("\nFailed to CoCreate an instance of the TaskService class: %x", hr);
          CoUninitialize();
          return 1;
    }
        
    //  Connect to the task service.
    hr = pService->Connect(_variant_t(), _variant_t(),
        _variant_t(), _variant_t());
    if( FAILED(hr) )
    {
        printf("\nITaskService::Connect failed: %x", hr );
        pService->Release();
        CoUninitialize();
        return 1;
    }

    //  ------------------------------------------------------
    //  Get the pointer to the root task folder.  This folder will hold the
    //  new task that is registered.
    ITaskFolder *pRootFolder = NULL;
    hr = pService->GetFolder( _bstr_t( L"\\") , &pRootFolder );
    if( FAILED(hr) )
    {
        printf("\nCannot get Root Folder pointer: %x", hr );
        pService->Release();
        CoUninitialize();
        return 1;
    }
    
    // If the same task exists, remove it.
    pRootFolder->DeleteTask( _bstr_t( wszTaskName), 0  );
    
    //  Create the task builder object to create the task.
    ITaskDefinition *pTask = NULL;
    hr = pService->NewTask( 0, &pTask );
    
    pService->Release();  // COM clean up.  Pointer is no longer used.
    if (FAILED(hr))
    {
        printf("\nFailed to create an instance of the task: %x", hr);
        pRootFolder->Release();
        CoUninitialize();
        return 1;
    }
        
    //  ------------------------------------------------------
    //  Get the registration info for setting the identification.
    IRegistrationInfo *pRegInfo= NULL;
    hr = pTask->get_RegistrationInfo( &pRegInfo );
    if( FAILED(hr) )
    {
        printf("\nCannot get identification pointer: %x", hr );
        pRootFolder->Release();
        pTask->Release();
        CoUninitialize();
        return 1;
    }
    
    hr = pRegInfo->put_Author( L"Author Name" );
    pRegInfo->Release();  // COM clean up.  Pointer is no longer used.
    if( FAILED(hr) )
    {
        printf("\nCannot put identification info: %x", hr );
        pRootFolder->Release();
        pTask->Release();
        CoUninitialize();
        return 1;
    }

    //  ------------------------------------------------------
    //  Create the settings for the task
    ITaskSettings *pSettings = NULL;
    hr = pTask->get_Settings( &pSettings );
    if( FAILED(hr) )
    {
        printf("\nCannot get settings pointer: %x", hr );
        pRootFolder->Release();
        pTask->Release();
        CoUninitialize();
        return 1;
    }
    
    //  Set setting values for the task.  
    hr = pSettings->put_StartWhenAvailable(VARIANT_BOOL(true));
    pSettings->Release();  // COM clean up.  Pointer is no longer used.
    if( FAILED(hr) )
    {
        printf("\nCannot put setting info: %x", hr );
        pRootFolder->Release();
        pTask->Release();
        CoUninitialize();
        return 1;
    }

    //  ------------------------------------------------------
    //  Get the trigger collection to insert the event trigger.
    ITriggerCollection *pTriggerCollection = NULL;
    hr = pTask->get_Triggers( &pTriggerCollection );
    if( FAILED(hr) )
    {
        printf("\nCannot get trigger collection: %x", hr );
        pRootFolder->Release();
        pTask->Release();
        CoUninitialize();
        return 1;
    }
    
    //  Create the event trigger for the task.
    ITrigger *pTrigger = NULL;
    
    hr = pTriggerCollection->Create( TASK_TRIGGER_EVENT, &pTrigger );
    pTriggerCollection->Release();
    if( FAILED(hr) )
    {
        printf("\nCannot create the trigger: %x", hr );
        pRootFolder->Release();
        pTask->Release();
        CoUninitialize();
        return 1;
    }     
    
    IEventTrigger *pEventTrigger = NULL;
    hr = pTrigger->QueryInterface( 
        IID_IEventTrigger, (void**) &pEventTrigger );
    pTrigger->Release();
    if( FAILED(hr) )
    {
        printf("\nQueryInterface call on IEventTrigger failed: %x", hr );
        pRootFolder->Release();
        pTask->Release();
        CoUninitialize();
        return 1;
    } 
    
    hr = pEventTrigger->put_Id( _bstr_t( L"Trigger1" ) );
    if( FAILED(hr) )
       printf("\nCannot put the trigger ID: %x", hr);

    //  Set the task to start at a certain time. The time 
    //  format should be YYYY-MM-DDTHH:MM:SS(+-)(timezone).
    //  For example, the start boundary below
    //  is January 1st 2005 at 12:05
    hr = pEventTrigger->put_StartBoundary( _bstr_t(L"2005-01-01T12:05:00") );
    if( FAILED(hr) )
        printf("\nCannot put the trigger start boundary: %x", hr);

    hr = pEventTrigger->put_EndBoundary( _bstr_t(L"2015-05-02T08:00:00") );
    if( FAILED(hr) )
        printf("\nCannot put the trigger end boundary: %x", hr);

    //  Define the delay for the event trigger (30 seconds).
    hr = pEventTrigger->put_Delay( L"PT30S" );
    if( FAILED(hr) )
        printf("\nCannot put the trigger delay: %x", hr);

    //  Define the event query for the event trigger.
    //  The following query string defines a subscription to all
    //  level 2 events in the System channel.
    hr = pEventTrigger->put_Subscription( 
        L"<QueryList> <Query Id='1'> <Select Path='System'>*[System/Level=2]</Select></Query></QueryList>" );
    pEventTrigger->Release();
    if( FAILED(hr) )
    {
        printf("\nCannot put the event query: %x", hr);  
        pRootFolder->Release();
        pTask->Release();
        CoUninitialize();
        return 1;
    }              

    //  ------------------------------------------------------
    //  Add an action to the task. This task will send an e-mail.     
    IActionCollection *pActionCollection = NULL;

    //  Get the task action collection pointer.
    hr = pTask->get_Actions( &pActionCollection );
    if( FAILED(hr) )
    {
        printf("\nCannot get action collection pointer: %x", hr );
        pRootFolder->Release();
        pTask->Release();
        CoUninitialize();
        return 1;
    }
        
    //  Create the action, specifying that it will send an e-mail.
    IAction *pAction = NULL;
    hr = pActionCollection->Create( TASK_ACTION_SEND_EMAIL, &pAction );
    pActionCollection->Release();
    if( FAILED(hr) )
    {
        printf("\nCannot create an e-mail action: %x", hr );
        pRootFolder->Release();
        pTask->Release();
        CoUninitialize();
        return 1;
    }

    IEmailAction *pEmailAction = NULL;
    //  QI for the e-mail task pointer.
    hr = pAction->QueryInterface(IID_IEmailAction, (void**) &pEmailAction );
    pAction->Release();
    if( FAILED(hr) )
    {
        printf("\nQueryInterface call failed for IEmailAction: %x", hr );
        pRootFolder->Release();
        pTask->Release();
        CoUninitialize();
        return 1;
    }

    //  Set the properties of the e-mail action.
    hr = pEmailAction->put_From(L"*****@*****.**");
    if( FAILED(hr) )
    {
        printf("\nCannot put From information: %x", hr );
        pRootFolder->Release();
        pEmailAction->Release();
        pTask->Release();
        CoUninitialize();
        return 1;
    }

    hr = pEmailAction->put_To(L"*****@*****.**");
    if( FAILED(hr) )
    {
        printf("\nCannot put To information: %x", hr );
        pRootFolder->Release();
        pEmailAction->Release();
        pTask->Release();
        CoUninitialize();
        return 1;
    }

    hr = pEmailAction->put_Server(L"smtp.tschd.microsoft.com");
    if( FAILED(hr) )
    {
        printf("\nCannot put SMTP server information: %x", hr );
        pRootFolder->Release();
        pEmailAction->Release();
        pTask->Release();
        CoUninitialize();
        return 1;
    }
    
    hr = pEmailAction->put_Subject(L"An event has occurred");
    if( FAILED(hr) )
        printf("\nCannot put the subject information: %x", hr);
    
    hr = pEmailAction->put_Body(L"A level 2 event occurred in the system channel.");
    if( FAILED(hr) )
        printf("\nCannot put the e-mail body information: %x", hr);
    
    pEmailAction->Release();

    //  ------------------------------------------------------
    //  Securely get the user name and password. The task will
    //  be created to run with the credentials from the supplied 
    //  user name and password.
    CREDUI_INFO cui;
    TCHAR pszName[CREDUI_MAX_USERNAME_LENGTH] = TEXT("");
    TCHAR pszPwd[CREDUI_MAX_PASSWORD_LENGTH] = TEXT("");
    BOOL fSave;
    DWORD dwErr;

    cui.cbSize = sizeof(CREDUI_INFO);
    cui.hwndParent = NULL;
    //  Ensure that MessageText and CaptionText identify
    //  what credentials to use and which application requires them.
    cui.pszMessageText = TEXT("Account information for task registration:");
    cui.pszCaptionText = TEXT("Enter Account Information for Task Registration");
    cui.hbmBanner = NULL;
    fSave = FALSE;

    //  Create the UI asking for the credentials.
    dwErr = CredUIPromptForCredentials(
        &cui,                             //  CREDUI_INFO structure
        TEXT(""),                         //  Target for credentials
        NULL,                             //  Reserved
        0,                                //  Reason
        pszName,                          //  User name
        CREDUI_MAX_USERNAME_LENGTH,       //  Max number for user name
        pszPwd,                           //  Password
        CREDUI_MAX_PASSWORD_LENGTH,       //  Max number for password
        &fSave,                           //  State of save check box
        CREDUI_FLAGS_GENERIC_CREDENTIALS |  //  Flags
        CREDUI_FLAGS_ALWAYS_SHOW_UI |
        CREDUI_FLAGS_DO_NOT_PERSIST);  

    if(dwErr)
    {
        printf("\nDid not get credentials.");
        pRootFolder->Release();
        pTask->Release();    
        CoUninitialize();
        return 1;      
    }
    
    //  ------------------------------------------------------
    //  Save the task in the root folder.
    IRegisteredTask *pRegisteredTask = NULL;
    hr = pRootFolder->RegisterTaskDefinition(
            _bstr_t( wszTaskName ),
            pTask,
            TASK_CREATE_OR_UPDATE, 
            _variant_t(_bstr_t(pszName)), 
            _variant_t(_bstr_t(pszPwd)), 
            TASK_LOGON_PASSWORD,
            _variant_t(L""),
            &pRegisteredTask);
    if( FAILED(hr) )
    {
        printf("\nError saving the Task : %x", hr );
        pRootFolder->Release();
        pTask->Release();
        CoUninitialize();
        SecureZeroMemory(pszName, sizeof(pszName));
        SecureZeroMemory(pszPwd, sizeof(pszPwd));
        return 1;
    }
    
    printf("\n Success! Task successfully registered. " );

    //  Clean up.
    pRootFolder->Release();
    pTask->Release();
    pRegisteredTask->Release();
    CoUninitialize();

    // When you have finished using the credentials,
    // erase them from memory.
    SecureZeroMemory(pszName, sizeof(pszName));
    SecureZeroMemory(pszPwd, sizeof(pszPwd));

    return 0;
}
Пример #23
0
int main(int argc, char* argv[])
{
	TCLAP::CmdLine cmd("EnvMapTool. Stanislav Podgorskiy.", ' ', "0.1", true);

	TCLAP::ValueArg<std::string> inputFileArg("i", "input", "The input texture file. Can be of the following formats: *.tga, *.png, *.dds", true, "", "Input file");
	TCLAP::MultiArg<std::string> inputMultiFileArg("I", "inputSequence", "The input texture files for cube map. You need specify six files: xp, xn yp, yn, zp, zn. WARNING! All the files MUST be the same format and size!", true, "Input files");
	TCLAP::ValueArg<std::string> outputFileArg("o", "output", "The output texture file.", true, "", "Output file");
	TCLAP::MultiArg<std::string> outputMultiFileArg("O", "outputSequence", "The output texture files for cube map. You need specify six files: xp, xn yp, yn, zp, zn", true, "Output files");
	TCLAP::ValueArg<std::string> outputFormatFileArg("f", "format", "Output texture file format. Can be one of the following \"TGA\", \"DDS\", \"PNG\". Default TGA.", false, "TGA", "Output format");
	TCLAP::ValueArg<int> faceToWriteArg("F", "faceToWrite", "If cubemap texture is written to format that does not support faces, this face will be written", false, 0, "Face to write");

	TCLAP::ValueArg<int> blurQualityArg("q", "blurQuality", "Effects the number of samples in Monte Carlo integration. Reasonable values are between 4 - 8. Large values will increase calculation time dramatically. Default is 4", false, 4, "Blur quality");
	TCLAP::ValueArg<float> blurRadiusArg("b", "blurRadius", "Gaussian blur radius. Default is 10.0", false, 10.0f, "Blur radius");
	TCLAP::SwitchArg doNotRemoveOuterAreaFlag("l", "leaveOuter", "If flag is set, than while cubemap -> sphere transform area around the sphere circule are not filled black, but represent mathematical extrapolation.", false);

	TCLAP::ValueArg<float> inputGammaArg("g", "inputGamma", "Gamma of input texture. Default is 2.2", false, 2.2f, "Input gamma");
	TCLAP::ValueArg<float> outputGammaArg("G", "outputGamma", "Gamma of output texture. Default is 2.2", false, 2.2f, "Output gamma");

	TCLAP::ValueArg<int> outputWidthArg("W", "outputWidth", "Width of output texture. Default is the same as input, or 4 times upscaled in case of cube2sphere transform, or 4 times downscaled in case of sphere2cube transform", false, -1, "Output texture width");
	TCLAP::ValueArg<int> outputHeightArg("H", "outputHeight", "Height of output texture. Default is the same as input, or 4 times upscaled in case of cube2sphere transform, or 4 times downscaled in case of sphere2cube transform", false, -1, "Output texture height");

	std::vector<std::string> allowed;
		allowed.push_back("cube2sphere");
		allowed.push_back("sphere2cube");
		allowed.push_back("blurCubemap");
		allowed.push_back("fastBlurCubemap");
		allowed.push_back("convert");
		TCLAP::ValuesConstraint<std::string> allowedVals( allowed );

	TCLAP::UnlabeledValueArg<std::string>  actionLable( "action",
		"Action. Can be:\n"
		"\tcube2sphere - Converts cube map texture to spherical map\n"
		"\tsphere2cube - Converts spherical map texture to cube map\n"
		"\tblurCubemap - Gaussian blur of cubemap\n"
		"\tconvert - Do nothing. Just to convert txture from one format to other\n", true, "", &allowedVals );

	cmd.add(actionLable);
	cmd.add(outputWidthArg);
	cmd.add(outputHeightArg);
	cmd.add(outputGammaArg);
	cmd.add(inputGammaArg);
	cmd.add(doNotRemoveOuterAreaFlag);
	cmd.add(blurRadiusArg);
	cmd.add(blurQualityArg);
	cmd.add(faceToWriteArg);
	cmd.add(outputFormatFileArg);
	cmd.xorAdd(outputFileArg, outputMultiFileArg);
	cmd.xorAdd(inputFileArg, inputMultiFileArg);
	cmd.parse( argc, argv );

	Texture* inputTex = new Texture;
	inputTex->m_gamma = inputGammaArg.getValue();

	if ( inputFileArg.isSet() )
	{
		inputTex->LoadFromFile(inputFileArg.getValue().c_str());
	}
	else if ( inputMultiFileArg.isSet() )
	{
		std::vector<std::string> files = inputMultiFileArg.getValue();
		if(files.size() != 6)
		{
			printf("Error: You should specify exactly six input files.\n");
			return 0;
		}
		int face = 0;
		for(std::vector<std::string>::iterator it = files.begin(); it != files.end(); ++it)
		{
			inputTex->LoadFromFile(it->c_str(), face);
			face++;
		}
		inputTex->m_cubemap = true;
	}

	Texture* outputTex = new Texture;
	outputTex->m_gamma = outputGammaArg.getValue();

	IFileFormat* format = NULL;
	std::string formatString = outputFormatFileArg.getValue();
	if (formatString == "TGA")
	{
		format = new TGAFile;
	}
	else if (formatString == "DDS")
	{
		format = new DDSFile;
	}
	else if (formatString == "PNG")
	{
		format = new PNGFile;
	}
	else
	{
		printf("Error: Wrong output format!\n");
		return 0;
	}

	int outputWidth = inputTex->m_width;
	int outputHeight = inputTex->m_height;

	IAction* action = NULL;
	std::string actionString = actionLable.getValue();
	if (actionString == "cube2sphere")
	{
		outputWidth *= 4;
		outputHeight *= 4;
		CubeMap2Sphere* cube2s = new CubeMap2Sphere;
		cube2s->m_doNotRemoveOuterAreas = doNotRemoveOuterAreaFlag.getValue();
		action = cube2s;
	}
	else if (actionString == "sphere2cube")
	{
		outputWidth /= 4;
		outputHeight /= 4;
		action = new Sphere2CubeMap;
	}
	else if (actionString == "blurCubemap")
	{
		BlurCubemap* blur = new BlurCubemap;
		blur->m_blurQuality = blurQualityArg.getValue();
		blur->m_blurRadius = blurRadiusArg.getValue();
		action = blur;
	}
	else if (actionString == "fastBlurCubemap")
	{
		FastBlurCubemap* blur = new FastBlurCubemap;
		blur->m_blurRadius = blurRadiusArg.getValue();
		action = blur;
	}
	else if (actionString == "convert")
	{
		action = new DummyAction;
	}
	else
	{
		printf("Error: Wrong action!\n");
		return 0;
	}

	outputTex->m_width = outputWidthArg.isSet() ? outputWidthArg.getValue() : outputWidth;
	outputTex->m_height = outputHeightArg.isSet() ? outputHeightArg.getValue() : outputHeight;

	action->DoTask(*inputTex, *outputTex);

	if ( outputFileArg.isSet() )
	{
		int face = 0;
		if(outputTex->m_cubemap)
		{
			face = faceToWriteArg.getValue();
			face = face > 5 ? 5 : face;
			face = face < 0 ? 0 : face;
		}
		outputTex->SaveToFile(outputFileArg.getValue().c_str(), format, face);
	}
	else if ( outputMultiFileArg.isSet() )
	{
		if(!outputTex->m_cubemap)
		{
			printf("Error: Can't output not a cube map to a sequence of files.\n");
			return 0;
		}
		std::vector<std::string> files = outputMultiFileArg.getValue();
		if(files.size() != 6)
		{
			printf("Error: You should specify exactly six output files.\n");
			return 0;
		}
		int face = 0;
		for(std::vector<std::string>::iterator it = files.begin(); it != files.end(); ++it)
		{
			outputTex->SaveToFile(it->c_str(), format, face);
			face++;
		}
	}
	return 0;
}