TabHistoryContentsWidget::TabHistoryContentsWidget(const QVariantMap ¶meters, QWidget *parent) : ContentsWidget(parameters, nullptr, parent), m_window(nullptr), m_ui(new Ui::TabHistoryContentsWidget) { m_ui->setupUi(this); m_ui->filterLineEditWidget->setClearOnEscape(true); m_ui->historyViewWidget->setModel(new QStandardItemModel(this)); m_ui->historyViewWidget->viewport()->installEventFilter(this); m_ui->historyViewWidget->viewport()->setMouseTracking(true); const MainWindow *mainWindow(MainWindow::findMainWindow(parentWidget())); if (mainWindow) { m_window = mainWindow->getActiveWindow(); connect(mainWindow, &MainWindow::currentWindowChanged, this, [=]() { Window *window(mainWindow->getActiveWindow()); if (window != m_window) { if (m_window) { disconnect(m_window, &Window::loadingStateChanged, this, &TabHistoryContentsWidget::updateHistory); } m_window = window; if (window) { connect(window, &Window::loadingStateChanged, this, &TabHistoryContentsWidget::updateHistory); } } updateHistory(); }); } updateHistory(); connect(m_ui->filterLineEditWidget, &LineEditWidget::textChanged, m_ui->historyViewWidget, &ItemViewWidget::setFilterString); connect(m_ui->historyViewWidget, &ItemViewWidget::customContextMenuRequested, this, &TabHistoryContentsWidget::showContextMenu); connect(m_ui->historyViewWidget, &ItemViewWidget::clicked, [&](const QModelIndex &index) { if (m_window && m_window->getWebWidget()) { m_window->triggerAction(ActionsManager::GoToHistoryIndexAction, {{QLatin1String("index"), index.row()}}); } }); }
END_TEST START_TEST(Server_HistorizingUpdateUpdate) { UA_HistoryDataBackend backend = UA_HistoryDataBackend_Memory(1, 1); UA_HistorizingNodeIdSettings setting; setting.historizingBackend = backend; setting.maxHistoryDataResponseSize = 1000; setting.historizingUpdateStrategy = UA_HISTORIZINGUPDATESTRATEGY_USER; serverMutexLock(); UA_StatusCode ret = gathering->registerNodeId(server, gathering->context, &outNodeId, setting); serverMutexUnlock(); ck_assert_str_eq(UA_StatusCode_name(ret), UA_StatusCode_name(UA_STATUSCODE_GOOD)); // fill backend with insert ck_assert_str_eq(UA_StatusCode_name(updateHistory(UA_PERFORMUPDATETYPE_INSERT, testData, NULL, NULL)) , UA_StatusCode_name(UA_STATUSCODE_GOOD)); testResult(testDataSorted, NULL); // delete some values ck_assert_str_eq(UA_StatusCode_name(deleteHistory(DELETE_START_TIME, DELETE_STOP_TIME)), UA_StatusCode_name(UA_STATUSCODE_GOOD)); testResult(testDataAfterDelete, NULL); // update all and insert some UA_StatusCode *result; size_t resultSize = 0; ck_assert_str_eq(UA_StatusCode_name(updateHistory(UA_PERFORMUPDATETYPE_UPDATE, testDataSorted, &result, &resultSize)) , UA_StatusCode_name(UA_STATUSCODE_GOOD)); for (size_t i = 0; i < resultSize; ++i) { ck_assert_str_eq(UA_StatusCode_name(result[i]), UA_StatusCode_name(testDataUpdateResult[i])); } UA_Array_delete(result, resultSize, &UA_TYPES[UA_TYPES_STATUSCODE]); UA_HistoryData data; UA_HistoryData_init(&data); testResult(testDataSorted, &data); for (size_t i = 0; i < data.dataValuesSize; ++i) { ck_assert_uint_eq(data.dataValues[i].hasValue, true); ck_assert(data.dataValues[i].value.type == &UA_TYPES[UA_TYPES_INT64]); ck_assert_uint_eq(*((UA_Int64*)data.dataValues[i].value.data), UA_PERFORMUPDATETYPE_UPDATE); } UA_HistoryData_deleteMembers(&data); UA_HistoryDataBackend_Memory_deleteMembers(&setting.historizingBackend); }
//--------------------------------------------------------------- void reference(int procNum, int vpn) { currProcIdx = getValidProcIndex(procNum, 0); // if( page number is out of bounds ) if(vpn < 1 || vpn > getAddrSpaceSize(currProcIdx)){ fprintf(stderr, "[Error] Page number out of bounds\n"); fprintf(stderr, " Please use a valid input file\n"); cleanUp(); exit(1); } // if( page is not in memory ) if(!pageInMem(currProcIdx, vpn)){ // if( memory is full ) if(!freePages){ // evict a page switch(policy){ case 0: replaceLRU(); break; case 1: replaceRandom(); break; case 2: replaceNFU(); } } storePage(currProcIdx, vpn); numFaults++; } updateHistory(procNum, vpn); numRefs++; if(DBG) printf("Free frames: %d\n", freePages); if(DBG) printf("Faults( %d ), References( %d ) -> Fault rate( %.4f )\n\n", numFaults, numRefs, (double)numFaults/numRefs); }
YCursor YLineSearch::forward(const QString& ch, bool& found, unsigned int times) { YCursor cur = mView->getLineColumnCursor(); int x = cur.x() + 1; // Start search after cursor pos int y = cur.y(); const QString& current = mView->buffer()->textline(y); int index = 0; unsigned int nfound = 0; while(nfound < times && x < current.length()) { index = current.indexOf(ch, x); if(index < 0) { break; } x = index + 1; nfound++; } YCursor pos; found = (nfound == times); if(found) { pos.setX(x - 1); pos.setY(y); } updateHistory(ch, SearchForward); return pos; }
void loadHistory(){ char loadPath[MAX]; strcpy(loadPath, home); strcat(loadPath, "/history.hist_list"); printf("\n\n %s \n\n", loadPath); FILE *fp; char line[MAX]; char *p; int i; for (i = 0; i < 20; i++) { history[i][0] = '\0'; } if( (fp = fopen(loadPath, "r")) != NULL){ //find or create file while(1) { printf("history loaded"); if( (fgets(line, MAX, fp)) == NULL) //end of file check break; else if ( (p = strchr(line, '\n')) != NULL) *p = '\0'; updateHistory(line); } fclose(fp); } } //end loadHistory()
float PIDController::update(float measuredValue, float dt, bool resetAccumulator) { const float error = getMeasuredValueSetpoint() - measuredValue; // Sign is the direction we want measuredValue to go. Positive means go higher. const float p = getKP() * error; // term is Proportional to error const float accumulatedError = glm::clamp(error * dt + (resetAccumulator ? 0 : _lastAccumulation), // integrate error getAccumulatedValueLowLimit(), // but clamp by anti-windup limits getAccumulatedValueHighLimit()); const float i = getKI() * accumulatedError; // term is Integral of error const float changeInError = (error - _lastError) / dt; // positive value denotes increasing deficit const float d = getKD() * changeInError; // term is Derivative of Error const float computedValue = glm::clamp(p + i + d, getControlledValueLowLimit(), getControlledValueHighLimit()); if (getIsLogging()) { // if logging/reporting updateHistory(measuredValue, dt, error, accumulatedError, changeInError, p, i, d, computedValue); } Q_ASSERT(!glm::isnan(computedValue)); // update state for next time _lastError = error; _lastAccumulation = accumulatedError; return computedValue; }
void loadHistory(){ FILE *fp; char line[MAX]; char *p; for (int i = 0; i < 20; i++) { history[i][0] = '\0'; } if( (fp = fopen("/home/student/f/fsb15182/history.hist_list", "r")) != NULL){ //find or create file while(1) { printf("history loaded"); if( (fgets(line, MAX, fp)) == NULL) //end of file check break; else if ( (p = strchr(line, '\n')) != NULL) *p = '\0'; updateHistory(line); } fclose(fp); } } //end loadHistory()
bool GuiTextEditCtrl::dealWithEnter( bool clearResponder ) { //first validate if (mProfile->mReturnTab) { onLoseFirstResponder(); } updateHistory(&mTextBuffer, true); mHistoryDirty = false; //next exec the alt console command execAltConsoleCallback(); // Notify of Return onReturn_callback(); if (mProfile->mReturnTab) { GuiCanvas *root = getRoot(); if (root) { root->tabNext(); return true; } } if( clearResponder ) clearFirstResponder(); return true; }
void DialogueWindow::setKeywords(std::list<std::string> keyWords) { mTopicsList->clear(); for (std::map<std::string, Link*>::iterator it = mTopicLinks.begin(); it != mTopicLinks.end(); ++it) delete it->second; mTopicLinks.clear(); mKeywordSearch.clear(); bool isCompanion = !mPtr.getClass().getScript(mPtr).empty() && mPtr.getRefData().getLocals().getIntVar(mPtr.getClass().getScript(mPtr), "companion"); bool anyService = mServices > 0 || isCompanion || mPtr.getTypeName() == typeid(ESM::NPC).name(); const MWWorld::Store<ESM::GameSetting> &gmst = MWBase::Environment::get().getWorld()->getStore().get<ESM::GameSetting>(); if (mPtr.getTypeName() == typeid(ESM::NPC).name()) mTopicsList->addItem(gmst.find("sPersuasion")->getString()); if (mServices & Service_Trade) mTopicsList->addItem(gmst.find("sBarter")->getString()); if (mServices & Service_BuySpells) mTopicsList->addItem(gmst.find("sSpells")->getString()); if (mServices & Service_Travel) mTopicsList->addItem(gmst.find("sTravel")->getString()); if (mServices & Service_CreateSpells) mTopicsList->addItem(gmst.find("sSpellmakingMenuTitle")->getString()); if (mServices & Service_Enchant) mTopicsList->addItem(gmst.find("sEnchanting")->getString()); if (mServices & Service_Training) mTopicsList->addItem(gmst.find("sServiceTrainingTitle")->getString()); if (mServices & Service_Repair) mTopicsList->addItem(gmst.find("sRepair")->getString()); if (isCompanion) mTopicsList->addItem(gmst.find("sCompanionShare")->getString()); if (anyService) mTopicsList->addSeparator(); for(std::list<std::string>::iterator it = keyWords.begin(); it != keyWords.end(); ++it) { mTopicsList->addItem(*it); Topic* t = new Topic(*it); mTopicLinks[Misc::StringUtils::lowerCase(*it)] = t; mKeywordSearch.seed(Misc::StringUtils::lowerCase(*it), intptr_t(t)); } mTopicsList->adjustSize(); updateHistory(); }
//-------------------------------------------------------------- void DatumHistorian::updateHistoryWhileClampingOutliers (float newval){ if ((bRunningAverageRequested == false) || (historyLength < 10)){ updateHistory(newval); } else { // store what may or may not become our new value. float newvalChecked = newval; // if the incoming newval differs by an absolute percentage in 0..1, don't accept it. float maxAcceptableAbsoluteChange = 0.10; float newvalDelta = fabs(newval - history[0]); if (newvalDelta > maxAcceptableAbsoluteChange){ // instead, clamp it to the maxAcceptableAbsoluteChange. float sign = ((newval - history[0]) < 0) ? -1 : 1; newvalChecked = history[0] + sign*maxAcceptableAbsoluteChange; newvalChecked = MAX(0, MIN(1, newvalChecked)); } // push all of the data down the array. for (int i=(maxHistoryLength-1); i>0; i--){ history[i] = history[i-1]; } // calculate the standard deviation of the derivatives (differences) // of the history array. If the current value represents too big a jump from // the previous value, just copy (the previous value + an estimation of velocity). history[0] = newvalChecked; // update overall properties historyLength = MIN(maxHistoryLength, historyLength+1); } }
void DialogueWindow::goodbye() { mLinks.push_back(new Goodbye()); mGoodbye = true; mTopicsList->setEnabled(false); mEnabled = false; updateHistory(); }
YCursor YLineSearch::forwardBefore(const QString& ch, bool& found, unsigned int times) { YCursor pos = forward(ch, found, times); if(found) { pos.setX(pos.x() - 1); } updateHistory(ch, SearchForwardBefore); return pos; }
void ScreenshotManager::uploadDone(const QString &fileName, const QString &url, const QString &deleteHash) { for (Screenshot *screenshot : qAsConst(mScreenshots)) { if (screenshot->options().fileName == fileName || screenshot->unloadedFileName() == fileName) { screenshot->uploadDone(url); if (screenshot->options().file) { updateHistory(fileName, url, deleteHash); } else { saveHistory("", url, deleteHash); } return; } } // If we get here, it's because the screenshot upload wasn't on the current screenshot list, which means it's a View History/Upload Later upload. updateHistory(fileName, url, deleteHash); }
void UltraGridMainWindow::doStart() { if(!started) { pushButton_start->setText("Stop"); started = true; statusBar.showMessage("Running"); QHash<QString, QString> sett = settings.getSettings(); QString command("uv "); if(sett.find("audio_cap") != sett.end()) command += "-s " + sett.find("audio_cap").value(); command += + " "; if(sett.find("audio_play") != sett.end()) command += "-r " + sett.find("audio_play").value(); command += + " "; if(sett.find("display") != sett.end()) { command += "-d " + sett.find("display").value(); if(sett.find("display_details") != sett.end()) command += ":" + sett.find("display_details").value(); } command += + " "; if(sett.find("capture") != sett.end()) { command += "-t " + sett.find("capture").value(); if(sett.find("capture_details") != sett.end()) command += ":" + sett.find("capture_details").value(); } command += + " "; if(sett.find("mtu") != sett.end()) command += "-m " + sett.find("mtu").value(); command += + " "; if(sett.find("compress") != sett.end()) { command += sett.find("compress").value(); if(sett.find("compress").value().compare("JPEG") == 0 && sett.find("compress_jpeg_quality") != sett.end()) { command += ":" + sett.find("compress_jpeg_quality").value(); } } command += + " "; if(sett.find("other") != sett.end()) command += sett.find("other").value(); command += + " "; history.insert(address->text()); updateHistory(); command += address->text(); process.setProcessChannelMode(QProcess::MergedChannels); process.start(command); } else { process.kill(); } }
YCursor YLineSearch::reverseAfter(const QString& ch, bool& found, unsigned int times) { YCursor pos = reverse(ch, found, times); if(found) { pos.setX(pos.x() + 1); } updateHistory(ch, SearchBackwardAfter); return pos; }
BOOL LoginDialog::onInitDialog() { setControlById(m_server, IDC_CSERVER); setControlById(m_listening, IDC_LISTENING); setControlById(m_ok, IDOK); updateHistory(); SetForegroundWindow(getControl()->getWindow()); m_server.setFocus(); if (m_isListening) { m_listening.setEnabled(false); } return TRUE; }
/* function: printItem Input: 1. node: the node the data item is in. 2. i: the index in node that data item is in. Returns: 0 on complete. (value not used) Prints item code, desc, and profit fields for report. Updates history of items that did not sell in current month. Sets profit back to 0 so data is ready for next months transactions. */ int printItem(struct Node *node, int i){ //item had no sale for the month if(node->data[i].profit == 0){ updateHistory(&(node->data[i]), 0); } printf("%s:%s Sales: $%.2f\n", node->data[i].code, node->data[i].desc, node->data[i].profit); node->data[i].profit = 0; return 0; }
/* function: itemChange Input: 1. action: action to be perfomed. 2. code: item changed by action. 3. line: original line from transaction file. 4. linepos: position in line after transaction type and item code. Return: 0 on complete. (value not used) Handles sales, delivery, and price changes for items. Part (a): Search for the item in question. Part (b): If the action is not a price change pull out amount of sale or delivery for use. Part (c): Perform correct transaction based on action input. - Sale: Item's stock is updated and the profit field of the item is calculated based on current price. - Delivery: Item's stock is updated. - Price change: function changePrice is called to handle change. Uses saveNode(), and getNode() from btree.c */ int itemChange(char *action, char *code, char *line, int linepos){ int j = 0; int newStock; int datapos; char amount[4]; struct Node root; struct Node node; getNode(0, &root); //Part (a) if ((datapos = search(&root, code, &node)) == -1){ printf("ERROR: No item with code %s. Cannot complete %s.\n", code, action); return 0; } // Part (b) if (strcmp(action, "PRICE") != 0){ linepos++; while(line[linepos] != '\0'){ amount[j] = line[linepos]; j++; linepos++; } line[linepos] = '\0'; } //Part (c) if (strcmp(action, "SALE") == 0){ newStock = (node.data[datapos].stock) - atoi(amount); if (newStock < 0){ printf("ERROR: Quantity Sold of item %s is greater than current stock.\n", code); }else{ node.data[datapos].stock = newStock; updateHistory(&(node.data[datapos]), atoi(amount)); updateSales(&(node.data[datapos]), atoi(amount)); } }else if (strcmp(action, "DELIVERY") == 0){ newStock = (node.data[datapos].stock) + atoi(amount); node.data[datapos].stock = newStock; }else{ changePrice(line, &node, datapos, linepos); } saveNode(&node); return 0; }
foreach (Screenshot* screenshot, mScreenshots) { if (screenshot->options().fileName == fileName || screenshot->unloadedFileName() == fileName) { screenshot->uploadDone(url); if (screenshot->options().file) { updateHistory(fileName, url, deleteHash); } else { saveHistory("", url, deleteHash); } return; } }
void QblDesktopChat::messageReceived(std::string contact, std::list<QblJsonChatMessageComplete> history) { std::list<QblDesktopChatContent *>::iterator iterator; for (iterator = chats.begin(); iterator != chats.end(); iterator++) { if (! (*iterator)->getRecipient()->getAlias().compare(contact)) { emit(updateHistory(history)); } } if(this->isVisible() == false) { emit(addToTopInfo()); } return; }
Eigen::Matrix4f CollarLinesRegistrationPipeline::runRegistration(const VelodynePointCloud &target_cloud, Mat &covariance) { PolarGridOfClouds::Ptr target_polar_grid = PolarGridOfClouds::of(target_cloud); Eigen::Matrix4f transformation; if(!history.empty()) { pickBestByAverage(runRegistrationEffective(target_polar_grid), transformation, covariance); estimation.addMeassurement(transformation); } else { transformation = Eigen::Matrix4f::Identity(); covariance = cv::Mat::zeros(6, 6, CV_64FC1); } updateHistory(target_polar_grid, transformation); pose_index++; return transformation; }
void QblDesktopChat::onContactClicked(QblJsonMainConfigIdentity *identity, QblJsonMainConfigContact *contact) { QblDesktopChatContent *oldContent; std::list<QblJsonChatMessageComplete> history; std::list<QblDesktopChatContent *>::iterator iterator; Qbl *qbl; oldContent = this->content; this->content = NULL; for (iterator = chats.begin(); iterator != chats.end(); iterator++) { uint8_t compareSender, compareRecipient; compareSender = (*iterator)->getSender()->compare(identity); compareRecipient = (*iterator)->getRecipient()->compare(contact); if (QblJsonObject::isUuidEqual(compareSender) && QblJsonObject::isUuidEqual(compareRecipient)) { this->content = *iterator; break; } } if (this->content == NULL) { this->content = new QblDesktopChatContent(identity, contact, this->ui->frContentField); this->chats.push_back(this->content); } this->content->resize(this->ui->frContentField->width(), this->ui->frContentField->height()); this->content->show(); qRegisterMetaType<std::list<QblJsonChatMessageComplete>>("std::list<QblJsonChatMessageComplete>"); connect(this, SIGNAL(updateHistory(std::list<QblJsonChatMessageComplete>)), this->content, SLOT(historyIsUpdated(std::list<QblJsonChatMessageComplete>))); qbl = Qbl::getInstance(); history = qbl->getChatHistory()->getHistory(contact); this->content->setHistory(history); if (oldContent != NULL) { oldContent->hide(); } return; }
// accept a time step into the solution history void e_trsolver::acceptstep_sync() { statIterations += iterations; if (--convError < 0) convHelper = 0; // Now advance in time or not... if (running > 1) { adjustDelta_sync (current); // deltaOld = delta; // stepDelta = deltaOld; // nextStates (); // rejected = 0; adjustOrder (); } else { fillStates (); nextStates (); rejected = 0; } saveCurrent = current; current += delta; running++; converged++; // Tell integrators to be running. setMode (MODE_NONE); // Initialize or update history. if (running > 1) { // update the solution history with the new results updateHistory (current); } else { // we have just solved the first transient state initHistory (current); } // store the current time lastsynctime = current; }
bool insertIntoTree(Edge *edge) { Witness *newWitness = new Witness(edge, edge); auto nearest = witnessInterface.nearestWithin(newWitness, radius); bool didAddNewEdge = false; if(nearest.elements.size() == 0 || nearest.distances[0] > radius) { witnessInterface.insertIntoTree(newWitness); insertionInterface.insertIntoTree(edge); didAddNewEdge = true; } else { Witness *witnessNode = nearest.elements[0]; Edge *prevBest = witnessNode->edge; //make sure the previous best is still in the tree if(prevBest->getPointIndex() != 0 && edge->gCost() < prevBest->gCost()) { tree[prevBest->parent].erase(prevBest); removeSubtree(prevBest); witnessNode->edge = edge; insertionInterface.insertIntoTree(edge); didAddNewEdge = true; } } if(didAddNewEdge) { if(tree.find(edge->parent) == tree.end()) { tree[edge->parent] = std::unordered_set<Edge*>(); } tree[edge->parent].insert(edge); } double failureRate = updateHistory(didAddNewEdge); if(historyFilled && failureRate >= resizeThreshold) { radius *= 0.5; resetHistory(); } return didAddNewEdge; }
void GestureMoveEventFilter::filter(GestureTouchEvent *ev) { if (!ev) return; if (m_moveThreshold <= 0) return; if (ev->type == GestureTouchEvent::TouchStart) { if (ev->numTouchPoints == 1) m_trackMovement = true; updateHistory(ev); } else if (ev->type == GestureTouchEvent::TouchMove && m_trackMovement) { bool aboveThreshold = false; unsigned int a = 0, b = 0; while (!aboveThreshold && a < m_numTouchPoints && b < ev->numTouchPoints) { // Compare the correct finger ids while (m_touchPoints[a].id < ev->touchPoints[b].id) a++; while (m_touchPoints[a].id > ev->touchPoints[b].id) b++; int diff = abs(m_touchPoints[a].x - ev->touchPoints[b].x) + abs(m_touchPoints[a].y - ev->touchPoints[b].y); if (diff > m_moveThreshold) aboveThreshold = true; a++; b++; } if (aboveThreshold) { ev->flags &= ~GestureTouchEvent::GESTURE_EVENT_TINY_MOVE; m_trackMovement = false; } else { ev->flags |= GestureTouchEvent::GESTURE_EVENT_TINY_MOVE; } } }
void DialogueWindow::addResponse(const std::string &text, const std::string &title) { // This is called from the dialogue manager, so text is // case-smashed - thus we have to retrieve the correct case // of the title through the topic list. std::string realTitle = title; if (realTitle != "") { for (size_t i=0; i<mTopicsList->getItemCount(); ++i) { std::string item = mTopicsList->getItemNameAt(i); if (Misc::StringUtils::ciEqual(item, title)) { realTitle = item; break; } } } mHistoryContents.push_back(new Response(text, realTitle)); updateHistory(); }
void ofxSceneManager::update( float dt ){ if ( !curtain.isReady() ){ //curtain is busy, so we are pre or post transition curtain.update(dt); if ( curtain.hasReachedBottom() ){ currentScene->sceneDidDisappear(futureScene); futureScene->sceneWillAppear(currentScene); updateHistory( futureScene ); currentScene = futureScene; futureScene = NULL; } if ( curtain.hasReachedTop() ){ currentScene->sceneDidAppear(); } }else{ futureScene = NULL; } if (currentScene != NULL){ vector <ofxScene*> screensToUpdate; screensToUpdate.push_back(currentScene); if (overlapUpdate){ if (futureScene != NULL){ screensToUpdate.push_back(futureScene); } } for (int i = 0; i < screensToUpdate.size(); i++){ ofxScene * s = screensToUpdate[i]; s->update(dt); } } }
YCursor YLineSearch::reverse(const QString& ch, bool& found, unsigned int times) { YCursor cur = mView->getLineColumnCursor(); unsigned int x = cur.x(); unsigned int y = cur.y(); if(x) { x--; // Start search before current cursor } const QString& current = mView->buffer()->textline(y); int index = 0; unsigned int nfound = 0; while(nfound < times && x > 0) { index = current.lastIndexOf(ch, x); if(index < 0) { break; } x = index - 1; nfound++; } YCursor pos; found = (nfound == times); if(found) { pos.setX(x + 1); pos.setY(y); } updateHistory(ch, SearchBackward); return pos; }
bool GuiTextEditCtrl::onKeyDown(const GuiEvent &event) { if ( !isActive() || !isAwake() ) return false; S32 stringLen = mTextBuffer.length(); setUpdate(); // Ugly, but now I'm cool like MarkF. if(event.keyCode == KEY_BACKSPACE) goto dealWithBackspace; if ( event.modifier & SI_SHIFT ) { // Added support for word jump selection. if ( event.modifier & SI_CTRL ) { switch ( event.keyCode ) { case KEY_LEFT: { S32 newpos = findPrevWord(); if ( mBlockStart == mBlockEnd ) { // There was not already a selection so start a new one. mBlockStart = newpos; mBlockEnd = mCursorPos; } else { // There was a selection already... // In this case the cursor MUST be at either the // start or end of that selection. if ( mCursorPos == mBlockStart ) { // We are at the start block and traveling left so // just extend the start block farther left. mBlockStart = newpos; } else { // We are at the end block BUT traveling left // back towards the start block... if ( newpos > mBlockStart ) { // We haven't overpassed the existing start block // so just trim back the end block. mBlockEnd = newpos; } else if ( newpos == mBlockStart ) { // We are back at the start, so no more selection. mBlockEnd = mBlockStart = 0; } else { // Only other option, we just backtracked PAST // our original start block. // So the new position becomes the start block // and the old start block becomes the end block. mBlockEnd = mBlockStart; mBlockStart = newpos; } } } mCursorPos = newpos; return true; } case KEY_RIGHT: { S32 newpos = findNextWord(); if ( mBlockStart == mBlockEnd ) { // There was not already a selection so start a new one. mBlockStart = mCursorPos; mBlockEnd = newpos; } else { // There was a selection already... // In this case the cursor MUST be at either the // start or end of that selection. if ( mCursorPos == mBlockEnd ) { // We are at the end block and traveling right so // just extend the end block farther right. mBlockEnd = newpos; } else { // We are at the start block BUT traveling right // back towards the end block... if ( newpos < mBlockEnd ) { // We haven't overpassed the existing end block // so just trim back the start block. mBlockStart = newpos; } else if ( newpos == mBlockEnd ) { // We are back at the end, so no more selection. mBlockEnd = mBlockStart = 0; } else { // Only other option, we just backtracked PAST // our original end block. // So the new position becomes the end block // and the old end block becomes the start block. mBlockStart = mBlockEnd; mBlockEnd = newpos; } } } mCursorPos = newpos; return true; } default: break; } } // End support for word jump selection. switch ( event.keyCode ) { case KEY_TAB: if ( mTabComplete ) { onTabComplete_callback("1"); return true; } break; // We don't want to fall through if we don't handle the TAB here. case KEY_HOME: mBlockStart = 0; mBlockEnd = mCursorPos; mCursorPos = 0; return true; case KEY_END: mBlockStart = mCursorPos; mBlockEnd = stringLen; mCursorPos = stringLen; return true; case KEY_LEFT: if ((mCursorPos > 0) & (stringLen > 0)) { //if we already have a selected block if (mCursorPos == mBlockEnd) { mCursorPos--; mBlockEnd--; if (mBlockEnd == mBlockStart) { mBlockStart = 0; mBlockEnd = 0; } } else { mCursorPos--; mBlockStart = mCursorPos; if (mBlockEnd == 0) { mBlockEnd = mCursorPos + 1; } } } return true; case KEY_RIGHT: if (mCursorPos < stringLen) { if ((mCursorPos == mBlockStart) && (mBlockEnd > 0)) { mCursorPos++; mBlockStart++; if (mBlockStart == mBlockEnd) { mBlockStart = 0; mBlockEnd = 0; } } else { if (mBlockEnd == 0) { mBlockStart = mCursorPos; mBlockEnd = mCursorPos; } mCursorPos++; mBlockEnd++; } } return true; case KEY_RETURN: case KEY_NUMPADENTER: return dealWithEnter(false); default: break; } } else if (event.modifier & SI_CTRL) { switch(event.keyCode) { #if defined(TORQUE_OS_MAC) // Added UNIX emacs key bindings - just a little hack here... // Ctrl-B - move one character back case KEY_B: { GuiEvent new_event; new_event.modifier = 0; new_event.keyCode = KEY_LEFT; return(onKeyDown(new_event)); } // Ctrl-F - move one character forward case KEY_F: { GuiEvent new_event; new_event.modifier = 0; new_event.keyCode = KEY_RIGHT; return(onKeyDown(new_event)); } // Ctrl-A - move to the beginning of the line case KEY_A: { GuiEvent new_event; new_event.modifier = 0; new_event.keyCode = KEY_HOME; return(onKeyDown(new_event)); } // Ctrl-E - move to the end of the line case KEY_E: { GuiEvent new_event; new_event.modifier = 0; new_event.keyCode = KEY_END; return(onKeyDown(new_event)); } // Ctrl-P - move backward in history case KEY_P: { GuiEvent new_event; new_event.modifier = 0; new_event.keyCode = KEY_UP; return(onKeyDown(new_event)); } // Ctrl-N - move forward in history case KEY_N: { GuiEvent new_event; new_event.modifier = 0; new_event.keyCode = KEY_DOWN; return(onKeyDown(new_event)); } // Ctrl-D - delete under cursor case KEY_D: { GuiEvent new_event; new_event.modifier = 0; new_event.keyCode = KEY_DELETE; return(onKeyDown(new_event)); } case KEY_U: { GuiEvent new_event; new_event.modifier = SI_CTRL; new_event.keyCode = KEY_DELETE; return(onKeyDown(new_event)); } // End added UNIX emacs key bindings #endif // Adding word jump navigation. case KEY_LEFT: { mCursorPos = findPrevWord(); mBlockStart = 0; mBlockEnd = 0; return true; } case KEY_RIGHT: { mCursorPos = findNextWord(); mBlockStart = 0; mBlockEnd = 0; return true; } #if !defined(TORQUE_OS_MAC) // Select all case KEY_A: { selectAllText(); return true; } // windows style cut / copy / paste / undo keybinds case KEY_C: case KEY_X: { // copy, and cut the text if we hit ctrl-x onCopy( event.keyCode==KEY_X ); return true; } case KEY_V: { onPaste(); // Execute the console command! execConsoleCallback(); return true; } case KEY_Z: if (! mDragHit) { onUndo(); return true; } #endif case KEY_DELETE: case KEY_BACKSPACE: //save the current state saveUndoState(); //delete everything in the field mTextBuffer.set(""); mCursorPos = 0; mBlockStart = 0; mBlockEnd = 0; execConsoleCallback(); onChangeCursorPos(); //.logicking return true; default: break; } } #if defined(TORQUE_OS_MAC) // mac style cut / copy / paste / undo keybinds else if (event.modifier & SI_ALT) { // Mac command key maps to alt in torque. // Added Mac cut/copy/paste/undo keys switch(event.keyCode) { // Select all case KEY_A: { selectAllText(); return true; } case KEY_C: case KEY_X: { // copy, and cut the text if we hit cmd-x onCopy( event.keyCode==KEY_X ); return true; } case KEY_V: { onPaste(); // Execute the console command! execConsoleCallback(); return true; } case KEY_Z: if (! mDragHit) { onUndo(); return true; } default: break; } } #endif else { switch(event.keyCode) { case KEY_ESCAPE: if( mEscapeCommand.isNotEmpty() ) { evaluate( mEscapeCommand ); return( true ); } return( Parent::onKeyDown( event ) ); case KEY_RETURN: case KEY_NUMPADENTER: return dealWithEnter(true); case KEY_UP: { if( mHistorySize > 0 ) { if(mHistoryDirty) { updateHistory(&mTextBuffer, false); mHistoryDirty = false; } mHistoryIndex--; if(mHistoryIndex >= 0 && mHistoryIndex <= mHistoryLast) setText(mHistoryBuf[mHistoryIndex]); else if(mHistoryIndex < 0) mHistoryIndex = 0; } return true; } case KEY_DOWN: { if( mHistorySize > 0 ) { if(mHistoryDirty) { updateHistory(&mTextBuffer, false); mHistoryDirty = false; } mHistoryIndex++; if(mHistoryIndex > mHistoryLast) { mHistoryIndex = mHistoryLast + 1; setText(""); } else setText(mHistoryBuf[mHistoryIndex]); } return true; } case KEY_LEFT: // If we have a selection put the cursor to the left side of it. if ( mBlockStart != mBlockEnd ) { mCursorPos = mBlockStart; mBlockStart = mBlockEnd = 0; } else { mBlockStart = mBlockEnd = 0; mCursorPos = getMax( mCursorPos - 1, 0 ); } return true; case KEY_RIGHT: // If we have a selection put the cursor to the right side of it. if ( mBlockStart != mBlockEnd ) { mCursorPos = mBlockEnd; mBlockStart = mBlockEnd = 0; } else { mBlockStart = mBlockEnd = 0; mCursorPos = getMin( mCursorPos + 1, stringLen ); } return true; case KEY_BACKSPACE: dealWithBackspace: //save the current state saveUndoState(); if (mBlockEnd > 0) { mTextBuffer.cut(mBlockStart, mBlockEnd-mBlockStart); mCursorPos = mBlockStart; mBlockStart = 0; mBlockEnd = 0; mHistoryDirty = true; // Execute the console command! execConsoleCallback(); } else if (mCursorPos > 0) { mTextBuffer.cut(mCursorPos-1, 1); mCursorPos--; mHistoryDirty = true; // Execute the console command! execConsoleCallback(); } return true; case KEY_DELETE: //save the current state saveUndoState(); if (mBlockEnd > 0) { mHistoryDirty = true; mTextBuffer.cut(mBlockStart, mBlockEnd-mBlockStart); mCursorPos = mBlockStart; mBlockStart = 0; mBlockEnd = 0; // Execute the console command! execConsoleCallback(); } else if (mCursorPos < stringLen) { mHistoryDirty = true; mTextBuffer.cut(mCursorPos, 1); // Execute the console command! execConsoleCallback(); } return true; case KEY_INSERT: mInsertOn = !mInsertOn; return true; case KEY_HOME: mBlockStart = 0; mBlockEnd = 0; mCursorPos = 0; return true; case KEY_END: mBlockStart = 0; mBlockEnd = 0; mCursorPos = stringLen; return true; default: break; } } switch ( event.keyCode ) { case KEY_TAB: if ( mTabComplete ) { onTabComplete_callback("0"); return( true ); } case KEY_UP: case KEY_DOWN: case KEY_ESCAPE: return Parent::onKeyDown( event ); default: break; } // Handle character input events. if( mProfile->mFont->isValidChar( event.ascii ) ) { handleCharInput( event.ascii ); return true; } // Or eat it if that's appropriate. if( mSinkAllKeyEvents ) return true; // Not handled - pass the event to it's parent. return Parent::onKeyDown( event ); }
void UIConsole::update(float dt) { updateHistory(); UIGroup::update(dt); }