static void setupKeymapper(OSystem &system) { #ifdef ENABLE_KEYMAPPER using namespace Common; Keymapper *mapper = system.getEventManager()->getKeymapper(); Keymap *globalMap = new Keymap("global"); Action *act; HardwareKeySet *keySet; keySet = system.getHardwareKeySet(); // Query backend for hardware keys and register them mapper->registerHardwareKeySet(keySet); // Now create the global keymap act = new Action(globalMap, "MENU", _("Menu"), kGenericActionType, kSelectKeyType); act->addKeyEvent(KeyState(KEYCODE_F5, ASCII_F5, 0)); act = new Action(globalMap, "SKCT", _("Skip"), kGenericActionType, kActionKeyType); act->addKeyEvent(KeyState(KEYCODE_ESCAPE, ASCII_ESCAPE, 0)); act = new Action(globalMap, "PAUS", _("Pause"), kGenericActionType, kStartKeyType); act->addKeyEvent(KeyState(KEYCODE_SPACE, ' ', 0)); act = new Action(globalMap, "SKLI", _("Skip line"), kGenericActionType, kActionKeyType); act->addKeyEvent(KeyState(KEYCODE_PERIOD, '.', 0)); act = new Action(globalMap, "VIRT", _("Display keyboard"), kVirtualKeyboardActionType); act->addKeyEvent(KeyState(KEYCODE_F7, ASCII_F7, 0)); act = new Action(globalMap, "REMP", _("Remap keys"), kKeyRemapActionType); act->addKeyEvent(KeyState(KEYCODE_F8, ASCII_F8, 0)); mapper->addGlobalKeymap(globalMap); mapper->pushKeymap("global"); #endif }
Action *ActionManagerPrivate::overridableAction(Id id) { Action *a = m_idCmdMap.value(id, 0); if (!a) { a = new Action(id); m_idCmdMap.insert(id, a); readUserSettings(id, a); ICore::mainWindow()->addAction(a->action()); a->action()->setObjectName(id.toString()); a->action()->setShortcutContext(Qt::ApplicationShortcut); a->setCurrentContext(m_context); if (ActionManager::isPresentationModeEnabled()) connect(a->action(), &QAction::triggered, this, &ActionManagerPrivate::actionTriggered); } return a; }
Action* MenuBar::actionForPath(const QString &path, bool create_if_not_exists) { qfLogFuncFrame() << path; QWidget *parent_w = this; Action *ret = nullptr; QStringList path_list = qf::core::String(path).splitAndTrim('/'); Q_FOREACH(auto id, path_list) { qfDebug() << id << "of path:" << path; if(!parent_w) { /// recent action was not a menu one qfWarning() << "Attempt to traverse through not menu action before:" << id << "in:" << path_list.join("/"); break; } ret = nullptr; Q_FOREACH(auto a, parent_w->actions()) { qfDebug() << a; Action *act = qobject_cast<Action*>(a); //if(!ret) continue; QF_ASSERT(act!=nullptr, "bad action", return ret); if(act->oid() == id) { qfDebug() << "\t found action" << a; ret = act; break; } } if(!ret) { if(!create_if_not_exists) { break; } QMenu *m = new QMenu(parent_w); ret = new Action(parent_w); ret->setMenu(m); ret->setOid(id); ret->setText(id); qfDebug() << "\t created menu" << ret; parent_w->addAction(ret); } parent_w = ret->menu(); }
void ButtonIO::handle_between(Action &action, int value) { if ( action.startTime > 0 ) { if (action.lastState == HIGH && value == LOW) { long time = millis(); long time_down = time - action.startTime; int duration = action.duration; int least = action.least; bool is_between = time_down > least && time_down < duration; if (is_between) { action.callback(action.pin); } action.startTime = -1; } } else { if (action.lastState == LOW && value == HIGH) { action.startTime = millis(); } } }
Action * StdCmdDownloadOnlineHelp::createAction(void) { Action *pcAction; QString exe = QString::fromAscii(App::GetApplication().getExecutableName()); pcAction = new Action(this,getMainWindow()); pcAction->setText(QCoreApplication::translate( this->className(), sMenuText, 0, QCoreApplication::CodecForTr)); pcAction->setToolTip(QCoreApplication::translate( this->className(), sToolTipText, 0, QCoreApplication::CodecForTr).arg(exe)); pcAction->setStatusTip(QCoreApplication::translate( this->className(), sStatusTip, 0, QCoreApplication::CodecForTr).arg(exe)); pcAction->setWhatsThis(QCoreApplication::translate( this->className(), sWhatsThis, 0, QCoreApplication::CodecForTr).arg(exe)); pcAction->setIcon(Gui::BitmapFactory().pixmap(sPixmap)); pcAction->setShortcut(QString::fromAscii(sAccel)); return pcAction; }
// Send Messages void Network::SendActionToAll(const Action& a, bool lock) const { if (0) { if (a.GetType() == Action::ACTION_GAME_CALCULATE_FRAME) { frames++; if (frames == Action::MAX_FRAMES) { Action b(Action::ACTION_GAME_PACK_CALCULATED_FRAMES, Action::MAX_FRAMES); SendAction(b, NULL, false, lock); printf("Sending pack for %u frames\n", Action::MAX_FRAMES); frames = 0; } return; } if (frames>0 && !a.IsFrameLess()) { // This should have arrived here assert(a.GetType()!=Action::ACTION_TIME_VERIFY_SYNC || a.GetType()!=Action::ACTION_NETWORK_VERIFY_RANDOM_SYNC); // The clients must have seen all previous frames for this to occur Action b(Action::ACTION_GAME_PACK_CALCULATED_FRAMES, frames); SendAction(b, NULL, false, lock); printf("Sending pack for %u frames because of action '%s'\n", frames, ActionHandler::GetActionName(a.GetType()).c_str()); frames = 0; } if (a.GetType()==Action::ACTION_TIME_VERIFY_SYNC || a.GetType()==Action::ACTION_NETWORK_VERIFY_RANDOM_SYNC) printf("Sending %u\n", (uint)a.GetType()); } MSG_DEBUG("network.traffic", "Send action %s to all remote computers", ActionHandler::GetActionName(a.GetType()).c_str()); SendAction(a, NULL, false, lock); }
Future<uint64_t> CoordinatorProcess::append(const string& bytes) { if (state == INITIAL) { return Failure("Coordinator is not elected"); } else if (state == ELECTING) { return Failure("Coordinator is being elected"); } else if (state == WRITING) { return Failure("Coordinator is currently writing"); } Action action; action.set_position(index); action.set_promised(proposal); action.set_performed(proposal); action.set_type(Action::APPEND); Action::Append* append = action.mutable_append(); append->set_bytes(bytes); return write(action); }
Future<uint64_t> CoordinatorProcess::truncate(uint64_t to) { if (state == INITIAL) { return Failure("Coordinator is not elected"); } else if (state == ELECTING) { return Failure("Coordinator is being elected"); } else if (state == WRITING) { return Failure("Coordinator is currently writing"); } Action action; action.set_position(index); action.set_promised(proposal); action.set_performed(proposal); action.set_type(Action::TRUNCATE); Action::Truncate* truncate = action.mutable_truncate(); truncate->set_to(to); return write(action); }
RobotInterface::Action RobotInterface::XMLReader::Private::readActionTag(TiXmlElement* actionElem) { if (actionElem->ValueStr().compare("action") != 0) { SYNTAX_ERROR(actionElem->Row()) << "Expected \"action\". Found" << actionElem->ValueStr(); } Action action; if (actionElem->QueryValueAttribute<ActionPhase>("phase", &action.phase()) != TIXML_SUCCESS || action.phase() == ActionPhaseUnknown) { SYNTAX_ERROR(actionElem->Row()) << "\"action\" element should contain the \"phase\" attribute [startup|interrupt{1,2,3}|shutdown]"; } if (actionElem->QueryValueAttribute<ActionType>("type", &action.type()) != TIXML_SUCCESS || action.type() == ActionTypeUnknown) { SYNTAX_ERROR(actionElem->Row()) << "\"action\" element should contain the \"type\" attribute [configure|calibrate|attach|abort|detach|park|custom]"; } // yDebug() << "Found action [ ]"; #if TINYXML_UNSIGNED_INT_BUG if (actionElem->QueryUnsignedAttribute("level", &action.level()) != TIXML_SUCCESS) { SYNTAX_ERROR(actionElem->Row()) << "\"action\" element should contain the \"level\" attribute [unsigned int]"; } #else int tmp; if (actionElem->QueryIntAttribute("level", &tmp) != TIXML_SUCCESS || tmp < 0) { SYNTAX_ERROR(actionElem->Row()) << "\"action\" element should contain the \"level\" attribute [unsigned int]"; } action.level() = (unsigned)tmp; #endif for (TiXmlElement* childElem = actionElem->FirstChildElement(); childElem != 0; childElem = childElem->NextSiblingElement()) { ParamList childParams = readParams(childElem); for (ParamList::const_iterator it = childParams.begin(); it != childParams.end(); ++it) { action.params().push_back(*it); } } // yDebug() << action; return action; }
Action *ActionManagerPrivate::overridableAction(Id id) { Action *a = 0; if (CommandPrivate *c = m_idCmdMap.value(id, 0)) { a = qobject_cast<Action *>(c); if (!a) { qWarning() << "registerAction: id" << id.name() << "is registered with a different command type."; return 0; } } else { a = new Action(id); m_idCmdMap.insert(id, a); ICore::mainWindow()->addAction(a->action()); a->action()->setObjectName(id.toString()); a->action()->setShortcutContext(Qt::ApplicationShortcut); a->setCurrentContext(m_context); if (ActionManager::isPresentationModeEnabled()) connect(a->action(), SIGNAL(triggered()), this, SLOT(actionTriggered())); } return a; }
Action * MacroCommand::createAction(void) { Action *pcAction; pcAction = new Action(this,getMainWindow()); pcAction->setText(QString::fromUtf8(sMenuText)); pcAction->setToolTip(QString::fromUtf8(sToolTipText)); pcAction->setStatusTip(QString::fromUtf8(sStatusTip)); if (pcAction->statusTip().isEmpty()) pcAction->setStatusTip(pcAction->toolTip()); pcAction->setWhatsThis(QString::fromUtf8(sWhatsThis)); if (sPixmap) pcAction->setIcon(Gui::BitmapFactory().pixmap(sPixmap)); pcAction->setShortcut(QString::fromAscii(sAccel)); QString accel = pcAction->shortcut().toString(QKeySequence::NativeText); if (!accel.isEmpty()) { // show shortcut inside tooltip QString ttip = QString::fromLatin1("%1 (%2)") .arg(pcAction->toolTip()).arg(accel); pcAction->setToolTip(ttip); // show shortcut inside status tip QString stip = QString::fromLatin1("(%1)\t%2") .arg(accel).arg(pcAction->statusTip()); pcAction->setStatusTip(stip); } return pcAction; }
Try<Nothing> LevelDBStorage::persist(const Action& action) { Stopwatch stopwatch; stopwatch.start(); Record record; record.set_type(Record::ACTION); record.mutable_action()->MergeFrom(action); string value; if (!record.SerializeToString(&value)) { return Error("Failed to serialize record"); } leveldb::WriteOptions options; options.sync = true; leveldb::Status status = db->Put(options, encode(action.position()), value); if (!status.ok()) { return Error(status.ToString()); } // Updated the first position. Notice that we use 'min' here instead // of checking 'isNone()' because it's likely that log entries are // written out of order during catch-up (e.g. if a random bulk // catch-up policy is used). first = min(first, action.position()); LOG(INFO) << "Persisting action (" << value.size() << " bytes) to leveldb took " << stopwatch.elapsed(); // Delete positions if a truncate action has been *learned*. Note // that we do this in a best-effort fashion (i.e., we ignore any // failures to the database since we can always try again). if (action.has_type() && action.type() == Action::TRUNCATE && action.has_learned() && action.learned()) { CHECK(action.has_truncate()); stopwatch.start(); // Restart the stopwatch. // To actually perform the truncation in leveldb we need to remove // all the keys that represent positions no longer in the log. We // do this by attempting to delete all keys that represent the // first position we know is still in leveldb up to (but // excluding) the truncate position. Note that this works because // the semantics of WriteBatch are such that even if the position // doesn't exist (which is possible because this replica has some // holes), we can attempt to delete the key that represents it and // it will just ignore that key. This is *much* cheaper than // actually iterating through the entire database instead (which // was, for posterity, the original implementation). In addition, // caching the "first" position we know is in the database is // cheaper than using an iterator to determine the first position // (which was, for posterity, the second implementation). leveldb::WriteBatch batch; CHECK_SOME(first); // Add positions up to (but excluding) the truncate position to // the batch starting at the first position still in leveldb. It's // likely that the first position is greater than the truncate // position (e.g., during catch-up). In that case, we do nothing // because there is nothing we can truncate. // TODO(jieyu): We might miss a truncation if we do random (i.e., // out of order) bulk catch-up and the truncate operation is // caught up first. uint64_t index = 0; while ((first.get() + index) < action.truncate().to()) { batch.Delete(encode(first.get() + index)); index++; } // If we added any positions, attempt to delete them! if (index > 0) { // We do this write asynchronously (e.g., using default options). leveldb::Status status = db->Write(leveldb::WriteOptions(), &batch); if (!status.ok()) { LOG(WARNING) << "Ignoring leveldb batch delete failure: " << status.ToString(); } else { // Save the new first position! CHECK_LT(first.get(), action.truncate().to()); first = action.truncate().to(); LOG(INFO) << "Deleting ~" << index << " keys from leveldb took " << stopwatch.elapsed(); } } } return Nothing(); }
ReturnValue Actions::internalUseItem(Player* player, const Position& pos, uint8_t index, Item* item, bool isHotkey) { if (Door* door = item->getDoor()) { if (!door->canUse(player)) { return RETURNVALUE_CANNOTUSETHISOBJECT; } } Action* action = getAction(item); if (action) { int32_t stack = item->getParent()->__getIndexOfThing(item); PositionEx posEx(pos, stack); if (action->isScripted()) { if (action->executeUse(player, item, posEx, posEx, false, 0, isHotkey)) { return RETURNVALUE_NOERROR; } } else if (action->function) { if (action->function(player, item, posEx, posEx, false, isHotkey)) { return RETURNVALUE_NOERROR; } } } if (BedItem* bed = item->getBed()) { if (!bed->canUse(player)) { return RETURNVALUE_CANNOTUSETHISOBJECT; } if (bed->trySleep(player)) { player->setBedItem(bed); g_game.sendOfflineTrainingDialog(player); } return RETURNVALUE_NOERROR; } if (Container* container = item->getContainer()) { Container* openContainer; //depot container if (DepotLocker* depot = container->getDepotLocker()) { DepotLocker* myDepotLocker = player->getDepotLocker(depot->getDepotId()); myDepotLocker->setParent(depot->getParent()->getTile()); openContainer = myDepotLocker; player->setLastDepotId(depot->getDepotId()); } else { openContainer = container; } uint32_t corpseOwner = container->getCorpseOwner(); if (corpseOwner != 0 && !player->canOpenCorpse(corpseOwner)) { return RETURNVALUE_YOUARENOTTHEOWNER; } //open/close container int32_t oldContainerId = player->getContainerID(openContainer); if (oldContainerId != -1) { player->onCloseContainer(openContainer); player->closeContainer(oldContainerId); } else { player->addContainer(index, openContainer); player->onSendContainer(openContainer); } return RETURNVALUE_NOERROR; } if (item->isReadable()) { if (item->canWriteText()) { player->setWriteItem(item, item->getMaxWriteLength()); player->sendTextWindow(item, item->getMaxWriteLength(), true); } else { player->setWriteItem(nullptr); player->sendTextWindow(item, 0, false); } return RETURNVALUE_NOERROR; } return RETURNVALUE_CANNOTUSETHISOBJECT; }
void RemapDialog::loadKeymap() { _currentActions.clear(); const Stack<Keymapper::MapRecord> &activeKeymaps = _keymapper->getActiveStack(); debug(3, "RemapDialog::loadKeymap active keymaps: %u", activeKeymaps.size()); if (!activeKeymaps.empty() && _kmPopUp->getSelected() == 0) { // This is the "effective" view which shows all effective actions: // - all of the topmost keymap action // - all mapped actions that are reachable List<const HardwareInput *> freeInputs(_keymapper->getHardwareInputs()); int topIndex = activeKeymaps.size() - 1; // This is a WORKAROUND for changing the popup list selected item and changing it back // to the top entry. Upon changing it back, the top keymap is always "gui". if (!_topKeymapIsGui && activeKeymaps[topIndex].keymap->getName() == kGuiKeymapName) --topIndex; // add most active keymap's keys Keymapper::MapRecord top = activeKeymaps[topIndex]; List<Action *>::iterator actIt; debug(3, "RemapDialog::loadKeymap top keymap: %s", top.keymap->getName().c_str()); for (actIt = top.keymap->getActions().begin(); actIt != top.keymap->getActions().end(); ++actIt) { Action *act = *actIt; ActionInfo info = {act, false, act->description}; _currentActions.push_back(info); if (act->getMappedInput()) freeInputs.remove(act->getMappedInput()); } // loop through remaining finding mappings for unmapped keys if (top.transparent && topIndex >= 0) { for (int i = topIndex - 1; i >= 0; --i) { Keymapper::MapRecord mr = activeKeymaps[i]; debug(3, "RemapDialog::loadKeymap keymap: %s", mr.keymap->getName().c_str()); List<const HardwareInput *>::iterator inputIt = freeInputs.begin(); const HardwareInput *input = *inputIt; while (inputIt != freeInputs.end()) { Action *act = 0; if (input->type == kHardwareInputTypeKeyboard) act = mr.keymap->getMappedAction(input->key); else if (input->type == kHardwareInputTypeGeneric) act = mr.keymap->getMappedAction(input->inputCode); if (act) { ActionInfo info = {act, true, act->description + " (" + mr.keymap->getName() + ")"}; _currentActions.push_back(info); freeInputs.erase(inputIt); } else { ++inputIt; } } if (mr.transparent == false || freeInputs.empty()) break; } } } else if (_kmPopUp->getSelected() != -1) { // This is the regular view of a keymap that isn't the topmost one. // It shows all of that keymap's actions Keymap *km = _keymapTable[_kmPopUp->getSelectedTag()]; List<Action *>::iterator it; for (it = km->getActions().begin(); it != km->getActions().end(); ++it) { ActionInfo info = {*it, false, (*it)->description}; _currentActions.push_back(info); } } // refresh scroll bar _scrollBar->_currentPos = 0; _scrollBar->_numEntries = _currentActions.size(); _scrollBar->recalc(); // force refresh _topAction = -1; refreshKeymap(); }
void Player::makeMove() { vector<Vec2> squareDirs = creature->getConstSquare()->getTravelDir(); const vector<Creature*>& creatures = creature->getLevel()->getAllCreatures(); if (creature->isAffected(Creature::HALLU)) ViewObject::setHallu(true); else ViewObject::setHallu(false); MEASURE( model->getView()->refreshView(creature), "level render time"); if (Options::getValue(OptionId::HINTS) && displayTravelInfo && creature->getConstSquare()->getName() == "road") { model->getView()->presentText("", "Use ctrl + arrows to travel quickly on roads and corridors."); displayTravelInfo = false; } static bool greeting = false; if (Options::getValue(OptionId::HINTS) && displayGreeting) { CHECK(creature->getFirstName()); model->getView()->presentText("", "Dear " + *creature->getFirstName() + ",\n \n \tIf you are reading this letter, then you have arrived in the valley of " + NameGenerator::worldNames.getNext() + ". There is a band of dwarves dwelling in caves under a mountain. Find them, talk to them, they will help you. Let your sword guide you.\n \n \nYours, " + NameGenerator::firstNames.getNext() + "\n \nPS.: Beware the goblins!"); model->getView()->presentText("", "Every settlement that you find has a leader, and they may have quests for you." "\n \nYou can turn these messages off in the options (press F2)."); displayGreeting = false; model->getView()->refreshView(creature); } for (const Creature* c : creature->getVisibleEnemies()) { if (c->isSpecialMonster() && !contains(specialCreatures, c)) { privateMessage(MessageBuffer::important(c->getDescription())); model->getView()->refreshView(creature); specialCreatures.push_back(c); } } if (travelling) travelAction(); else if (target) targetAction(); else { Action action = model->getView()->getAction(); vector<Vec2> direction; bool travel = false; switch (action.getId()) { case ActionId::FIRE: fireAction(action.getDirection()); break; case ActionId::TRAVEL: travel = true; case ActionId::MOVE: direction.push_back(action.getDirection()); break; case ActionId::MOVE_TO: if (action.getDirection().dist8(creature->getPosition()) == 1) { Vec2 dir = action.getDirection() - creature->getPosition(); if (const Creature* c = creature->getConstSquare(dir)->getCreature()) { if (!creature->isEnemy(c)) { chatAction(dir); break; } } direction.push_back(dir); } else if (action.getDirection() != creature->getPosition()) { target = action.getDirection(); target = Vec2(min(creature->getLevel()->getBounds().getKX() - 1, max(0, target->x)), min(creature->getLevel()->getBounds().getKY() - 1, max(0, target->y))); // Just in case if (!target->inRectangle(creature->getLevel()->getBounds())) target = Nothing(); } else pickUpAction(false); break; case ActionId::SHOW_INVENTORY: displayInventory(); break; case ActionId::PICK_UP: pickUpAction(false); break; case ActionId::EXT_PICK_UP: pickUpAction(true); break; case ActionId::DROP: dropAction(false); break; case ActionId::EXT_DROP: dropAction(true); break; case ActionId::WAIT: creature->wait(); break; case ActionId::APPLY_ITEM: applyAction(); break; case ActionId::THROW: throwAction(); break; case ActionId::THROW_DIR: throwAction(action.getDirection()); break; case ActionId::EQUIPMENT: equipmentAction(); break; case ActionId::HIDE: hideAction(); break; case ActionId::PAY_DEBT: payDebtAction(); break; case ActionId::CHAT: chatAction(); break; case ActionId::SHOW_HISTORY: messageBuffer.showHistory(); break; case ActionId::UNPOSSESS: if (creature->canPopController()) { creature->popController(); return; } break; case ActionId::CAST_SPELL: spellAction(); break; case ActionId::DRAW_LEVEL_MAP: model->getView()->drawLevelMap(creature); break; case ActionId::EXIT: model->exitAction(); break; case ActionId::IDLE: break; } if (creature->isAffected(Creature::SLEEP) && creature->canPopController()) { if (model->getView()->yesOrNoPrompt("You fell asleep. Do you want to leave your minion?")) creature->popController(); return; } for (Vec2 dir : direction) if (travel) { vector<Vec2> squareDirs = creature->getConstSquare()->getTravelDir(); if (findElement(squareDirs, dir)) { travelDir = dir; lastLocation = creature->getLevel()->getLocation(creature->getPosition()); travelling = true; travelAction(); } } else if (creature->canMove(dir)) { creature->move(dir); itemsMessage(); break; } else { const Creature *c = creature->getConstSquare(dir)->getCreature(); if (creature->canBumpInto(dir)) { creature->bumpInto(dir); break; } else if (creature->canDestroy(dir)) { privateMessage("You bash the " + creature->getSquare(dir)->getName()); creature->destroy(dir); break; } } } for (Vec2 pos : creature->getLevel()->getVisibleTiles(creature)) { ViewIndex index = creature->getLevel()->getSquare(pos)->getViewIndex(creature); (*levelMemory)[creature->getLevel()].clearSquare(pos); for (ViewLayer l : { ViewLayer::ITEM, ViewLayer::FLOOR_BACKGROUND, ViewLayer::FLOOR, ViewLayer::LARGE_ITEM}) if (index.hasObject(l)) remember(pos, index.getObject(l)); } }
void MenuAdapter::remove(Action& action) { ::RemoveMenu(HMENU(_handle), (UINT) uptrint_t(action.getId()), MF_BYCOMMAND); }
/*static*/ QMenu* JMenuUtil::jMenuFromElement(QDomElement main, WindowInterface* wi, QObject* context) { bool addSep = false; QString name = "<none>"; Logger log("JMenuUtil"); if (main.isNull()) { log.warn("Menu from element called without an element"); return new QMenu(name); } //name = LocaleSelector.getAttribute(main, "name"); name = GuiUtilBase::getLocaleAttribute(main, "name"); QMenu* menu = new QMenu(name); QList<int> mnemonicList = QList<int>(); //QDomNodeList nodes = main.elementsByTagName("node"); QDomNodeList nodes = main.childNodes(); for(int i = 0; i < nodes.size(); i++) { QObject* menuItem = NULL; QDomElement child = nodes.at(i).toElement(); if(child.tagName()!= "node") continue; if (child.elementsByTagName("node").size() == 0) { // leaf //QAction* menuItem = NULL; if ((child.text().trimmed())==("separator")) { addSep = true; } else { if ((/*!SystemType.isMacOSX()*/ // && UIManager.getLookAndFeel().isNativeLookAndFeel() && (!(child.firstChildElement("adapter").isNull() && child.firstChildElement("adapter").text()==("apps.gui3.TabbedPreferencesAction")) || !(child.firstChildElement("current").isNull() && child.firstChildElement("current").text()==("quit"))))) { if (addSep) { menu->addSeparator(); addSep = false; } QString leafName = child.attribute("name"); Action* act = actionFromNode(child, wi, context); if(act !=NULL) { log.debug(tr("create action item '%1' in '%2' menu").arg(act->text()).arg(name)); menu->addAction((QAction*)(menuItem = (QObject*)act)); if(!child.firstChildElement("type").isNull()) { if(child.firstChildElement("type").text() == "checkbox") act->setCheckable(true); } if (!child.firstChildElement("current").isNull()) { //setMenuItemInterAction(context, child.firstChildElement("current").text(), menuItem); QString current = act->data().toString(); ((RosterFrame*)wi)->currentMapper->setMapping(act,act); connect(act, SIGNAL(triggered(bool)), ((RosterFrame*)wi)->currentMapper, SLOT(map())); } } } } }
MDP *convert_map_to_array(StatesMap *states, ActionsMap *actions, StateTransitions *stateTransitions, SASRewards *rewards, Horizon *horizon) { // Next, create the states object. As part of this, we must create a mapping from the // indexed states to the original states. Also create the initial state in the process. StatesMap *S = new StatesMap(); std::unordered_map<unsigned int, State *> convertStates; IndexedState::reset_indexer(); for (auto state : *states) { State *indexedState = new IndexedState(); S->add(indexedState); convertStates[indexedState->hash_value()] = resolve(state); } // Create the actions object in a similar manner, with its own mapping. ActionsMap *A = new ActionsMap(); std::unordered_map<unsigned int, Action *> convertActions; IndexedAction::reset_indexer(); for (auto action : *actions) { Action *indexedAction = new IndexedAction(); A->add(indexedAction); convertActions[indexedAction->hash_value()] = resolve(action); } // With our states and actions maps, we may now create the state transitions and the rewards. StateTransitionsArray *T = new StateTransitionsArray(S->get_num_states(), A->get_num_actions()); SASRewardsArray *R = new SASRewardsArray(S->get_num_states(), A->get_num_actions()); for (auto state : *S) { State *s = resolve(state); State *sOriginal = convertStates[s->hash_value()]; for (auto action : *A) { Action *a = resolve(action); Action *aOriginal = convertActions[a->hash_value()]; for (auto nextState : *S) { State *sp = resolve(nextState); State *spOriginal = convertStates[sp->hash_value()]; // std::cout << "(" << sOriginal->to_string() << ", " << aOriginal->to_string() << ", " << spOriginal->to_string() << ")\n"; // std::cout.flush(); T->set(s, a, sp, stateTransitions->get(sOriginal, aOriginal, spOriginal)); R->set(s, a, sp, rewards->get(sOriginal, aOriginal, spOriginal)); } } } // Finally, create a copy of the horizon. Horizon *h = nullptr; if (horizon->is_finite()) { h = new Horizon(horizon->get_horizon()); } else { h = new Horizon(horizon->get_discount_factor()); } return new MDP(S, A, T, R, h); }
/** * The state machine takes care of passing all the events from SDL to the * active state, running any code within and blitting all the states and * cursor to the screen. This is run indefinitely until the game quits. */ void Game::run() { enum ApplicationState { RUNNING = 0, SLOWED = 1, PAUSED = 2 } runningState = RUNNING; static const ApplicationState kbFocusRun[4] = { RUNNING, RUNNING, SLOWED, PAUSED }; static const ApplicationState stateRun[4] = { SLOWED, PAUSED, PAUSED, PAUSED }; // this will avoid processing SDL's resize event on startup, workaround for the heap allocation error it causes. bool startupEvent = Options::allowResize; while (!_quit) { // Clean up states while (!_deleted.empty()) { delete _deleted.back(); _deleted.pop_back(); } // Initialize active state if (!_init) { _init = true; _states.back()->init(); // Unpress buttons _states.back()->resetAll(); // Refresh mouse position SDL_Event ev; int x, y; SDL_GetMouseState(&x, &y); ev.type = SDL_MOUSEMOTION; ev.motion.x = x; ev.motion.y = y; Action action = Action(&ev, _screen->getXScale(), _screen->getYScale(), _screen->getCursorTopBlackBand(), _screen->getCursorLeftBlackBand()); _states.back()->handle(&action); } // Process events while (SDL_PollEvent(&_event)) { if (CrossPlatform::isQuitShortcut(_event)) _event.type = SDL_QUIT; switch (_event.type) { case SDL_QUIT: quit(); break; case SDL_ACTIVEEVENT: switch (reinterpret_cast<SDL_ActiveEvent*>(&_event)->state) { case SDL_APPACTIVE: runningState = reinterpret_cast<SDL_ActiveEvent*>(&_event)->gain ? RUNNING : stateRun[Options::pauseMode]; break; case SDL_APPMOUSEFOCUS: // We consciously ignore it. break; case SDL_APPINPUTFOCUS: runningState = reinterpret_cast<SDL_ActiveEvent*>(&_event)->gain ? RUNNING : kbFocusRun[Options::pauseMode]; break; } break; case SDL_VIDEORESIZE: if (Options::allowResize) { if (!startupEvent) { Options::newDisplayWidth = Options::displayWidth = std::max(Screen::ORIGINAL_WIDTH, _event.resize.w); Options::newDisplayHeight = Options::displayHeight = std::max(Screen::ORIGINAL_HEIGHT, _event.resize.h); int dX = 0, dY = 0; Screen::updateScale(Options::battlescapeScale, Options::battlescapeScale, Options::baseXBattlescape, Options::baseYBattlescape, false); Screen::updateScale(Options::geoscapeScale, Options::geoscapeScale, Options::baseXGeoscape, Options::baseYGeoscape, false); for (std::list<State*>::iterator i = _states.begin(); i != _states.end(); ++i) { (*i)->resize(dX, dY); } _screen->resetDisplay(); } else { startupEvent = false; } } break; case SDL_MOUSEMOTION: case SDL_MOUSEBUTTONDOWN: case SDL_MOUSEBUTTONUP: // Skip mouse events if they're disabled if (!_mouseActive) continue; // re-gain focus on mouse-over or keypress. runningState = RUNNING; // Go on, feed the event to others default: Action action = Action(&_event, _screen->getXScale(), _screen->getYScale(), _screen->getCursorTopBlackBand(), _screen->getCursorLeftBlackBand()); _screen->handle(&action); _cursor->handle(&action); _fpsCounter->handle(&action); _states.back()->handle(&action); if (action.getDetails()->type == SDL_KEYDOWN) { // "ctrl-g" grab input if (action.getDetails()->key.keysym.sym == SDLK_g && (SDL_GetModState() & KMOD_CTRL) != 0) { Options::captureMouse = (SDL_GrabMode)(!Options::captureMouse); SDL_WM_GrabInput(Options::captureMouse); } else if (Options::debug) { if (action.getDetails()->key.keysym.sym == SDLK_t && (SDL_GetModState() & KMOD_CTRL) != 0) { setState(new TestState); } // "ctrl-u" debug UI else if (action.getDetails()->key.keysym.sym == SDLK_u && (SDL_GetModState() & KMOD_CTRL) != 0) { Options::debugUi = !Options::debugUi; _states.back()->redrawText(); } } } break; } } // Process rendering if (runningState != PAUSED) { // Process logic _states.back()->think(); _fpsCounter->think(); if (Options::FPS > 0 && !(Options::useOpenGL && Options::vSyncForOpenGL)) { // Update our FPS delay time based on the time of the last draw. int fps = SDL_GetAppState() & SDL_APPINPUTFOCUS ? Options::FPS : Options::FPSInactive; _timeUntilNextFrame = (1000.0f / fps) - (SDL_GetTicks() - _timeOfLastFrame); } else { _timeUntilNextFrame = 0; } if (_init && _timeUntilNextFrame <= 0) { // make a note of when this frame update occured. _timeOfLastFrame = SDL_GetTicks(); _fpsCounter->addFrame(); _screen->clear(); std::list<State*>::iterator i = _states.end(); do { --i; } while (i != _states.begin() && !(*i)->isScreen()); for (; i != _states.end(); ++i) { (*i)->blit(); } _fpsCounter->blit(_screen->getSurface()); _cursor->blit(_screen->getSurface()); _screen->flip(); } } // Save on CPU switch (runningState) { case RUNNING: SDL_Delay(1); //Save CPU from going 100% break; case SLOWED: case PAUSED: SDL_Delay(100); break; //More slowing down. } } Options::save(); }
DeviceManager::DeviceError DevicePluginIntertechno::executeAction(Device *device, const Action &action) { QList<int> rawData; QByteArray binCode; QString familyCode = device->paramValue("familyCode").toString(); // ======================================= // generate bin from family code if(familyCode == "A"){ binCode.append("00000000"); }else if(familyCode == "B"){ binCode.append("01000000"); }else if(familyCode == "C"){ binCode.append("00010000"); }else if(familyCode == "D"){ binCode.append("01010000"); }else if(familyCode == "E"){ binCode.append("00000100"); }else if(familyCode == "F"){ binCode.append("01000100"); }else if(familyCode == "G"){ binCode.append("01000000"); }else if(familyCode == "H"){ binCode.append("01010100"); }else if(familyCode == "I"){ binCode.append("00000001"); }else if(familyCode == "J"){ binCode.append("01000001"); }else if(familyCode == "K"){ binCode.append("00010001"); }else if(familyCode == "L"){ binCode.append("01010001"); }else if(familyCode == "M"){ binCode.append("00000101"); }else if(familyCode == "N"){ binCode.append("01000101"); }else if(familyCode == "O"){ binCode.append("00010101"); }else if(familyCode == "P"){ binCode.append("01010101"); }else{ return DeviceManager::DeviceErrorNoError; } QString buttonCode = device->paramValue("buttonCode").toString(); // ======================================= // generate bin from button code if(familyCode == "1"){ binCode.append("00000000"); }else if(familyCode == "2"){ binCode.append("01000000"); }else if(familyCode == "3"){ binCode.append("00010000"); }else if(familyCode == "4"){ binCode.append("01010000"); }else if(familyCode == "5"){ binCode.append("00000100"); }else if(familyCode == "6"){ binCode.append("01000100"); }else if(familyCode == "7"){ binCode.append("01000000"); }else if(familyCode == "8"){ binCode.append("01010100"); }else if(familyCode == "9"){ binCode.append("00000001"); }else if(familyCode == "10"){ binCode.append("01000001"); }else if(familyCode == "11"){ binCode.append("00010001"); }else if(familyCode == "12"){ binCode.append("01010001"); }else if(familyCode == "13"){ binCode.append("00000101"); }else if(familyCode == "14"){ binCode.append("01000101"); }else if(familyCode == "15"){ binCode.append("00010101"); }else if(familyCode == "16"){ binCode.append("01010101"); }else{ return DeviceManager::DeviceErrorNoError; } // ======================================= // add fix nibble (0F) binCode.append("0001"); // ======================================= // add power nibble if(action.param("power").value().toBool()){ binCode.append("0101"); }else{ binCode.append("0100"); } //qDebug() << "bin code:" << binCode; // ======================================= //create rawData timings list int delay = 350; // sync signal rawData.append(1); rawData.append(31); // add the code foreach (QChar c, binCode) { if(c == '0'){ rawData.append(1); rawData.append(3); }else{ rawData.append(3); rawData.append(1); } } // ======================================= // send data to hardware resource if(transmitData(delay, rawData)){ qDebug() << "transmitted" << pluginName() << device->name() << "power: " << action.param("power").value().toBool(); return DeviceManager::DeviceErrorNoError; }else{ qWarning() << "ERROR: could not transmitt" << pluginName() << device->name() << "power: " << action.param("power").value().toBool(); return DeviceManager::DeviceErrorHardwareNotAvailable; } }
void ContextMenuActionProvider::addIgnoreMenu(QMenu *menu, const QString &hostmask, const QMap<QString, bool> &ignoreMap) { QMenu *ignoreMenu = _nickIgnoreMenuAction->menu(); ignoreMenu->clear(); QString nick = nickFromMask(hostmask); QString ident = userFromMask(hostmask); QString host = hostFromMask(hostmask); QString domain = host; QRegExp domainRx = QRegExp("(\\.[^.]+\\.\\w+\\D)$"); if (domainRx.indexIn(host) != -1) domain = domainRx.cap(1); // we can't rely on who-data // if we don't have the data, we skip actions where we would need it bool haveWhoData = !ident.isEmpty() && !host.isEmpty(); // add "Add Ignore Rule" description ignoreMenu->addAction(_ignoreDescriptions.at(0)); if (haveWhoData) { QString text; text = QString("*!%1@%2").arg(ident, host); action(NickIgnoreUser)->setText(text); action(NickIgnoreUser)->setProperty("ignoreRule", text); text = QString("*!*@%1").arg(host); action(NickIgnoreHost)->setText(text); action(NickIgnoreHost)->setProperty("ignoreRule", text); text = domain.at(0) == '.' ? QString("*!%1@*%2").arg(ident, domain) : QString("*!%1@%2").arg(ident, domain); action(NickIgnoreDomain)->setText(text); action(NickIgnoreDomain)->setProperty("ignoreRule", text); if (!ignoreMap.contains(action(NickIgnoreUser)->property("ignoreRule").toString())) ignoreMenu->addAction(action(NickIgnoreUser)); if (!ignoreMap.contains(action(NickIgnoreHost)->property("ignoreRule").toString())) ignoreMenu->addAction(action(NickIgnoreHost)); // we only add that NickIgnoreDomain if it isn't the same as NickIgnoreUser // as happens with @foobar.com hostmasks and ips if (!ignoreMap.contains(action(NickIgnoreDomain)->property("ignoreRule").toString()) && action(NickIgnoreUser)->property("ignoreRule").toString() != action(NickIgnoreDomain)->property("ignoreRule").toString()) ignoreMenu->addAction(action(NickIgnoreDomain)); } action(NickIgnoreCustom)->setProperty("ignoreRule", hostmask); ignoreMenu->addAction(action(NickIgnoreCustom)); ignoreMenu->addSeparator(); if (haveWhoData) { QMap<QString, bool>::const_iterator ruleIter = ignoreMap.begin(); int counter = 0; if (!ignoreMap.isEmpty()) // add "Existing Rules" description ignoreMenu->addAction(_ignoreDescriptions.at(1)); while (ruleIter != ignoreMap.constEnd()) { if (counter < 5) { ActionType type = static_cast<ActionType>(NickIgnoreToggleEnabled0 + counter*0x100000); Action *act = action(type); act->setText(ruleIter.key()); act->setProperty("ignoreRule", ruleIter.key()); act->setChecked(ruleIter.value()); ignoreMenu->addAction(act); } counter++; ++ruleIter; } if (counter) ignoreMenu->addSeparator(); } ignoreMenu->addAction(action(ShowIgnoreList)); addAction(_nickIgnoreMenuAction, menu); }
TEST(testPool, make_action) { Action<size_t, decltype(test), int, int> action = make_action<decltype(test), int, int > (test, 2, 6); ASSERT_EQ(action.act(), 12); }
// TODO: // - current weakness: // - if an action finds a key with required type but a parent action with // higher priority is using it, that key is never used void Keymap::automaticMapping(HardwareKeySet *hwKeys) { // Create copies of action and key lists. List<Action*> actions(_actions); List<const HardwareKey*> keys(hwKeys->getHardwareKeys()); List<Action*>::iterator actIt; List<const HardwareKey*>::iterator keyIt, selectedKey; // Remove actions and keys from local lists that have already been mapped. actIt = actions.begin(); while (actIt != actions.end()) { Action *act = *actIt; const HardwareKey *key = act->getMappedKey(); if (key) { keys.remove(key); actIt = actions.erase(actIt); } else { ++actIt; } } // Sort remaining actions by priority. ActionPriorityComp priorityComp; sort(actions.begin(), actions.end(), priorityComp); // First mapping pass: // - Match if a key's preferred action type is the same as the action's // type, or vice versa. // - Priority is given to: // - keys that match action types over key types. // - keys that have not been used by parent maps. // - If a key has been used by a parent map the new action must have a // higher priority than the parent action. // - As soon as the number of skipped actions equals the number of keys // remaining we stop matching. This means that the second pass will assign keys // to these higher priority skipped actions. uint skipped = 0; actIt = actions.begin(); while (actIt != actions.end() && skipped < keys.size()) { selectedKey = keys.end(); int matchRank = 0; Action *act = *actIt; for (keyIt = keys.begin(); keyIt != keys.end(); ++keyIt) { if ((*keyIt)->preferredAction == act->type && act->type != kGenericActionType) { Action *parentAct = getParentMappedAction((*keyIt)->key); if (!parentAct) { selectedKey = keyIt; break; } else if (parentAct->priority <= act->priority && matchRank < 3) { selectedKey = keyIt; matchRank = 3; } } else if ((*keyIt)->type == act->preferredKey && act->preferredKey != kGenericKeyType && matchRank < 2) { Action *parentAct = getParentMappedAction((*keyIt)->key); if (!parentAct) { selectedKey = keyIt; matchRank = 2; } else if (parentAct->priority <= act->priority && matchRank < 1) { selectedKey = keyIt; matchRank = 1; } } } if (selectedKey != keys.end()) { // Map action and delete action & key from local lists. act->mapKey(*selectedKey); keys.erase(selectedKey); actIt = actions.erase(actIt); } else { // Skip action (will be mapped in next pass). ++actIt; ++skipped; } } // Second mapping pass: // - Maps any remaining actions to keys // - priority given to: // - keys that have no parent action // - keys whose parent action has lower priority than the new action // - keys whose parent action has the lowest priority // - is guaranteed to match a key if they are not all used up for (actIt = actions.begin(); actIt != actions.end(); ++actIt) { selectedKey = keys.end(); int matchRank = 0; int lowestPriority = 0; Action *act = *actIt; for (keyIt = keys.begin(); keyIt != keys.end(); ++keyIt) { Action *parentAct = getParentMappedAction((*keyIt)->key); if (!parentAct) { selectedKey = keyIt; break; } else if (matchRank < 2) { if (parentAct->priority <= act->priority) { matchRank = 2; selectedKey = keyIt; } else if (parentAct->priority < lowestPriority || matchRank == 0) { matchRank = 1; lowestPriority = parentAct->priority; selectedKey = keyIt; } } } if (selectedKey != keys.end()) { act->mapKey(*selectedKey); keys.erase(selectedKey); } else {// no match = no keys left break; } } }
Action *Registration::createDiscoFeatureAction(const Jid &AStreamJid, const QString &AFeature, const IDiscoInfo &ADiscoInfo, QWidget *AParent) { IPresence *presence = FPresenceManager!=NULL ? FPresenceManager->findPresence(AStreamJid) : NULL; if (presence && presence->isOpen() && AFeature==NS_JABBER_REGISTER) { Menu *regMenu = new Menu(AParent); regMenu->setTitle(tr("Registration")); regMenu->setIcon(RSR_STORAGE_MENUICONS,MNI_REGISTRATION); Action *action = new Action(regMenu); action->setText(tr("Register")); action->setIcon(RSR_STORAGE_MENUICONS,MNI_REGISTRATION); action->setData(ADR_STREAM_JID,AStreamJid.full()); action->setData(ADR_SERVICE_JID,ADiscoInfo.contactJid.full()); action->setData(ADR_OPERATION,IRegistration::Register); connect(action,SIGNAL(triggered(bool)),SLOT(onRegisterActionTriggered(bool))); regMenu->addAction(action,AG_DEFAULT,false); action = new Action(regMenu); action->setText(tr("Unregister")); action->setIcon(RSR_STORAGE_MENUICONS,MNI_REGISTRATION_REMOVE); action->setData(ADR_STREAM_JID,AStreamJid.full()); action->setData(ADR_SERVICE_JID,ADiscoInfo.contactJid.full()); action->setData(ADR_OPERATION,IRegistration::Unregister); connect(action,SIGNAL(triggered(bool)),SLOT(onRegisterActionTriggered(bool))); regMenu->addAction(action,AG_DEFAULT,false); action = new Action(regMenu); action->setText(tr("Change password")); action->setIcon(RSR_STORAGE_MENUICONS,MNI_REGISTRATION_CHANGE); action->setData(ADR_STREAM_JID,AStreamJid.full()); action->setData(ADR_SERVICE_JID,ADiscoInfo.contactJid.full()); action->setData(ADR_OPERATION,IRegistration::ChangePassword); connect(action,SIGNAL(triggered(bool)),SLOT(onRegisterActionTriggered(bool))); regMenu->addAction(action,AG_DEFAULT,false); return regMenu->menuAction(); } return NULL; }
void Driver::BuildUniversalActions(const ArgList &Args, ActionList &Actions) const { llvm::PrettyStackTraceString CrashInfo("Building actions for universal build"); // Collect the list of architectures. Duplicates are allowed, but // should only be handled once (in the order seen). llvm::StringSet<> ArchNames; llvm::SmallVector<const char *, 4> Archs; for (ArgList::const_iterator it = Args.begin(), ie = Args.end(); it != ie; ++it) { Arg *A = *it; if (A->getOption().getId() == options::OPT_arch) { const char *Name = A->getValue(Args); // FIXME: We need to handle canonicalization of the specified // arch? A->claim(); if (ArchNames.insert(Name)) Archs.push_back(Name); } } // When there is no explicit arch for this platform, make sure we // still bind the architecture (to the default) so that -Xarch_ is // handled correctly. if (!Archs.size()) Archs.push_back(0); // FIXME: We killed off some others but these aren't yet detected in // a functional manner. If we added information to jobs about which // "auxiliary" files they wrote then we could detect the conflict // these cause downstream. if (Archs.size() > 1) { // No recovery needed, the point of this is just to prevent // overwriting the same files. if (const Arg *A = Args.getLastArg(options::OPT_save_temps)) Diag(clang::diag::err_drv_invalid_opt_with_multiple_archs) << A->getAsString(Args); } ActionList SingleActions; BuildActions(Args, SingleActions); // Add in arch binding and lipo (if necessary) for every top level // action. for (unsigned i = 0, e = SingleActions.size(); i != e; ++i) { Action *Act = SingleActions[i]; // Make sure we can lipo this kind of output. If not (and it is an // actual output) then we disallow, since we can't create an // output file with the right name without overwriting it. We // could remove this oddity by just changing the output names to // include the arch, which would also fix // -save-temps. Compatibility wins for now. if (Archs.size() > 1 && !types::canLipoType(Act->getType())) Diag(clang::diag::err_drv_invalid_output_with_multiple_archs) << types::getTypeName(Act->getType()); ActionList Inputs; for (unsigned i = 0, e = Archs.size(); i != e; ++i) Inputs.push_back(new BindArchAction(Act, Archs[i])); // Lipo if necessary, We do it this way because we need to set the // arch flag so that -Xarch_ gets overwritten. if (Inputs.size() == 1 || Act->getType() == types::TY_Nothing) Actions.append(Inputs.begin(), Inputs.end()); else Actions.push_back(new LipoJobAction(Inputs, Act->getType())); } }
void IStrategizer::OnlinePlanExpansionExecution::UpdateActionNode(_In_ IOlcbpPlan::NodeID currentNode, _In_ const WorldClock& clock) { _ASSERTE(IsNodeReady(currentNode)); _ASSERTE(IsActionNode(currentNode)); Action *pAction = (Action*)m_pOlcbpPlan->GetNode(currentNode); if (!IsNodeDone(currentNode)) { _ASSERTE(pAction->GetState() == ESTATE_NotPrepared || pAction->GetState() == ESTATE_Executing || pAction->GetState() == ESTATE_END); if (pAction->GetState() == ESTATE_END) MarkActionAsActive(currentNode); pAction->Update(*g_Game, clock); if (pAction->GetState() == ESTATE_Succeeded) { OnActionNodeSucceeded(currentNode); } else if (pAction->GetState() == ESTATE_Failed) { if (pAction->SleepsCount() < ActionMaxSleepsCount) { LogInfo("%s failed execution, but will reset it and send it to sleep", pAction->ToString().c_str(), pAction->SleepsCount()); pAction->Abort(*g_Game); pAction->Reset(*g_Game, clock); pAction->Sleep(clock, ActionSleepTime); } else { LogInfo("%s failed execution, already tried to sleep it %d time(s) before, failing it", pAction->ToString().c_str(), ActionMaxSleepsCount); OnActionNodeFailed(currentNode); } } } }
void Driver::BuildActions(const ArgList &Args, ActionList &Actions) const { llvm::PrettyStackTraceString CrashInfo("Building compilation actions"); // Start by constructing the list of inputs and their types. // Track the current user specified (-x) input. We also explicitly // track the argument used to set the type; we only want to claim // the type when we actually use it, so we warn about unused -x // arguments. types::ID InputType = types::TY_Nothing; Arg *InputTypeArg = 0; llvm::SmallVector<std::pair<types::ID, const Arg*>, 16> Inputs; for (ArgList::const_iterator it = Args.begin(), ie = Args.end(); it != ie; ++it) { Arg *A = *it; if (isa<InputOption>(A->getOption())) { const char *Value = A->getValue(Args); types::ID Ty = types::TY_INVALID; // Infer the input type if necessary. if (InputType == types::TY_Nothing) { // If there was an explicit arg for this, claim it. if (InputTypeArg) InputTypeArg->claim(); // stdin must be handled specially. if (memcmp(Value, "-", 2) == 0) { // If running with -E, treat as a C input (this changes the // builtin macros, for example). This may be overridden by // -ObjC below. // // Otherwise emit an error but still use a valid type to // avoid spurious errors (e.g., no inputs). if (!Args.hasArg(options::OPT_E, false)) Diag(clang::diag::err_drv_unknown_stdin_type); Ty = types::TY_C; } else { // Otherwise lookup by extension, and fallback to ObjectType // if not found. We use a host hook here because Darwin at // least has its own idea of what .s is. if (const char *Ext = strrchr(Value, '.')) Ty = Host->lookupTypeForExtension(Ext + 1); if (Ty == types::TY_INVALID) Ty = types::TY_Object; } // -ObjC and -ObjC++ override the default language, but only for "source // files". We just treat everything that isn't a linker input as a // source file. // // FIXME: Clean this up if we move the phase sequence into the type. if (Ty != types::TY_Object) { if (Args.hasArg(options::OPT_ObjC)) Ty = types::TY_ObjC; else if (Args.hasArg(options::OPT_ObjCXX)) Ty = types::TY_ObjCXX; } } else { assert(InputTypeArg && "InputType set w/o InputTypeArg"); InputTypeArg->claim(); Ty = InputType; } // Check that the file exists. It isn't clear this is worth // doing, since the tool presumably does this anyway, and this // just adds an extra stat to the equation, but this is gcc // compatible. if (memcmp(Value, "-", 2) != 0 && !llvm::sys::Path(Value).exists()) Diag(clang::diag::err_drv_no_such_file) << A->getValue(Args); else Inputs.push_back(std::make_pair(Ty, A)); } else if (A->getOption().isLinkerInput()) { // Just treat as object type, we could make a special type for // this if necessary. Inputs.push_back(std::make_pair(types::TY_Object, A)); } else if (A->getOption().getId() == options::OPT_x) { InputTypeArg = A; InputType = types::lookupTypeForTypeSpecifier(A->getValue(Args)); // Follow gcc behavior and treat as linker input for invalid -x // options. Its not clear why we shouldn't just revert to // unknown; but this isn't very important, we might as well be // bug comatible. if (!InputType) { Diag(clang::diag::err_drv_unknown_language) << A->getValue(Args); InputType = types::TY_Object; } } } if (!SuppressMissingInputWarning && Inputs.empty()) { Diag(clang::diag::err_drv_no_input_files); return; } // Determine which compilation mode we are in. We look for options // which affect the phase, starting with the earliest phases, and // record which option we used to determine the final phase. Arg *FinalPhaseArg = 0; phases::ID FinalPhase; // -{E,M,MM} only run the preprocessor. if ((FinalPhaseArg = Args.getLastArg(options::OPT_E)) || (FinalPhaseArg = Args.getLastArg(options::OPT_M)) || (FinalPhaseArg = Args.getLastArg(options::OPT_MM))) { FinalPhase = phases::Preprocess; // -{fsyntax-only,-analyze,emit-llvm,S} only run up to the compiler. } else if ((FinalPhaseArg = Args.getLastArg(options::OPT_fsyntax_only)) || (FinalPhaseArg = Args.getLastArg(options::OPT__analyze, options::OPT__analyze_auto)) || (FinalPhaseArg = Args.getLastArg(options::OPT_S))) { FinalPhase = phases::Compile; // -c only runs up to the assembler. } else if ((FinalPhaseArg = Args.getLastArg(options::OPT_c))) { FinalPhase = phases::Assemble; // Otherwise do everything. } else FinalPhase = phases::Link; // Reject -Z* at the top level, these options should never have been // exposed by gcc. if (Arg *A = Args.getLastArg(options::OPT_Z_Joined)) Diag(clang::diag::err_drv_use_of_Z_option) << A->getAsString(Args); // Construct the actions to perform. ActionList LinkerInputs; for (unsigned i = 0, e = Inputs.size(); i != e; ++i) { types::ID InputType = Inputs[i].first; const Arg *InputArg = Inputs[i].second; unsigned NumSteps = types::getNumCompilationPhases(InputType); assert(NumSteps && "Invalid number of steps!"); // If the first step comes after the final phase we are doing as // part of this compilation, warn the user about it. phases::ID InitialPhase = types::getCompilationPhase(InputType, 0); if (InitialPhase > FinalPhase) { // Claim here to avoid the more general unused warning. InputArg->claim(); Diag(clang::diag::warn_drv_input_file_unused) << InputArg->getAsString(Args) << getPhaseName(InitialPhase) << FinalPhaseArg->getOption().getName(); continue; } // Build the pipeline for this file. Action *Current = new InputAction(*InputArg, InputType); for (unsigned i = 0; i != NumSteps; ++i) { phases::ID Phase = types::getCompilationPhase(InputType, i); // We are done if this step is past what the user requested. if (Phase > FinalPhase) break; // Queue linker inputs. if (Phase == phases::Link) { assert(i + 1 == NumSteps && "linking must be final compilation step."); LinkerInputs.push_back(Current); Current = 0; break; } // Some types skip the assembler phase (e.g., llvm-bc), but we // can't encode this in the steps because the intermediate type // depends on arguments. Just special case here. if (Phase == phases::Assemble && Current->getType() != types::TY_PP_Asm) continue; // Otherwise construct the appropriate action. Current = ConstructPhaseAction(Args, Phase, Current); if (Current->getType() == types::TY_Nothing) break; } // If we ended with something, add to the output list. if (Current) Actions.push_back(Current); } // Add a link action if necessary. if (!LinkerInputs.empty()) Actions.push_back(new LinkJobAction(LinkerInputs, types::TY_Image)); }
StateWidget::StateWidget(IChatStates *AChatStates, IMessageWindow *AWindow, QWidget *AParent) : QToolButton(AParent) { FWindow = AWindow; FChatStates = AChatStates; FMultiWindow = qobject_cast<IMultiUserChatWindow *>(AWindow->instance()); FMenu = new Menu(this); QActionGroup *actionGroup = new QActionGroup(FMenu); connect(actionGroup,SIGNAL(triggered(QAction*)),SLOT(onStatusActionTriggered(QAction*))); setMenu(FMenu); Action *permitDefault = new Action(FMenu); permitDefault->setCheckable(true); permitDefault->setText(tr("Default")); permitDefault->setData(ADR_PERMIT_STATUS, IChatStates::StatusDefault); permitDefault->setActionGroup(actionGroup); FMenu->addAction(permitDefault); Action *permitEnable = new Action(FMenu); permitEnable->setCheckable(true); permitEnable->setText(tr("Always send my chat activity")); permitEnable->setData(ADR_PERMIT_STATUS, IChatStates::StatusEnable); permitEnable->setActionGroup(actionGroup); FMenu->addAction(permitEnable); Action *permitDisable = new Action(FMenu); permitDisable->setCheckable(true); permitDisable->setText(tr("Never send my chat activity")); permitDisable->setData(ADR_PERMIT_STATUS, IChatStates::StatusDisable); permitDisable->setActionGroup(actionGroup); FMenu->addAction(permitDisable); connect(FChatStates->instance(),SIGNAL(permitStatusChanged(const Jid &, int)),SLOT(onPermitStatusChanged(const Jid &, int))); connect(FWindow->address()->instance(),SIGNAL(addressChanged(const Jid &, const Jid &)),SLOT(onWindowAddressChanged(const Jid &, const Jid &))); if (FMultiWindow == NULL) { setToolTip(tr("User activity in chat")); connect(FChatStates->instance(),SIGNAL(userChatStateChanged(const Jid &, const Jid &, int)),SLOT(onUserChatStateChanged(const Jid &, const Jid &, int))); }
bool StarTrekEngine::saveOrLoadGameData(Common::SeekableReadStream *in, Common::WriteStream *out, SavegameMetadata *meta) { Common::Serializer ser(in, out); if (ser.isLoading()) { if (_lastGameMode == GAMEMODE_BRIDGE) cleanupBridge(); else // Assume GAMEMODE_AWAYMISSION unloadRoom(); } ser.syncAsUint16LE(_gameMode); // TODO: sub_1d8eb (save) / sub_1d958 (load) (probably bridge / space combat state) Common::String midiFilename = _sound->_loadedMidiFilename; ser.syncString(midiFilename); ser.syncAsSint16LE(_sound->_loopingMidiTrack); if (ser.isLoading()) { if (midiFilename.empty()) _sound->clearAllMidiSlots(); else { _sound->loadMusicFile(midiFilename); _sound->playMidiMusicTracks(_sound->_loopingMidiTrack, _sound->_loopingMidiTrack); } } ser.syncAsUint16LE(_frameIndex); ser.syncAsUint16LE(_mouseControllingShip); // TODO: word_45aa8 // TODO: word_45aaa // TODO: word_45aac // TODO: word_5082e // TODO: dword_519b0 // TODO: word_45ab2 // TODO: word_45ab4 // TODO: word_45ab8 ser.syncString(_missionToLoad); // TODO: word_4b032 // TODO: word_519bc // TODO: word_45c5c // TODO: unk_52afe ser.syncString(_sound->_loopingAudioName); if (ser.isLoading()) { if (!_sound->_loopingAudioName.empty()) _sound->playVoc(_sound->_loopingAudioName); } // TODO: word_45a50 for (int i = 0; i < NUM_OBJECTS; i++) { ser.syncAsByte(_itemList[i].have); } if (_gameMode == GAMEMODE_AWAYMISSION) { ser.syncString(_missionName); ser.syncAsSint16LE(_roomIndex); if (ser.isLoading()) { _gfx->fadeoutScreen(); _txtFilename = "ground"; // This must be done before loading the actor variables, since this clears // them. loadRoom(_missionName, _roomIndex); } ser.syncAsUint32LE(_roomFrameCounter); ser.syncAsUint32LE(_frameIndex); // FIXME: redundant // Serialize the "actor" class for (int i = 0; i < NUM_ACTORS; i++) { Actor *a = &_actorList[i]; ser.syncAsUint16LE(a->spriteDrawn); ser.syncBytes((byte *)a->animFilename, 16); ser.syncAsUint16LE(a->animType); a->sprite.saveLoadWithSerializer(ser); ser.syncBytes((byte *)a->bitmapFilename, 10); a->scale.saveLoadWithSerializer(ser); // Can't save "animFile" (will be reloaded) ser.syncAsUint16LE(a->numAnimFrames); ser.syncAsUint16LE(a->animFrame); ser.syncAsUint32LE(a->frameToStartNextAnim); ser.syncAsSint16LE(a->pos.x); ser.syncAsSint16LE(a->pos.y); ser.syncAsUint16LE(a->field60); ser.syncAsUint16LE(a->field62); ser.syncAsUint16LE(a->triggerActionWhenAnimFinished); ser.syncAsUint16LE(a->finishedAnimActionParam); ser.syncBytes((byte *)a->animationString2, 8); ser.syncAsUint16LE(a->field70); ser.syncAsUint16LE(a->field72); ser.syncAsUint16LE(a->field74); ser.syncAsUint16LE(a->field76); ser.syncAsSint16LE(a->iwSrcPosition); ser.syncAsSint16LE(a->iwDestPosition); a->granularPosX.saveLoadWithSerializer(ser); a->granularPosY.saveLoadWithSerializer(ser); a->speedX.saveLoadWithSerializer(ser); a->speedY.saveLoadWithSerializer(ser); ser.syncAsSint16LE(a->dest.x); ser.syncAsSint16LE(a->dest.y); ser.syncAsUint16LE(a->field90); ser.syncAsByte(a->field92); ser.syncAsByte(a->direction); ser.syncAsUint16LE(a->field94); ser.syncAsUint16LE(a->field96); ser.syncBytes((byte *)a->animationString, 10); ser.syncAsUint16LE(a->fielda2); ser.syncAsUint16LE(a->fielda4); ser.syncAsUint16LE(a->fielda6); } ser.syncString(_mapFilename); // Away mission struct for (int i = 0; i < 8; i++) ser.syncAsSint16LE(_awayMission.timers[i]); ser.syncAsSint16LE(_awayMission.mouseX); ser.syncAsSint16LE(_awayMission.mouseY); for (int i = 0; i < 4; i++) ser.syncAsSint16LE(_awayMission.crewGetupTimers[i]); ser.syncAsByte(_awayMission.disableWalking); ser.syncAsByte(_awayMission.disableInput); ser.syncAsByte(_awayMission.redshirtDead); ser.syncAsByte(_awayMission.activeAction); ser.syncAsByte(_awayMission.activeObject); ser.syncAsByte(_awayMission.passiveObject); ser.syncAsByte(_awayMission.rdfStillDoDefaultAction); ser.syncAsByte(_awayMission.crewDownBitset); for (int i = 0; i < 4; i++) ser.syncAsByte(_awayMission.crewDirectionsAfterWalk[i]); if (_missionName == "DEMON") { _awayMission.demon.saveLoadWithSerializer(ser); _room->_roomVar.demon.saveLoadWithSerializer(ser); } else if (_missionName == "TUG") { _awayMission.tug.saveLoadWithSerializer(ser); _room->_roomVar.tug.saveLoadWithSerializer(ser); } else if (_missionName == "LOVE") { _awayMission.love.saveLoadWithSerializer(ser); _room->_roomVar.love.saveLoadWithSerializer(ser); } else if (_missionName == "MUDD") { _awayMission.mudd.saveLoadWithSerializer(ser); _room->_roomVar.mudd.saveLoadWithSerializer(ser); } else if (_missionName == "FEATHER") { _awayMission.feather.saveLoadWithSerializer(ser); _room->_roomVar.feather.saveLoadWithSerializer(ser); } else if (_missionName == "TRIAL") { _awayMission.trial.saveLoadWithSerializer(ser); _room->_roomVar.trial.saveLoadWithSerializer(ser); } else if (_missionName == "SINS") { _awayMission.sins.saveLoadWithSerializer(ser); _room->_roomVar.sins.saveLoadWithSerializer(ser); } // The action queue if (ser.isLoading()) { _actionQueue = Common::Queue<Action>(); int16 n = 0; ser.syncAsSint16LE(n); for (int i = 0; i < n; i++) { Action a; a.saveLoadWithSerializer(ser); _actionQueue.push(a); } } else { // Saving int16 n = _actionQueue.size(); ser.syncAsSint16LE(n); for (int i = 0; i < n; i++) { Action a = _actionQueue.pop(); a.saveLoadWithSerializer(ser); _actionQueue.push(a); } } // Original game located changes in RDF files and saved them. Since RDF files // aren't modified directly here, that's skipped. ser.syncAsSint16LE(_objectHasWalkPosition); ser.syncAsSint16LE(_objectWalkPosition.x); ser.syncAsSint16LE(_objectWalkPosition.y); for (int i = 0; i < MAX_BUFFERED_WALK_ACTIONS; i++) { _actionOnWalkCompletion[i].saveLoadWithSerializer(ser); ser.syncAsByte(_actionOnWalkCompletionInUse[i]); } ser.syncAsSint16LE(_warpHotspotsActive); } return true; }
void RemapDialog::loadKeymap() { _currentActions.clear(); const Stack<Keymapper::MapRecord> &activeKeymaps = _keymapper->getActiveStack(); if (!activeKeymaps.empty() && _kmPopUp->getSelected() == 0) { // load active keymaps List<const HardwareKey*> freeKeys(_keymapper->getHardwareKeys()); // add most active keymap's keys Keymapper::MapRecord top = activeKeymaps.top(); List<Action*>::iterator actIt; for (actIt = top.keymap->getActions().begin(); actIt != top.keymap->getActions().end(); ++actIt) { Action *act = *actIt; ActionInfo info = {act, false, act->description}; _currentActions.push_back(info); if (act->getMappedKey()) freeKeys.remove(act->getMappedKey()); } // loop through remaining finding mappings for unmapped keys if (top.inherit) { for (int i = activeKeymaps.size() - 2; i >= 0; --i) { Keymapper::MapRecord mr = activeKeymaps[i]; List<const HardwareKey*>::iterator keyIt = freeKeys.begin(); while (keyIt != freeKeys.end()) { Action *act = mr.keymap->getMappedAction((*keyIt)->key); if (act) { ActionInfo info = {act, true, act->description + " (" + mr.keymap->getName() + ")"}; _currentActions.push_back(info); freeKeys.erase(keyIt++); } else { ++keyIt; } } if (mr.inherit == false || freeKeys.empty()) break; } } } else if (_kmPopUp->getSelected() != -1) { Keymap *km = _keymapTable[_kmPopUp->getSelectedTag()]; List<Action*>::iterator it; for (it = km->getActions().begin(); it != km->getActions().end(); ++it) { ActionInfo info = {*it, false, (*it)->description}; _currentActions.push_back(info); } } // refresh scroll bar _scrollBar->_currentPos = 0; _scrollBar->_numEntries = (_currentActions.size() + _colCount - 1) / _colCount; _scrollBar->recalc(); // force refresh _topAction = -1; refreshKeymap(); }