int main () { QHash<int, int> myQHash; QHash<int, int> :: iterator it; myQHash[1] = 500; myQHash[2] = 300; myQHash[3] = 100; it = myQHash.begin(); it = myQHash.find(1); if (it.value() == 500) { it = myQHash.erase(it); } it = myQHash.find(2); if (it.value() == 300) { it = myQHash.erase(it); } assert(!(myQHash.empty())); return 0; }
void CDBirthdayController::syncBirthdays(const QList<QContact> &birthdayContacts) { QHash<ContactIdType, CalendarBirthday> oldBirthdays = mCalendar->birthdays(); // Check all birthdays from the contacts if the stored calendar item is up-to-date foreach (const QContact &contact, birthdayContacts) { #ifdef USING_QTPIM const QString contactDisplayLabel = contact.detail<QContactDisplayLabel>().label(); #else const QString contactDisplayLabel = contact.displayLabel(); #endif if (contactDisplayLabel.isNull()) { debug() << "Contact: " << contact << " has no displayLabel, so not syncing to calendar"; continue; } QHash<ContactIdType, CalendarBirthday>::Iterator it = oldBirthdays.find(apiId(contact)); if (oldBirthdays.end() != it) { const QContactBirthday contactBirthday = contact.detail<QContactBirthday>(); const CalendarBirthday &calendarBirthday = *it; // Display label or birthdate was changed on the contact, so update the calendar. if ((contactDisplayLabel != calendarBirthday.summary()) || (contactBirthday.date() != calendarBirthday.date())) { debug() << "Contact with calendar birthday: " << contactBirthday.date() << " and calendar displayLabel: " << calendarBirthday.summary() << " changed details to: " << contact << ", so update the calendar event"; mCalendar->updateBirthday(contact); } // Birthday exists, so not a garbage one oldBirthdays.erase(it); } else { // Create new birthday mCalendar->updateBirthday(contact); } } // Remaining old birthdays in the calendar db do not did not match any contact, so remove them. foreach (const ContactIdType &id, oldBirthdays.keys()) { debug() << "Birthday with contact id" << id << "no longer has a matching contact, trashing it"; mCalendar->deleteBirthday(id); } }
void scriptRemoveObject(const BASE_OBJECT *psObj) { for (QHash<int, bindNode>::iterator i = bindings.find(psObj->id); i != bindings.end(); i++) { int id = i.key(); bindNode node = i.value(); BASE_OBJECT *psObj = IdToPointer(id, node.player); if (psObj && !psObj->died) { QScriptValueList args; args += convMax(psObj, node.engine); callFunction(node.engine, node.funcName, args); } bindings.erase(i); } }
void testEraseNoError() { QHash<int, int> a; a.insert(100, 100); a.insert(101, 200); a.insert(5, 50); a.insertMulti(5, 60); a.insertMulti(5, 70); a.insertMulti(5, 80); QHash<int, int>::iterator i = a.begin(); while (i.key() != 5) ++i; ++i; a.erase(i); qDebug() << "Erase - got no errors on iterator check"; }
static bool isSubJOM(const QString &processExeName) { HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); if (hSnapshot == INVALID_HANDLE_VALUE) return false; bool result = false; QHash<DWORD, PROCESSENTRY32> processEntries; QSet<DWORD> seenProcessIds; PROCESSENTRY32 pe = {0}; pe.dwSize = sizeof(pe); if (!Process32First(hSnapshot, &pe)) { qWarning("Process32First failed with error code %d.", GetLastError()); goto done; } do { processEntries.insert(pe.th32ProcessID, pe); } while (Process32Next(hSnapshot, &pe)); const DWORD dwCurrentProcessId = GetCurrentProcessId(); DWORD dwProcessId = dwCurrentProcessId; while (dwProcessId && !seenProcessIds.contains(dwProcessId)) { seenProcessIds.insert(dwProcessId); QHash<DWORD, PROCESSENTRY32>::iterator it = processEntries.find(dwProcessId); if (it == processEntries.end()) break; PROCESSENTRY32 &pe = it.value(); QString exeName = QString::fromUtf16((const ushort*)pe.szExeFile); if (pe.th32ProcessID != dwCurrentProcessId && exeName == processExeName) { result = true; goto done; } dwProcessId = pe.th32ParentProcessID; processEntries.erase(it); } done: CloseHandle(hSnapshot); return result; }
// DSSI multiple instance entry destructor. void dssi_multi_destroy ( qtractorDssiPluginType *pDssiType ) { // Remove hash table entry... const QString& sKey = dssi_multi_key(pDssiType); QHash<QString, DssiMulti *>::Iterator iter = g_dssiHash.find(sKey); if (iter == g_dssiHash.end()) return; DssiMulti *pDssiMulti = iter.value(); if (pDssiMulti->removeRef()) { delete pDssiMulti; g_dssiHash.erase(iter); } // On last entry deallocate dummy buffer as well... if (g_dssiHash.isEmpty() && g_pDummyBuffer) { delete [] g_pDummyBuffer; g_pDummyBuffer = NULL; g_iDummyBufferSize = 0; } }
void keyToKeypad(QKeyEvent *event) { static const int ALT = 0x02000000; static const QHash<int, int> QtKeyMap { // Touchpad left buttons {Qt::Key_Escape, keymap::esc} ,{Qt::Key_End, keymap::pad} ,{Qt::Key_Tab, keymap::tab} // Touchpad right buttons ,{Qt::Key_Home, keymap::on} ,{Qt::Key_Escape | ALT, keymap::on} ,{Qt::Key_PageUp, keymap::doc} ,{Qt::Key_D | ALT, keymap::doc} ,{Qt::Key_PageDown, keymap::menu} ,{Qt::Key_M | ALT, keymap::menu} // Touchpad bottom buttons ,{Qt::Key_Control, keymap::ctrl} ,{Qt::Key_Shift, keymap::shift} ,{Qt::Key_Insert, keymap::var} ,{Qt::Key_V | ALT, keymap::var} ,{Qt::Key_Backspace, keymap::del} ,{Qt::Key_Delete, keymap::del} // Alpha buttons ,{Qt::Key_A, keymap::aa} ,{Qt::Key_B, keymap::ab} ,{Qt::Key_C, keymap::ac} ,{Qt::Key_D, keymap::ad} ,{Qt::Key_E, keymap::ae} ,{Qt::Key_F, keymap::af} ,{Qt::Key_G, keymap::ag} ,{Qt::Key_H, keymap::ah} ,{Qt::Key_I, keymap::ai} ,{Qt::Key_J, keymap::aj} ,{Qt::Key_K, keymap::ak} ,{Qt::Key_L, keymap::al} ,{Qt::Key_M, keymap::am} ,{Qt::Key_N, keymap::an} ,{Qt::Key_O, keymap::ao} ,{Qt::Key_P, keymap::ap} ,{Qt::Key_Q, keymap::aq} ,{Qt::Key_R, keymap::ar} ,{Qt::Key_S, keymap::as} ,{Qt::Key_T, keymap::at} ,{Qt::Key_U, keymap::au} ,{Qt::Key_V, keymap::av} ,{Qt::Key_W, keymap::aw} ,{Qt::Key_X, keymap::ax} ,{Qt::Key_Y, keymap::ay} ,{Qt::Key_Z, keymap::az} ,{Qt::Key_Less, keymap::ee} ,{Qt::Key_Less | ALT, keymap::ee} ,{Qt::Key_E | ALT, keymap::ee} ,{Qt::Key_Bar, keymap::pi} ,{Qt::Key_Bar | ALT, keymap::pi} ,{Qt::Key_Comma, keymap::comma} ,{Qt::Key_Comma | ALT, keymap::comma} ,{Qt::Key_Question, keymap::punct} ,{Qt::Key_Question | ALT, keymap::punct} ,{Qt::Key_W | ALT, keymap::punct} ,{Qt::Key_Greater, keymap::flag} ,{Qt::Key_Greater | ALT, keymap::flag} ,{Qt::Key_F | ALT, keymap::flag} ,{Qt::Key_Space, keymap::space} ,{Qt::Key_Enter | ALT, keymap::ret} ,{Qt::Key_Return | ALT, keymap::ret} // Numpad buttons ,{Qt::Key_0, keymap::n0} ,{Qt::Key_1, keymap::n1} ,{Qt::Key_2, keymap::n2} ,{Qt::Key_3, keymap::n3} ,{Qt::Key_4, keymap::n4} ,{Qt::Key_5, keymap::n5} ,{Qt::Key_6, keymap::n6} ,{Qt::Key_7, keymap::n7} ,{Qt::Key_8, keymap::n8} ,{Qt::Key_9, keymap::n9} ,{Qt::Key_Period, keymap::dot} ,{Qt::Key_Period | ALT, keymap::dot} ,{Qt::Key_Minus | ALT, keymap::neg} ,{Qt::Key_QuoteLeft, keymap::neg} ,{Qt::Key_QuoteLeft | ALT, keymap::neg} // Left buttons ,{Qt::Key_Equal, keymap::equ} ,{Qt::Key_Equal | ALT, keymap::equ} ,{Qt::Key_Q | ALT, keymap::equ} ,{Qt::Key_Backslash, keymap::trig} ,{Qt::Key_Backslash | ALT, keymap::trig} ,{Qt::Key_T | ALT, keymap::trig} ,{Qt::Key_AsciiCircum, keymap::pow} ,{Qt::Key_AsciiCircum | ALT, keymap::pow} ,{Qt::Key_P | ALT, keymap::pow} ,{Qt::Key_At, keymap::squ} ,{Qt::Key_At | ALT, keymap::squ} ,{Qt::Key_2 | ALT, keymap::squ} ,{Qt::Key_BracketLeft, keymap::exp} ,{Qt::Key_BracketLeft | ALT, keymap::exp} ,{Qt::Key_X | ALT, keymap::exp} ,{Qt::Key_BracketRight, keymap::pow10} ,{Qt::Key_BracketRight | ALT, keymap::pow10} ,{Qt::Key_1 | ALT, keymap::pow10} ,{Qt::Key_ParenLeft, keymap::pleft} ,{Qt::Key_ParenLeft | ALT, keymap::pleft} ,{Qt::Key_F1, keymap::pleft} ,{Qt::Key_ParenRight, keymap::pright} ,{Qt::Key_ParenRight | ALT, keymap::pright} ,{Qt::Key_F2, keymap::pright} // Right buttons ,{Qt::Key_Semicolon, keymap::metrix} ,{Qt::Key_Semicolon | ALT, keymap::metrix} ,{Qt::Key_O | ALT, keymap::metrix} ,{Qt::Key_Apostrophe, keymap::cat} ,{Qt::Key_Apostrophe | ALT, keymap::cat} ,{Qt::Key_C | ALT, keymap::cat} ,{Qt::Key_Asterisk, keymap::mult} ,{Qt::Key_Asterisk | ALT, keymap::mult} ,{Qt::Key_A | ALT, keymap::mult} ,{Qt::Key_Slash, keymap::div} ,{Qt::Key_Slash | ALT, keymap::div} ,{Qt::Key_F3, keymap::div} ,{Qt::Key_Plus, keymap::plus} ,{Qt::Key_Plus | ALT, keymap::plus} ,{Qt::Key_Equal | ALT, keymap::plus} ,{Qt::Key_Minus, keymap::minus} ,{Qt::Key_Minus | ALT, keymap::minus} ,{Qt::Key_Underscore, keymap::minus} ,{Qt::Key_Underscore | ALT, keymap::minus} ,{Qt::Key_Enter, keymap::enter} ,{Qt::Key_Return, keymap::enter} }; static QHash<int, int> pressed_keys; // Ignore autorepeat, calc os must handle it on it's own if (event->isAutoRepeat()) return; // Determine virtual key that correspond to the key we got auto vkey = event->nativeVirtualKey(); // nativeVirtualKey should be working everywhere, but just in case it's not if (vkey == 0 || vkey == 1) vkey = event->nativeScanCode(); // If neither of them worked then simply use key code if (vkey == 0 || vkey == 1) vkey = event->key(); auto pressed = pressed_keys.find(vkey); // If vkey is already pressed, then this must the the release event if (pressed != pressed_keys.end()) { setKeypad(*pressed, false); pressed_keys.erase(pressed); } else if (event->type() == QEvent::KeyPress) // But press only on the press event { auto mkey = event->key(); if (event->modifiers() & Qt::ShiftModifier && mkey == Qt::Key_Alt) { setKeypad(keymap::shift, false); return; } if (event->modifiers() & Qt::AltModifier) { if (mkey == Qt::Key_Shift) return; // Just ignore it else mkey |= ALT; // Compose alt into the unused bit of the keycode } auto translated = QtKeyMap.find(mkey); if (translated != QtKeyMap.end()) { pressed_keys.insert(vkey, *translated); setKeypad(*translated, true); } } }
void apiOrderBook::receiveDataFromSgOrderBook() { QHash<QString, RSP::OrderConfirmation*> confirmationMap; _ApiPointer->getBaseWrapper()->getOfflineConfirmationMap(confirmationMap); QHash<QString, RSP::OrderConfirmation*>::iterator it; if(_apiOrderBookModel->rowCount() == 0 ) ui->doubleSpinBoxPrice->setValue(0); if(confirmationMap.isEmpty()) { _apiOrderBookModel->setRowCount(0); } else { int eventCounter = 0; for(int row=_apiOrderBookModel->rowCount()-1;row>=0;row--) { QString key = _apiOrderBookModel->item(row, colOrderBook_ExOrderId)->data(Qt::DisplayRole).toString(); RSP::OrderConfirmation *confirmation = 0; it = confirmationMap.find(key); if(it != confirmationMap.end() && _ApiPointer->isStrategyIdExists(it.value()->getStrategyId())) { confirmation = it.value(); if( confirmation != NULL ) { updateModel(row, *confirmation); delete confirmation; confirmation = 0; } confirmationMap.erase(it); } else _apiOrderBookModel->removeRow(row); eventCounter++; if(eventCounter == 100) { eventCounter = 0; qApp->processEvents(); } } it = confirmationMap.begin(); while(it != confirmationMap.end()) { RSP::OrderConfirmation *confirmation = it.value(); if(confirmation != NULL) { insertNewRowInOrderBook(*confirmation); delete confirmation; confirmation = 0; } eventCounter++; if(eventCounter == 100) { eventCounter = 0; qApp->processEvents(); } it = confirmationMap.erase(it); } } _proxyModel->invalidate(); _ApiPointer->getCommonMethodsWrapper()->updateTableView(ui->apiOrderBookTableView); }
void KListWidgetPrivate::doLayout() { Q_Q(KListWidget); if(m_model->isEmpty()) { /*直接回收所有资源,并返回。*/ QHash<int, QPointer<KListItem>> items = m_widgetItems; m_widgetItems.clear(); m_indexWidgetItemBegin = 0; int iLeft = 0; for(QHash<int,QPointer<KListItem>>::iterator iter = items.begin(); iter != items.end(); iter++, iLeft++) { KListItem *pli = iter.value(); if(iLeft < 3) { m_creator->recycle(pli); pli->hide(); } else { delete pli; } } return; } /*至少有一个元素。*/ //显示在列表中的第一个Item //计算下边框是否隐藏为列表可见区的第一项。 qreal itemPosVisibleFirst = -m_valueCurrentScroll; int itemIdxFirst = 0; #if 1 calcLayoutFirstItem(itemIdxFirst, itemPosVisibleFirst, 0, m_model->count()); #else int nblock = (m_model->count() + 49) / 50; for(int iblock = 0; iblock < nblock; iblock++) { int height50 = m_heightUnselect * 50; if(iblock * 50 < m_indexSelect && m_indexSelect < (iblock+1) * 50) { height50 += m_heightSelect - m_heightUnselect; } if(itemPosVisibleFirst + height50 > m_contentArea.top()) { for(int i = iblock * 50; i < m_model->count(); i++) { if(m_indexSelect == i) { if(itemPosVisibleFirst + m_heightSelect > m_contentArea.top()) { itemIdxFirst = i; break; } else { itemPosVisibleFirst += m_heightSelect; } } else { if(itemPosVisibleFirst + m_heightUnselect > m_contentArea.top()) { itemIdxFirst = i; break; } else { itemPosVisibleFirst += m_heightUnselect; } } } break; } else { itemPosVisibleFirst += height50; } } #endif //最后一个元素显示在列表中的。 //计算上边框是否隐藏来判断是否为列表可见区中最后一项 qreal itemPosVisibleLast = itemPosVisibleFirst; int itemIdxLast = m_model->count() - 1; for(int i = itemIdxFirst; i < m_model->count(); i++) { if(m_indexSelect == i) { if(itemPosVisibleLast + m_heightSelect > m_contentArea.bottom()) { itemIdxLast = i; break; } else { itemPosVisibleLast += m_heightSelect; } } else { if(itemPosVisibleLast + m_heightUnselect > m_contentArea.bottom()) { itemIdxLast = i; break; } else { itemPosVisibleLast += m_heightUnselect; } } } QHash<int,QPointer<KListItem>> items = m_widgetItems; m_widgetItems.clear(); m_indexWidgetItemBegin = itemIdxFirst; /*处理已经重复的对象*/ qreal itemPosVisible = itemPosVisibleFirst; QSet<int> itemsok; for(int i = itemIdxFirst; !items.isEmpty() && i <= itemIdxLast; i++) { KListItem *pli = items.take(i); if(pli == NULL) { if(i == m_indexSelect) { itemPosVisible += m_heightSelect; } else { itemPosVisible += m_heightUnselect; } continue; } QRectF itemRt; if(i == m_indexSelect) { itemRt = QRectF(m_contentArea.left(), itemPosVisible, m_contentArea.width(), m_heightSelect); itemPosVisible += m_heightSelect; } else { itemRt = QRectF(m_contentArea.left(), itemPosVisible, m_contentArea.width(), m_heightUnselect); itemPosVisible += m_heightUnselect; } pli->setMargins(m_itemMargins); pli->setGeometry(itemRt); pli->setFixSize(itemRt.size()); if(i == m_indexSelect) { pli->setSelected(m_variantSelected); } else if(pli->isUnderMouse()) { pli->setHovered(m_variantHovered); } else { pli->setUnselected(m_variantUnselect); } pli->show(); m_widgetItems.insert(i, pli); itemsok.insert(i); } /*处理没有设置的对象。*/ itemPosVisible = itemPosVisibleFirst; for(int i = itemIdxFirst; i <= itemIdxLast; i++) { if(itemsok.contains(i)) { if(i == m_indexSelect) { itemPosVisible += m_heightSelect; } else { itemPosVisible += m_heightUnselect; } continue; } KListItem *pli; if(items.isEmpty()) { pli = m_creator->create(q); } else { QHash<int,QPointer<KListItem>>::iterator iter = items.begin(); pli = iter.value(); items.erase(iter); } QRectF itemRt; if(i == m_indexSelect) { itemRt = QRectF(m_contentArea.left(), itemPosVisible, m_contentArea.width(), m_heightSelect); itemPosVisible += m_heightSelect; } else { itemRt = QRectF(m_contentArea.left(), itemPosVisible, m_contentArea.width(), m_heightUnselect); itemPosVisible += m_heightUnselect; } pli->resetIndex(i); pli->setMargins(m_itemMargins); pli->setGeometry(itemRt); pli->setFixSize(itemRt.size()); if(i == m_indexSelect) { pli->setSelected(m_variantSelected); } else if(pli->isUnderMouse()) { pli->setHovered(m_variantHovered); } else { pli->setUnselected(m_variantUnselect); } pli->show(); m_widgetItems.insert(i, pli); } int iLeft = 0; for(QHash<int,QPointer<KListItem>>::iterator iter = items.begin(); iter != items.end(); iter++, iLeft++) { KListItem *pli = iter.value(); if(iLeft < 3) { m_creator->recycle(pli); pli->hide(); } else { delete pli; } } }
void ParserXmlVasttrafikSe::parseSearchJourney(QNetworkReply *networkReply) { qDebug() << "ParserXmlVasttrafikSe::parseSearchJourney(networkReply.url()=" << networkReply->url().toString() << ")"; JourneyResultList *journeyResultList = new JourneyResultList(); for (QHash<QString, JourneyDetailResultList *>::Iterator it = cachedJourneyDetails.begin(); it != cachedJourneyDetails.end();) { JourneyDetailResultList *jdrl = it.value(); it = cachedJourneyDetails.erase(it); delete jdrl; } /// Use fallback values for empty results (i.e. no connections found) journeyResultList->setDepartureStation(m_searchJourneyParameters.departureStation.name); journeyResultList->setViaStation(m_searchJourneyParameters.viaStation.name); journeyResultList->setArrivalStation(m_searchJourneyParameters.arrivalStation.name); journeyResultList->setTimeInfo(tr("%1, %2", "DATE, TIME").arg(m_searchJourneyParameters.dateTime.date().toString(Qt::DefaultLocaleShortDate)).arg(m_searchJourneyParameters.dateTime.time().toString(Qt::DefaultLocaleShortDate))); m_earliestArrival = m_latestResultDeparture = QDateTime(); QTextStream ts(networkReply->readAll()); ts.setCodec("UTF-8"); const QString xmlRawtext = ts.readAll(); QDomDocument doc("result"); if (doc.setContent(xmlRawtext, false)) { QDomNodeList tripNodeList = doc.elementsByTagName("Trip"); for (unsigned int i = 0; i < tripNodeList.length(); ++i) { JourneyResultItem *jritem = new JourneyResultItem(); JourneyDetailResultList *detailsList = new JourneyDetailResultList(); /// Set default values for journey's start and end time QDateTime journeyStart = QDateTime::currentDateTime(); QDateTime journeyEnd = QDateTime::currentDateTime(); QDomNodeList legNodeList = tripNodeList.item(i).childNodes(); int numStops = 0; QStringList trainTypes; int tripRtStatus = TRIP_RTDATA_NONE; for (unsigned int j = 0; j < legNodeList.length(); ++j) { QDomNode legNode = legNodeList.item(j); QDomNode originNode = legNode.namedItem("Origin"); QDomNode destinationNode = legNode.namedItem("Destination"); if (j == 0) { journeyStart.setDate(QDate::fromString(getAttribute(originNode, "date"), QLatin1String("yyyy-MM-dd"))); journeyEnd.setDate(journeyStart.date()); const QTime time = QTime::fromString(getAttribute(originNode, "time"), "hh:mm"); journeyStart.setTime(time); if (i == 0) { const QDate date = QDate::fromString(getAttribute(originNode, "date"), QLatin1String("yyyy-MM-dd")); journeyResultList->setDepartureStation(getAttribute(originNode, "name")); journeyResultList->setTimeInfo(tr("%1, %2", "DATE, TIME").arg(date.toString(Qt::DefaultLocaleShortDate)).arg(time.toString(Qt::DefaultLocaleShortDate))); } } if (j == legNodeList.length() - 1) { journeyEnd.setTime(QTime::fromString(getAttribute(destinationNode, "time"), "hh:mm")); if (i == 0) journeyResultList->setArrivalStation(getAttribute(destinationNode, "name")); } if (getAttribute(legNode, "type") != QLatin1String("WALK") || getAttribute(originNode, "name") != getAttribute(destinationNode, "name")) { ++numStops; trainTypes.append(i18nConnectionType(getAttribute(legNode, "name"))); } JourneyDetailResultItem *jdrItem = new JourneyDetailResultItem(); jdrItem->setDepartureStation(getAttribute(originNode, "name")); const QString depTrack = getAttribute(originNode, "track"); jdrItem->setDepartureInfo(depTrack.isEmpty() ? QChar(0x2014) : tr("Track %1").arg(depTrack)); const QDateTime scheduledDepartureTime = QDateTime::fromString(getAttribute(originNode, "date") + getAttribute(originNode, "time"), "yyyy-MM-ddhh:mm"); jdrItem->setDepartureDateTime(scheduledDepartureTime); jdrItem->setArrivalStation(getAttribute(destinationNode, "name")); const QString arrTrack = getAttribute(destinationNode, "track"); jdrItem->setArrivalInfo(arrTrack.isEmpty() ? QChar(0x2014) : tr("Track %1").arg(arrTrack)); const QDateTime scheduledArrivalTime = QDateTime::fromString(getAttribute(destinationNode, "date") + getAttribute(destinationNode, "time"), "yyyy-MM-ddhh:mm"); jdrItem->setArrivalDateTime(scheduledArrivalTime); const QString direction = getAttribute(legNode, "direction"); if (!direction.isEmpty()) jdrItem->setInfo(tr("to %1").arg(direction)); if (getAttribute(legNode, "type") == QLatin1String("WALK")) jdrItem->setTrain(tr("Walk")); else { const QString connectionName = i18nConnectionType(getAttribute(legNode, "name")); const QString fgColor = getAttribute(legNode, "fgColor"); const QString bgColor = getAttribute(legNode, "bgColor"); if (!fgColor.isEmpty() && !bgColor.isEmpty()) jdrItem->setTrain(QString(QLatin1String("<span style=\"color:%2; background-color: %3;\">%1</span>")).arg(connectionName).arg(fgColor).arg(bgColor)); else jdrItem->setTrain(connectionName); } jdrItem->setInternalData1("NO setInternalData1"); jdrItem->setInternalData2("NO setInternalData2"); const QString realTimeDeparture = getAttribute(originNode, "rtTime"); if (!realTimeDeparture.isEmpty()) { const QTime realTimeTime = QTime::fromString(realTimeDeparture, QLatin1String("hh:mm")); const int minutesTo = scheduledDepartureTime.time().msecsTo(realTimeTime) / 60000; if (minutesTo > 3) { jdrItem->setDepartureInfo(jdrItem->departureInfo() + tr("<br/><span style=\"color:#b30;\">%1 min late</span>").arg(minutesTo)); tripRtStatus = TRIP_RTDATA_WARNING; } else { if (tripRtStatus == TRIP_RTDATA_NONE) { tripRtStatus = TRIP_RTDATA_ONTIME; } jdrItem->setDepartureInfo(jdrItem->departureInfo() + tr("<br/><span style=\"color:#093; font-weight: normal;\">on time</span>")); } } const QString realTimeArrival = getAttribute(destinationNode, "rtTime"); if (!realTimeArrival.isEmpty()) { const QTime realTimeTime = QTime::fromString(realTimeArrival, QLatin1String("hh:mm")); const int minutesTo = scheduledArrivalTime.time().msecsTo(realTimeTime) / 60000; if (minutesTo > 3) jdrItem->setArrivalInfo(jdrItem->arrivalInfo() + tr("<br/><span style=\"color:#b30;\">%1 min late</span>").arg(minutesTo)); else jdrItem->setArrivalInfo(jdrItem->arrivalInfo() + tr("<br/><span style=\"color:#093; font-weight: normal;\">on time</span>")); } detailsList->appendItem(jdrItem); } if (journeyStart.time() > journeyEnd.time()) journeyEnd = journeyEnd.addDays(1); jritem->setDate(journeyStart.date()); jritem->setDepartureTime(journeyStart.time().toString(tr("hh:mm"))); jritem->setArrivalTime(journeyEnd.time().toString(tr("hh:mm"))); int diffTime = journeyStart.secsTo(journeyEnd); if (diffTime < 0) diffTime += 86400; jritem->setDuration(tr("%1:%2").arg(diffTime / 3600).arg(QString::number(diffTime / 60 % 60), 2, '0')); jritem->setTransfers(QString::number(legNodeList.length() - 1)); trainTypes.removeDuplicates(); jritem->setTrainType(trainTypes.join(", ")); if (tripRtStatus == TRIP_RTDATA_WARNING) jritem->setMiscInfo(tr("<span style=\"color:#b30;\">traffic warning</span>")); else if (tripRtStatus == TRIP_RTDATA_ONTIME) jritem->setMiscInfo(tr("<span style=\"color:#093; font-weight: normal;\">on time</span>")); journeyResultList->appendItem(jritem); const QString id = QString::number(i); jritem->setId(id); detailsList->setId(id); detailsList->setDepartureStation(journeyResultList->departureStation()); detailsList->setViaStation(journeyResultList->viaStation()); detailsList->setArrivalStation(journeyResultList->arrivalStation()); detailsList->setDuration(jritem->duration()); detailsList->setArrivalDateTime(journeyEnd); detailsList->setDepartureDateTime(journeyStart); cachedJourneyDetails[id] = detailsList; if (!m_earliestArrival.isValid() || journeyEnd < m_earliestArrival) m_earliestArrival = journeyEnd.addSecs(-60); if (!m_latestResultDeparture.isValid() || journeyStart > m_latestResultDeparture) m_latestResultDeparture = journeyStart.addSecs(60); } } emit journeyResult(journeyResultList); }
void DatabaseSynchronizer::run() { QMutexLocker locker(&FMutex); while (!FQuit && !FStreams.isEmpty()) { Jid streamJid = FStreams.dequeue(); locker.unlock(); Logger::startTiming(STMP_HISTORY_FILE_DATABASE_SYNC); bool syncFailed = false; QDateTime syncTime = QDateTime::currentDateTime(); QString archivePath = FFileArchive->fileArchivePath(streamJid); if (!archivePath.isEmpty()) { IArchiveRequest loadRequest; QHash<Jid, QList<QString> > databaseHeadersMap; QHash<QString, DatabaseArchiveHeader> databaseFileHeaders; DatabaseTaskLoadHeaders *loadTask = new DatabaseTaskLoadHeaders(streamJid,loadRequest,QString::null); if (!FDatabaseWorker->execTask(loadTask)) { syncFailed = true; REPORT_ERROR("Failed to synchronize file archive database: Load database headers task not executed"); } else if (loadTask->isFailed()) { syncFailed = true; REPORT_ERROR("Failed to synchronize file archive database: Load database headers task failed"); } else foreach(const DatabaseArchiveHeader &header, loadTask->headers()) { if (header.timestamp < syncTime) { QString fileName = (FFileArchive->collectionDirName(header.with)+"/"+FFileArchive->collectionFileName(header.start)).toLower(); databaseHeadersMap[header.with].append(fileName); databaseFileHeaders.insert(fileName,header); } } delete loadTask; QHash<Jid, QList<IArchiveHeader> > fileHeadersMap; QDirIterator bareIt(archivePath,QDir::Dirs|QDir::NoDotAndDotDot); while (!FQuit && !syncFailed && bareIt.hasNext()) { QDirIterator filesIt(bareIt.next(), QDir::Files, QDirIterator::Subdirectories); Jid bareWith = Jid::decode(bareIt.fileName()); bool isGated = bareWith.pDomain().endsWith(".gateway"); int pathLength = bareIt.filePath().length()-bareIt.fileName().length(); while (filesIt.hasNext()) { filesIt.next(); QDateTime fileLastModified = filesIt.fileInfo().lastModified(); if (fileLastModified < syncTime) { QString fileName = filesIt.filePath().mid(pathLength).toLower(); QHash<QString, DatabaseArchiveHeader>::iterator dbHeaderIt = databaseFileHeaders.find(fileName); if (dbHeaderIt==databaseFileHeaders.end() || dbHeaderIt->timestamp<fileLastModified) { IArchiveHeader header = FFileArchive->loadFileHeader(filesIt.filePath()); if (header.with.isValid() && header.start.isValid() && !fileHeadersMap.value(header.with).contains(header)) { if (!isGated && header.with.pBare()==bareWith.pBare()) fileHeadersMap[header.with].append(header); else if (isGated && header.with.pNode()==bareWith.pNode()) fileHeadersMap[header.with].append(header); } } else { databaseFileHeaders.erase(dbHeaderIt); } } } } for (QHash<Jid, QList<IArchiveHeader> >::iterator it=fileHeadersMap.begin(); !FQuit && !syncFailed && it!=fileHeadersMap.end(); ++it) { Jid with = it.key(); QList<IArchiveHeader> newHeaders; QList<IArchiveHeader> difHeaders; QList<IArchiveHeader> oldHeaders; QList<IArchiveHeader> &fileHeaders = it.value(); qSort(fileHeaders.begin(),fileHeaders.end()); QList<IArchiveHeader> databaseHeaders; foreach(const QString &fileName, databaseHeadersMap.take(with)) { QHash<QString, DatabaseArchiveHeader>::const_iterator dbHeaderIt = databaseFileHeaders.constFind(fileName); if (dbHeaderIt != databaseFileHeaders.constEnd()) databaseHeaders.append(dbHeaderIt.value()); } qSort(databaseHeaders.begin(),databaseHeaders.end()); if (databaseHeaders.isEmpty()) { newHeaders = fileHeaders; } else if (fileHeaders.isEmpty()) { oldHeaders = databaseHeaders; } else while (!fileHeaders.isEmpty() || !databaseHeaders.isEmpty()) { if (fileHeaders.isEmpty()) { oldHeaders += databaseHeaders.takeFirst(); } else if (databaseHeaders.isEmpty()) { newHeaders += fileHeaders.takeFirst(); } else if (fileHeaders.first() < databaseHeaders.first()) { newHeaders += fileHeaders.takeFirst(); } else if (databaseHeaders.first() < fileHeaders.first()) { oldHeaders += databaseHeaders.takeFirst(); } else if (fileHeaders.first().version != databaseHeaders.first().version) { difHeaders += fileHeaders.takeFirst(); databaseHeaders.removeFirst(); } else { fileHeaders.removeFirst(); databaseHeaders.removeFirst(); } } if (!syncFailed && !newHeaders.isEmpty()) { QString gateType = !with.node().isEmpty() ? FFileArchive->contactGateType(with) : QString::null; DatabaseTaskInsertHeaders *insertTask = new DatabaseTaskInsertHeaders(streamJid,newHeaders,gateType); if (!FDatabaseWorker->execTask(insertTask)) { syncFailed = true; REPORT_ERROR("Failed to synchronize file archive database: Insert new headers task not executed"); } else if(insertTask->isFailed()) { syncFailed = true; REPORT_ERROR("Failed to synchronize file archive database: Insert new headers task failed"); } delete insertTask; } if (!syncFailed && !difHeaders.isEmpty()) { DatabaseTaskUpdateHeaders *updateTask = new DatabaseTaskUpdateHeaders(streamJid,difHeaders); if (!FDatabaseWorker->execTask(updateTask)) { syncFailed = true; REPORT_ERROR("Failed to synchronize file archive database: Update changed headers task not executed"); } else if (updateTask->isFailed()) { syncFailed = true; REPORT_ERROR("Failed to synchronize file archive database: Update changed headers task failed"); } delete updateTask; } if (!syncFailed && !oldHeaders.isEmpty()) { DatabaseTaskRemoveHeaders *removeTask = new DatabaseTaskRemoveHeaders(streamJid,oldHeaders); if (!FDatabaseWorker->execTask(removeTask)) { syncFailed = true; REPORT_ERROR("Failed to synchronize file archive database: Remove old headers task not executed"); } else if (removeTask->isFailed()) { syncFailed = true; REPORT_ERROR("Failed to synchronize file archive database: Remove old headers task failed"); } delete removeTask; } } for (QHash<Jid, QList<QString> >::const_iterator it=databaseHeadersMap.constBegin(); !FQuit && !syncFailed && it!=databaseHeadersMap.constEnd(); ++it) { QList<IArchiveHeader> oldHeaders; foreach(const QString &fileName, it.value()) { QHash<QString, DatabaseArchiveHeader>::const_iterator dbHeaderIt = databaseFileHeaders.constFind(fileName); if (dbHeaderIt != databaseFileHeaders.constEnd()) oldHeaders.append(dbHeaderIt.value()); } if (!oldHeaders.isEmpty()) { DatabaseTaskRemoveHeaders *removeTask = new DatabaseTaskRemoveHeaders(streamJid,oldHeaders); if (!FDatabaseWorker->execTask(removeTask)) { syncFailed = true; REPORT_ERROR("Failed to synchronize file archive database: Remove old headers task not executed"); } else if (removeTask->isFailed()) { syncFailed = true; REPORT_ERROR("Failed to synchronize file archive database: Remove old headers task failed"); } delete removeTask; } } } else {
void KTreeWidgetPrivate::doLayout() { Q_Q(KTreeWidget); if(m_itemsTree.isEmpty()) { /*直接回收所有资源,并返回。*/ QHash<qint64, QPointer<KTreeItem>> items = m_widgetItems; m_widgetItems.clear(); m_indexWidgetItemBegin = 0; int iLeft = 0; for(QHash<qint64, QPointer<KTreeItem>>::iterator iter = items.begin(); iter != items.end(); iter++,iLeft++) { KTreeItem *pli = iter.value(); if(iLeft <= 3) { m_creator->recycle(pli); pli->hide(); } else { delete pli; } } return; } /*至少有一个元素。*/ //显示在列表中的第一个Item //计算下边框是否隐藏为列表可见区的第一项。 qreal itemPosVisibleFirst = -m_valueCurrentScroll; int itemIdxFirst = 0; calcLayoutFirstItem(itemIdxFirst, itemPosVisibleFirst, 0, m_itemsTree.size()); //最后一个元素显示在列表中的。 //计算上边框是否隐藏来判断是否为列表可见区中最后一项 qreal itemPosVisibleLast = itemPosVisibleFirst; int itemIdxLast = m_itemsTree.count() - 1; for(int i = itemIdxFirst; i < m_itemsTree.count(); i++) { if(itemPosVisibleLast + m_heightItem > m_contentArea.bottom()) { itemIdxLast = i; break; } else { itemPosVisibleLast += m_heightItem; } } QHash<qint64, QPointer<KTreeItem>> items = m_widgetItems; m_widgetItems.clear(); m_indexWidgetItemBegin = itemIdxFirst; /*处理已经重复的对象*/ bool bdepth = m_styleTree & KTreeWidget::HasBranch; qreal itemPosVisible = itemPosVisibleFirst; QSet<int> itemsok; for(int i = itemIdxFirst; !items.isEmpty() && i <= itemIdxLast; i++) { qint64 nodeid = m_itemsTree.at(i); KTreeItem *pli = items.take(nodeid); if(pli == NULL) { itemPosVisible += m_heightItem; continue; } QRectF itemRt; itemRt = QRectF(m_contentArea.left(), itemPosVisible, m_contentArea.width(), m_heightItem); itemPosVisible += m_heightItem; QMargins margins = m_itemMargins; if(bdepth) { int ndepth = m_model->nodeDepth(nodeid); ndepth *= m_depthIndentation; margins = QMargins(m_itemMargins.left() + ndepth, m_itemMargins.top(), m_itemMargins.right(), m_itemMargins.bottom()); } pli->setMargins(margins); pli->setGeometry(itemRt); pli->setFixSize(itemRt.size()); if(nodeid == m_nodeIdSelect) { pli->setSelected(m_variantSelected); } else if(pli->isUnderMouse()) { pli->setHovered(m_variantHovered); } else { pli->setUnselected(m_variantUnselect); } pli->show(); m_widgetItems.insert(nodeid, pli); itemsok.insert(i); } /*处理没有设置的对象。*/ itemPosVisible = itemPosVisibleFirst; for(int i = itemIdxFirst; i <= itemIdxLast; i++) { if(itemsok.contains(i)) { itemPosVisible += m_heightItem; continue; } qint64 nodeid = m_itemsTree.at(i); KTreeItem *pli = NULL; if(items.isEmpty()) { pli = m_creator->create(q); } else { QHash<qint64, QPointer<KTreeItem>>::iterator iter = items.begin(); pli = iter.value(); items.erase(iter); } QRectF itemRt; itemRt = QRectF(m_contentArea.left(), itemPosVisible, m_contentArea.width(), m_heightItem); itemPosVisible += m_heightItem; pli->resetNodeId(nodeid); QMargins margins = m_itemMargins; if(bdepth) { int ndepth = m_model->nodeDepth(nodeid); ndepth *= m_depthIndentation; margins = QMargins(m_itemMargins.left() + ndepth, m_itemMargins.top(), m_itemMargins.right(), m_itemMargins.bottom()); } pli->setMargins(margins); pli->setGeometry(itemRt); pli->setFixSize(itemRt.size()); if(nodeid == m_nodeIdSelect) { pli->setSelected(m_variantSelected); } else if(pli->isUnderMouse()) { pli->setHovered(m_variantHovered); } else { pli->setUnselected(m_variantUnselect); } pli->show(); m_widgetItems.insert(nodeid, pli); } int iLeft = 0; for(QHash<qint64, QPointer<KTreeItem>>::iterator iter = items.begin(); iter != items.end(); iter++,iLeft++) { KTreeItem *pli = iter.value(); if(iLeft <= 3) { m_creator->recycle(pli); pli->hide(); } else { delete pli; } } }