void LibraryTreeWidget::onCustomContextMenuRequested(const QPoint& pos) { QMenu menu(this); bool file = false; bool folder = false; bool project = false; int size = selectedItems().size(); for (int i = 0; i < selectedItems().size(); ++i) { if (selectedItems()[i]->parent() == NULL) { project = true; } else { QString fileName = selectedItems()[i]->data(0, Qt::UserRole).toMap()["filename"].toString(); if (fileName.isEmpty() == true) folder = true; else file = true; } } if (size == 1 && (folder || project)) { menu.addAction(addNewFileAction_); menu.addAction(importToLibraryAction_); menu.addAction(newFolderAction_); } if (size > 0 && !project) menu.addAction(removeAction_); if (size == 1 && folder) menu.addAction(renameAction_); if (size == 1 && (folder || project)) menu.addAction(sortAction_); if (size == 1 && file) { menu.addAction(insertIntoDocumentAction_); QMap<QString, QVariant> data = selectedItems()[0]->data(0, Qt::UserRole).toMap(); QString fileName = data["filename"].toString(); QFileInfo fileInfo(fileName); QString ext = fileInfo.suffix().toLower(); if (ext == "lua") { menu.addAction(codeDependenciesAction_); bool excludeFromExecution = data.contains("excludeFromExecution") && data["excludeFromExecution"].toBool(); excludeFromExecutionAction_->setChecked(excludeFromExecution); menu.addAction(excludeFromExecutionAction_); } if (ext == "png" || ext == "jpg" || ext == "jpeg") { bool downsizing = data.contains("downsizing") && data["downsizing"].toBool(); automaticDownsizingAction_->setChecked(downsizing); menu.addAction(automaticDownsizingAction_); } } if (size == 1 && project) menu.addAction(projectPropertiesAction_); if (!menu.isEmpty()) menu.exec(QCursor::pos()); }
void MsScWriter::note(const QString pitch, const QVector<Bww::BeamType> beamList, const QString type, const int dots, bool tieStart, bool /*TODO tieStop */, StartStop triplet, bool grace) { qDebug() << "MsScWriter::note()" << "type:" << type << "dots:" << dots << "grace" << grace ; if (!stepAlterOctMap.contains(pitch) || !typeMap.contains(type)) { // TODO: error message return; } StepAlterOct sao = stepAlterOctMap.value(pitch); int ticks = 4 * Ms::MScore::division / type.toInt(); if (dots) ticks = 3 * ticks / 2; qDebug() << "ticks:" << ticks; Ms::TDuration durationType(Ms::TDuration::DurationType::V_INVALID); durationType.setVal(ticks); qDebug() << "duration:" << durationType.name(); if (triplet != ST_NONE) ticks = 2 * ticks / 3; Ms::Beam::Mode bm = (beamList.at(0) == Bww::BM_BEGIN) ? Ms::Beam::Mode::BEGIN : Ms::Beam::Mode::AUTO; Ms::Direction sd = Ms::Direction::AUTO; // create chord Ms::Chord* cr = new Ms::Chord(score); //ws cr->setTick(tick); cr->setBeamMode(bm); cr->setTrack(0); if (grace) { cr->setNoteType(Ms::NoteType::GRACE32); cr->setDurationType(Ms::TDuration::DurationType::V_32ND); sd = Ms::Direction::UP; } else { if (durationType.type() == Ms::TDuration::DurationType::V_INVALID) durationType.setType(Ms::TDuration::DurationType::V_QUARTER); cr->setDurationType(durationType); sd = Ms::Direction::DOWN; } cr->setDuration(durationType.fraction()); cr->setDots(dots); cr->setStemDirection(sd); // add note to chord Ms::Note* note = new Ms::Note(score); note->setTrack(0); xmlSetPitch(note, sao.s.toLatin1(), sao.a, sao.o); if (tieStart) { Ms::Tie* tie = new Ms::Tie(score); note->setTieFor(tie); tie->setStartNote(note); tie->setTrack(0); } cr->add(note); // add chord to measure if (!grace) { Ms::Segment* s = currentMeasure->getSegment(Ms::Segment::Type::ChordRest, tick); s->add(cr); if (!currentGraceNotes.isEmpty()) { for (int i = currentGraceNotes.size() - 1; i >=0; i--) cr->add(currentGraceNotes.at(i)); currentGraceNotes.clear(); } doTriplet(cr, triplet); int tickBefore = tick; tick += ticks; Ms::Fraction nl(Ms::Fraction::fromTicks(tick - currentMeasure->tick())); currentMeasure->setLen(nl); qDebug() << "MsScWriter::note()" << "tickBefore:" << tickBefore << "tick:" << tick << "nl:" << nl.print() ; } else { currentGraceNotes.append(cr); } }
void rce::gui::RImageMarkerScene:: mousePressEvent(QGraphicsSceneMouseEvent *mouseEvent) { if(mouseEvent->button() == Qt::LeftButton) { const QGraphicsView *eventView = NULL; if(mouseEvent->widget() != NULL) { eventView = dynamic_cast<const QGraphicsView*>(mouseEvent->widget()->parentWidget()); } QTransform viewTransform; if(eventView != NULL) { viewTransform = eventView->transform(); } itemEdited_ = false; switch(mode_) { case rce::gui::RImageMarkerScene::DrawPointMode: { // check if there is handle under mouse QList<QGraphicsItem *> itemsUnderMouse = items(rce::gui::getSceneRectAroundScreenPos(mouseEvent->screenPos(), mouseEvent->scenePos(), dynamic_cast<const QGraphicsView*>(mouseEvent->widget()->parentWidget())), Qt::IntersectsItemBoundingRect, Qt::DescendingOrder, viewTransform); QGraphicsItem *handle = NULL; for(int i = 0; i < itemsUnderMouse.size(); ++i) { if((itemsUnderMouse[i]->data(RCE_ITEM_TYPE_DATA_INDEX).toUInt() == HandleType) && itemsUnderMouse[i]->boundingRect().contains(itemsUnderMouse[i]->mapFromScene(mouseEvent->scenePos()))) { handle = itemsUnderMouse[i]; break; } } if(handle != NULL) { // there is handle, set is as active activeHandleIdx_ = 0; } else { activeHandleIdx_ = -1; } } break; case rce::gui::RImageMarkerScene::DrawPolygonMode: case rce::gui::RImageMarkerScene::DrawPolylineMode: { // check if there is handle under mouse QList<QGraphicsItem *> itemsUnderMouse = items(rce::gui::getSceneRectAroundScreenPos(mouseEvent->screenPos(), mouseEvent->scenePos(), dynamic_cast<const QGraphicsView*>(mouseEvent->widget()->parentWidget())), Qt::IntersectsItemBoundingRect, Qt::DescendingOrder, viewTransform); QGraphicsItem *handle = NULL; for(int i = 0; i < itemsUnderMouse.size(); ++i) { if((itemsUnderMouse[i]->data(RCE_ITEM_TYPE_DATA_INDEX).toUInt() == HandleType) && itemsUnderMouse[i]->boundingRect().contains(itemsUnderMouse[i]->mapFromScene(mouseEvent->scenePos()))) { handle = itemsUnderMouse[i]; break; } } if(handle != NULL) { // there is handle, set is as active activeHandleIdx_ = handle->data(RCE_ITEM_ID_DATA_INDEX).toInt(); } else { // there is not handle - create new addControlPoint(mouseEvent->scenePos()); itemEdited_ = true; activeHandleIdx_ = handles_.size() - 1; } } break; case rce::gui::RImageMarkerScene::PickPolygonMode: case rce::gui::RImageMarkerScene::PickPolylineMode: case rce::gui::RImageMarkerScene::PickPointMode: case rce::gui::RImageMarkerScene::PickAnyMode: { QVector<quint32> polygons; QVector<quint32> polylines; QVector<quint32> points; getItemsAtPosition(rce::gui::getSceneRectAroundScreenPos(mouseEvent->screenPos(), mouseEvent->scenePos(), dynamic_cast<const QGraphicsView*>(mouseEvent->widget()->parentWidget())), polygons, polylines, points, viewTransform); if(polygons.size() + polylines.size() + points.size() > 1) { // show menu QMap<QAction *, quint32> actionToPolygon; QMap<QAction *, quint32> actionToPolyline; QMap<QAction *, quint32> actionToPoint; QMenu *ctxMenu = new QMenu(mouseEvent->widget()); ctxMenu->setTitle(tr("Pick Item...")); foreach(quint32 polygonID, polygons) { actionToPolygon[ctxMenu->addAction(getPolygonDisplayName(polygonID))] = polygonID; } ctxMenu->addSeparator(); foreach(quint32 polylineID, polylines) { actionToPolyline[ctxMenu->addAction(getPolylineDisplayName(polylineID))] = polylineID; } ctxMenu->addSeparator(); foreach(quint32 pointID, points) { actionToPoint[ctxMenu->addAction(getPointDisplayName(pointID))] = pointID; } QAction *selectedAction = ctxMenu->exec(mouseEvent->screenPos()); if(actionToPolygon.contains(selectedAction)) { pickedItem_ = polygonItems_[actionToPolygon[selectedAction]]; emit pickedPolygon(actionToPolygon[selectedAction]); } else if(actionToPolyline.contains(selectedAction)) { pickedItem_ = polylineItems_[actionToPolyline[selectedAction]]; emit pickedPolyline(actionToPolyline[selectedAction]); } else if(actionToPoint.contains(selectedAction)) { pickedItem_ = pointItems_[actionToPoint[selectedAction]]; emit pickedPoint(actionToPoint[selectedAction]); } else { pickedItem_ = NULL; emit pickedNothing(); } ctxMenu->deleteLater(); } else { if(polygons.size() == 1) { pickedItem_ = polygonItems_[polygons[0]]; emit pickedPolygon(polygons[0]); } else if(polylines.size() == 1) { pickedItem_ = polylineItems_[polylines[0]]; emit pickedPolyline(polylines[0]); } else if(points.size() == 1) { pickedItem_ = pointItems_[points[0]]; emit pickedPoint(points[0]); } else { pickedItem_ = NULL; emit pickedNothing(); } } } break; }
void FriendWidget::contextMenuEvent(QContextMenuEvent * event) { QPoint pos = event->globalPos(); QString id = Core::getInstance()->getFriendAddress(friendId); QString dir = Settings::getInstance().getAutoAcceptDir(id); QMenu menu; QMenu* inviteMenu = menu.addMenu(tr("Invite to group","Menu to invite a friend to a groupchat")); QAction* copyId = menu.addAction(tr("Copy friend ID","Menu to copy the Tox ID of that friend")); QMap<QAction*, Group*> groupActions; for (Group* group : GroupList::groupList) { QAction* groupAction = inviteMenu->addAction(group->widget->getName()); groupActions[groupAction] = group; } if (groupActions.isEmpty()) inviteMenu->setEnabled(false); QAction* setAlias = menu.addAction(tr("Set alias...")); menu.addSeparator(); QAction* autoAccept = menu.addAction(tr("Auto accept files from this friend", "context menu entry")); autoAccept->setCheckable(true); autoAccept->setChecked(!dir.isEmpty()); menu.addSeparator(); QAction* removeFriendAction = menu.addAction(tr("Remove friend", "Menu to remove the friend from our friendlist")); QAction* selectedItem = menu.exec(pos); if (selectedItem) { if (selectedItem == copyId) { emit copyFriendIdToClipboard(friendId); return; } else if (selectedItem == setAlias) { setFriendAlias(); } else if (selectedItem == removeFriendAction) { hide(); show(); //Toggle visibility to work around bug of repaintEvent() not being fired on parent widget when this is hidden hide(); emit removeFriend(friendId); return; } else if (selectedItem == autoAccept) { if (!autoAccept->isChecked()) { qDebug() << "not checked"; dir = QDir::homePath(); autoAccept->setChecked(false); Settings::getInstance().setAutoAcceptDir(id, ""); } if (autoAccept->isChecked()) { dir = QFileDialog::getExistingDirectory(0, tr("Choose an auto accept directory","popup title"), dir); autoAccept->setChecked(true); qDebug() << "FriendWidget: setting auto accept dir for" << friendId << "to" << dir; Settings::getInstance().setAutoAcceptDir(id, dir); } } else if (groupActions.contains(selectedItem)) { Group* group = groupActions[selectedItem]; Core::getInstance()->groupInviteFriend(friendId, group->groupId); } } }
GPGME_Error GPGME::init(const QString & gpgHomeDir) { if (instancesStore.contains(gpgHomeDir)) { return GPG_ERR_NO_ERROR; } setlocale(LC_ALL, ""); gpgme_check_version(NULL); gpgme_set_locale(NULL, LC_CTYPE, setlocale (LC_CTYPE, NULL)); #ifdef LC_MESSAGES gpgme_set_locale (NULL, LC_MESSAGES, setlocale (LC_MESSAGES, NULL)); #endif gpgme_error_t err; gpgme_ctx_t context; err = gpgme_engine_check_version(GPGME_PROTOCOL_OpenPGP); if (err != GPG_ERR_NO_ERROR) { return err; } QString protocolName = gpgme_get_protocol_name(GPGME_PROTOCOL_OpenPGP); qDebug() << "protocol: " << protocolName; gpgme_engine_info_t engineInfo; err = gpgme_get_engine_info(&engineInfo); if (err != GPG_ERR_NO_ERROR) { return err; } qDebug() << "Backend info"; qDebug() << "filename: " << engineInfo->file_name << ", homedir: " << engineInfo->home_dir; err = gpgme_new(&context); if (err != GPG_ERR_NO_ERROR) { return err; } err = gpgme_set_protocol(context, GPGME_PROTOCOL_OpenPGP); if (err != GPG_ERR_NO_ERROR) { return err; } // we don't need to set gnupg home dir explicitly QString gnupgHome; if (gpgHomeDir.isEmpty()) { // i.e. use default gnupg directory or one from environment QString gnupgHomeEnv = QString::fromLatin1(qgetenv("GNUPGHOME")); if (!gnupgHomeEnv.isEmpty()) { gnupgHome = gnupgHomeEnv; } else { // use default path: "~/.gnupg" QDir gh = QDir::home(); gh.cd(".gnupg"); gnupgHome = gh.canonicalPath(); } } else { QDir gh(gpgHomeDir); gnupgHome = gh.canonicalPath(); } qDebug() << "GNUPGHOME" << gnupgHome; err = gpgme_ctx_set_engine_info(context, GPGME_PROTOCOL_OpenPGP, engineInfo->file_name, gnupgHome.toLatin1().data() ); if (err != GPG_ERR_NO_ERROR) { return err; } GPGME * inst = new GPGME(context, gnupgHome); instancesStore[gpgHomeDir] = inst; qDebug() << "gpgme initalized for the directory " << gnupgHome << "[store key: " << gpgHomeDir << "]"; return GPG_ERR_NO_ERROR; }
Response::ResponseCode Server_ProtocolHandler::processGameCommandContainer(const CommandContainer &cont, ResponseContainer &rc) { static QList<GameCommand::GameCommandType> antifloodCommandsWhiteList = QList<GameCommand::GameCommandType>() // draw/undo card draw (example: drawing 10 cards one by one from the deck) << GameCommand::DRAW_CARDS << GameCommand::UNDO_DRAW // create, delete arrows (example: targeting with 10 cards during an attack) << GameCommand::CREATE_ARROW << GameCommand::DELETE_ARROW // set card attributes (example: tapping 10 cards at once) << GameCommand::SET_CARD_ATTR // increment / decrement counter (example: -10 life points one by one) << GameCommand::INC_COUNTER // mulling lots of hands in a row << GameCommand::MULLIGAN // allows a user to sideboard without receiving flooding message << GameCommand::MOVE_CARD; if (authState == NotLoggedIn) return Response::RespLoginNeeded; QMap<int, QPair<int, int> > gameMap = getGames(); if (!gameMap.contains(cont.game_id())) return Response::RespNotInRoom; const QPair<int, int> roomIdAndPlayerId = gameMap.value(cont.game_id()); QReadLocker roomsLocker(&server->roomsLock); Server_Room *room = server->getRooms().value(roomIdAndPlayerId.first); if (!room) return Response::RespNotInRoom; QReadLocker roomGamesLocker(&room->gamesLock); Server_Game *game = room->getGames().value(cont.game_id()); if (!game) { if (room->getExternalGames().contains(cont.game_id())) { server->sendIsl_GameCommand(cont, room->getExternalGames().value(cont.game_id()).server_id(), userInfo->session_id(), roomIdAndPlayerId.first, roomIdAndPlayerId.second ); return Response::RespNothing; } return Response::RespNotInRoom; } QMutexLocker gameLocker(&game->gameMutex); Server_Player *player = game->getPlayers().value(roomIdAndPlayerId.second); if (!player) return Response::RespNotInRoom; int commandCountingInterval = server->getCommandCountingInterval(); int maxCommandCountPerInterval = server->getMaxCommandCountPerInterval(); GameEventStorage ges; Response::ResponseCode finalResponseCode = Response::RespOk; for (int i = cont.game_command_size() - 1; i >= 0; --i) { const GameCommand &sc = cont.game_command(i); logDebugMessage(QString("game %1 player %2: ").arg(cont.game_id()).arg(roomIdAndPlayerId.second) + QString::fromStdString(sc.ShortDebugString())); if (commandCountingInterval > 0) { int totalCount = 0; if (commandCountOverTime.isEmpty()) commandCountOverTime.prepend(0); if(!antifloodCommandsWhiteList.contains((GameCommand::GameCommandType) getPbExtension(sc))) ++commandCountOverTime[0]; for (int i = 0; i < commandCountOverTime.size(); ++i) totalCount += commandCountOverTime[i]; if (totalCount > maxCommandCountPerInterval) return Response::RespChatFlood; } Response::ResponseCode resp = player->processGameCommand(sc, rc, ges); if (resp != Response::RespOk) finalResponseCode = resp; } ges.sendToGame(game); return finalResponseCode; }
bool KMCupsJobManager::editJobAttributes(KMJob *j) { IppRequest req; req.setOperation(IPP_GET_JOB_ATTRIBUTES); req.addURI(IPP_TAG_OPERATION, "job-uri", j->uri()); /* if (!j->uri().isEmpty()) { KURL url(j->uri()); req.setHost(url.host()); req.setPort(url.port()); } */ if (!req.doRequest("/")) { KMManager::self()->setErrorMsg(i18n("Unable to retrieve job information: ")+req.statusMessage()); return false; } QMap<QString,QString> opts = req.toMap(IPP_TAG_JOB); // translate the "Copies" option to non-CUPS syntax if (opts.contains("copies")) opts["kde-copies"] = opts["copies"]; if (opts.contains("page-set")) opts["kde-pageset"] = (opts["page-set"] == "even" ? "2" : (opts["page-set"] == "odd" ? "1" : "0")); if (opts.contains("OutputOrder")) opts["kde-pageorder"] = opts["OutputOrder"]; if (opts.contains("multiple-document-handling")) opts["kde-collate"] = (opts["multiple-document-handling"] == "separate-documents-collated-copies" ? "Collate" : "Uncollate"); if (opts.contains("page-ranges")) opts["kde-range"] = opts["page-ranges"]; // find printer and construct dialog KMPrinter *prt = KMManager::self()->findPrinter(j->printer()); if (!prt) { KMManager::self()->setErrorMsg(i18n("Unable to find printer %1.").arg(j->printer())); return false; } KMManager::self()->completePrinterShort(prt); KPrinter::ApplicationType oldAppType = KPrinter::applicationType(); KPrinter::setApplicationType(KPrinter::StandAlone); KPrinterPropertyDialog dlg(prt); dlg.setDriver(KMManager::self()->loadPrinterDriver(prt)); KMFactory::self()->uiManager()->setupPrinterPropertyDialog(&dlg); KPrinter::setApplicationType( oldAppType ); if (dlg.driver()) dlg.addPage(new KPDriverPage(prt, dlg.driver(), &dlg)); dlg.addPage(new KPCopiesPage(0, &dlg)); dlg.addPage(new KPSchedulePage(&dlg)); dlg.addPage(new KPTagsPage(true, &dlg)); dlg.setOptions(opts); dlg.enableSaveButton(false); dlg.setCaption(i18n("Attributes of Job %1@%2 (%3)").arg(j->id()).arg(j->printer()).arg(j->name())); if (dlg.exec()) { opts.clear(); // include default values to override non-default values dlg.getOptions(opts, true); // translate the "Copies" options from non-CUPS syntax opts["copies"] = opts["kde-copies"]; opts["OutputOrder"] = opts["kde-pageorder"]; opts["multiple-document-handling"] = (opts["kde-collate"] == "Collate" ? "separate-documents-collated-copies" : "separate-documents-uncollated-copies"); opts["page-set"] = (opts["kde-pageset"] == "1" ? "odd" : (opts["kde-pageset"] == "2" ? "even" : "all")); // it seems CUPS is buggy. Disable page-ranges modification, otherwise nothing gets printed opts["page-ranges"] = processRange(opts["kde-range"]); req.init(); req.setOperation(IPP_SET_JOB_ATTRIBUTES); req.addURI(IPP_TAG_OPERATION, "job-uri", j->uri()); req.addName(IPP_TAG_OPERATION, "requesting-user-name", CupsInfos::self()->login()); req.setMap(opts); //req.dump(1); if (!req.doRequest("/jobs/")) { KMManager::self()->setErrorMsg(i18n("Unable to set job attributes: ")+req.statusMessage()); return false; } } return true; }
bool SASLAuthFeature::xmppStanzaIn(IXmppStream *AXmppStream, Stanza &AStanza, int AOrder) { if (AXmppStream==FXmppStream && AOrder==XSHO_XMPP_FEATURE) { if (AStanza.kind() == "challenge") { QByteArray challengeData = QByteArray::fromBase64(AStanza.element().text().toLatin1()); LOG_STRM_DEBUG(FXmppStream->streamJid(),QString("SASL auth challenge received: %1").arg(QString::fromUtf8(challengeData))); QMap<QByteArray, QByteArray> responseMap; QMap<QByteArray, QByteArray> challengeMap = parseChallenge(challengeData); if (challengeMap.value("qop") == "auth") { QByteArray randBytes(32,' '); for (int i=0; i<randBytes.size(); i++) randBytes[i] = (char) (256.0 * qrand() / (RAND_MAX + 1.0)); responseMap["cnonce"] = randBytes.toHex(); if (challengeMap.contains("realm")) responseMap["realm"] = challengeMap.value("realm"); else responseMap["realm"] = FXmppStream->streamJid().pDomain().toUtf8(); responseMap["username"] = FXmppStream->streamJid().pNode().toUtf8(); responseMap["nonce"] = challengeMap.value("nonce"); responseMap["nc"] = "00000001"; responseMap["qop"] = "auth"; responseMap["digest-uri"] = QString("xmpp/%1").arg(FXmppStream->streamJid().pDomain()).toUtf8(); responseMap["charset"] = "utf-8"; responseMap["response"] = getResponseValue(responseMap,FXmppStream->password()); } QByteArray responseData = serializeResponse(responseMap); Stanza response("response",NS_FEATURE_SASL); response.element().appendChild(response.createTextNode(responseData.toBase64())); FXmppStream->sendStanza(response); LOG_STRM_DEBUG(FXmppStream->streamJid(),QString("SASL auth response sent: %1").arg(QString::fromUtf8(responseData))); } else { FXmppStream->removeXmppStanzaHandler(XSHO_XMPP_FEATURE,this); if (AStanza.kind() == "success") { LOG_STRM_INFO(FXmppStream->streamJid(),"Authorization successes"); deleteLater(); emit finished(true); } else if (AStanza.kind() == "failure") { XmppSaslError err(AStanza.element()); LOG_STRM_WARNING(FXmppStream->streamJid(),QString("Authorization failed: %1").arg(err.condition())); emit error(err); } else { XmppError err(IERR_SASL_AUTH_INVALID_RESPONSE); LOG_STRM_WARNING(FXmppStream->streamJid(),QString("Authorization error: Invalid stanza kind=%1").arg(AStanza.kind())); emit error(err); } } return true; } return false; }
bool HsMenuClientPrivate::add(const QVariantMap &entryPreference) { bool result = false; QMap<QString, QVariant> pref = entryPreference; CaIconDescription iconDesc; if(pref.contains(hsItemId)) { QSharedPointer<CaEntry> update_entry = CaService::instance()->getEntry(pref.take(hsItemId).toInt()); if(pref.contains(hsItemLocName)) { update_entry->setText(pref.take(hsItemLocName).toString(),true); } else { update_entry->setText(pref.take(hsItemName).toString()); } if(pref.contains(hsItemLocDescription)) { update_entry->setDescription(pref.take(hsItemLocDescription).toString(), true); } else { update_entry->setDescription(pref.take(hsItemDescription).toString()); } iconDesc.setFilename(pref.take(hsIconFileName).toString()); iconDesc.setSkinId(pref.take(hsIconName).toString()); iconDesc.setApplicationId(pref.take(hsIconApplicationId).toString()); update_entry->setIconDescription(iconDesc); QMapIterator<QString, QVariant> k(pref); while (k.hasNext()) { k.next(); update_entry->setAttribute(k.key(),k.value().toString()); } result = CaService::instance()->updateEntry(*update_entry); } else if ((pref.contains(hsItemName) || pref.contains(hsItemLocName)) && pref.contains(hsitemLaunchUri) && pref.contains(hsitemPublisherId)) { CaEntry add_entry(ItemEntryRole); add_entry.setEntryTypeName(Hs::templatedApplicationTypeName); // mandatory values if(pref.contains(hsItemLocName)) { add_entry.setText(pref.take(hsItemLocName).toString(),true); } else { add_entry.setText(pref.take(hsItemName).toString()); } iconDesc.setFilename(pref.take(hsIconFileName).toString()); iconDesc.setSkinId(pref.take(hsIconName).toString()); iconDesc.setApplicationId(pref.take(hsIconApplicationId).toString()); add_entry.setIconDescription(iconDesc); if(pref.contains(hsItemLocDescription)) { add_entry.setDescription(pref.take(hsItemLocDescription).toString(), true); } else { add_entry.setDescription(pref.take(hsItemDescription).toString()); } QMapIterator<QString, QVariant> k(pref); while (k.hasNext()) { k.next(); add_entry.setAttribute(k.key(),k.value().toString()); } add_entry.setFlags(add_entry.flags() & ~RemovableEntryFlag); QSharedPointer<CaEntry> entry = CaService::instance()->createEntry(add_entry); if (!entry.isNull()) { result = true; } } else { return false; } return result; }
// This method will cause the class to rebuild its text representation. // based on the parent classifier object. // For any situation in which this is called, we are either building the code // document up, or replacing/regenerating the existing auto-generated parts. As // such, we will want to insert everything we resonablely will want // during creation. We can set various parts of the document (esp. the // comments) to appear or not, as needed. void DClassifierCodeDocument::updateContent() { // Gather info on the various fields and parent objects of this class... UMLClassifier * c = getParentClassifier(); Q_ASSERT(c != 0); CodeGenerationPolicy * commonPolicy = UMLApp::app()->commonPolicy(); CodeGenPolicyExt * pe = UMLApp::app()->policyExt(); DCodeGenerationPolicy * policy = dynamic_cast<DCodeGenerationPolicy*>(pe); // first, set the global flag on whether or not to show classfield info // This depends on whether or not we have attribute/association classes const CodeClassFieldList * cfList = getCodeClassFieldList(); CodeClassFieldList::const_iterator it = cfList->begin(); CodeClassFieldList::const_iterator end = cfList->end(); for (; it != end; ++it) { CodeClassField * field = *it; if (field->parentIsAttribute()) field->setWriteOutMethods(policy->getAutoGenerateAttribAccessors()); else field->setWriteOutMethods(policy->getAutoGenerateAssocAccessors()); } // attribute-based ClassFields // we do it this way to have the static fields sorted out from regular ones CodeClassFieldList staticAttribClassFields = getSpecificClassFields (CodeClassField::Attribute, true); CodeClassFieldList attribClassFields = getSpecificClassFields (CodeClassField::Attribute, false); // association-based ClassFields // don't care if they are static or not..all are lumped together CodeClassFieldList plainAssocClassFields = getSpecificClassFields (CodeClassField::PlainAssociation); CodeClassFieldList aggregationClassFields = getSpecificClassFields (CodeClassField::Aggregation); CodeClassFieldList compositionClassFields = getSpecificClassFields (CodeClassField::Composition); bool isInterface = parentIsInterface(); bool hasOperationMethods = false; UMLOperationList list = c->getOpList(); hasOperationMethods = ! list.isEmpty(); QString endLine = commonPolicy->getNewLineEndingChars(); // a shortcut..so we don't have to call this all the time // // START GENERATING CODE/TEXT BLOCKS and COMMENTS FOR THE DOCUMENT // // // PACKAGE CODE BLOCK // QString pkgs = getPackage(); pkgs.replace(QRegExp(QLatin1String("::")), QLatin1String(".")); QString packageText = getPackage().isEmpty() ? QString() : QString(QLatin1String("package ")+pkgs+QLatin1Char(';')+endLine); CodeBlockWithComments * pblock = addOrUpdateTaggedCodeBlockWithComments(QLatin1String("packages"), packageText, QString(), 0, false); if (packageText.isEmpty() && pblock->contentType() == CodeBlock::AutoGenerated) pblock->setWriteOutText(false); else pblock->setWriteOutText(true); // IMPORT CODEBLOCK // // Q: Why all utils? Aren't just List and Vector the only classes we are using? // A: doesn't matter at all; it is more readable to just include '*' and d compilers // don't slow down or anything. (TZ) QString importStatement; if (hasObjectVectorClassFields()) importStatement.append(QLatin1String("import d.util.*;")); //only import classes in a different package from this class UMLPackageList imports; QMap<UMLPackage*, QString> packageMap; // so we don't repeat packages CodeGenerator::findObjectsRelated(c, imports); for (UMLPackageListIt importsIt(imports); importsIt.hasNext();) { UMLPackage *con = importsIt.next(); // NO (default) datatypes in the import statement.. use defined // ones whould be possible, but no idea how to do that...at least for now. // Dynamic casting is slow..not an optimal way to do this. if (!packageMap.contains(con) && !con->isUMLDatatype()) { packageMap.insert(con, con->package()); // now, we DON'T need to import classes that are already in our own package // (that is, IF a package is specified). Otherwise, we should have a declaration. if (con->package() != c->package() || (c->package().isEmpty() && con->package().isEmpty())) { importStatement.append(endLine+QLatin1String("import ")); if (!con->package().isEmpty()) importStatement.append(con->package()+QLatin1Char('.')); importStatement.append(CodeGenerator::cleanName(con->name())+QLatin1Char(';')); } } } // now, add/update the imports codeblock CodeBlockWithComments * iblock = addOrUpdateTaggedCodeBlockWithComments(QLatin1String("imports"), importStatement, QString(), 0, false); if (importStatement.isEmpty() && iblock->contentType() == CodeBlock::AutoGenerated) iblock->setWriteOutText(false); else iblock->setWriteOutText(true); // CLASS DECLARATION BLOCK // // get the declaration block. If it is not already present, add it too DClassDeclarationBlock * myClassDeclCodeBlock = getClassDecl(); addTextBlock(myClassDeclCodeBlock); // note: wont add if already present // NOW create document in sections.. // now we want to populate the body of our class // our layout is the following general groupings of code blocks: // start d classifier document // header comment // package code block // import code block // class declaration // section: // - class field declaration section comment // - class field declarations (0+ codeblocks) // section: // - methods section comment // sub-section: constructor ops // - constructor method section comment // - constructor methods (0+ codeblocks) // sub-section: accessors // - accessor method section comment // - static accessor methods (0+ codeblocks) // - non-static accessor methods (0+ codeblocks) // sub-section: non-constructor ops // - operation method section comment // - operations (0+ codeblocks) // end class declaration // end d classifier document // Q: Why use the more complicated scheme of arranging code blocks within codeblocks? // A: This will allow us later to preserve the format of our document so that if // codeblocks are added, they may be easily added in the correct place, rather than at // the end of the document, or by using a difficult algorithm to find the location of // the last appropriate code block sibling (which may not exist.. for example user adds // a constructor operation, but there currently are no constructor code blocks // within the document). // // * CLASS FIELD declaration section // // get/create the field declaration code block HierarchicalCodeBlock * fieldDeclBlock = myClassDeclCodeBlock->getHierarchicalCodeBlock(QLatin1String("fieldsDecl"), QLatin1String("Fields"), 1); // Update the comment: we only set comment to appear under the following conditions CodeComment * fcomment = fieldDeclBlock->getComment(); if (isInterface || (!forceDoc() && !hasClassFields())) fcomment->setWriteOutText(false); else fcomment->setWriteOutText(true); // now actually declare the fields within the appropriate HCodeBlock declareClassFields(staticAttribClassFields, fieldDeclBlock); declareClassFields(attribClassFields, fieldDeclBlock); declareClassFields(plainAssocClassFields, fieldDeclBlock); declareClassFields(aggregationClassFields, fieldDeclBlock); declareClassFields(compositionClassFields, fieldDeclBlock); // // METHODS section // // get/create the method codeblock HierarchicalCodeBlock * methodsBlock = myClassDeclCodeBlock->getHierarchicalCodeBlock(QLatin1String("methodsBlock"), QLatin1String("Methods"), 1); // Update the section comment CodeComment * methodsComment = methodsBlock->getComment(); // set conditions for showing this comment if (!forceDoc() && !hasClassFields() && !hasOperationMethods) methodsComment->setWriteOutText(false); else methodsComment->setWriteOutText(true); // METHODS sub-section : constructor methods // // get/create the constructor codeblock HierarchicalCodeBlock * constBlock = methodsBlock->getHierarchicalCodeBlock(QLatin1String("constructorMethods"), QLatin1String("Constructors"), 1); constructorBlock = constBlock; // record this codeblock for later, when operations are updated // special condiions for showing comment: only when autogenerateding empty constructors // Although, we *should* check for other constructor methods too CodeComment * constComment = constBlock->getComment(); CodeGenerationPolicy *pol = UMLApp::app()->commonPolicy(); if (!forceDoc() && (isInterface || !pol->getAutoGenerateConstructors())) constComment->setWriteOutText(false); else constComment->setWriteOutText(true); // add/get the empty constructor QString DClassName = getDClassName(c->name()); QString emptyConstStatement = QLatin1String("public ")+DClassName+QLatin1String(" () { }"); CodeBlockWithComments * emptyConstBlock = constBlock->addOrUpdateTaggedCodeBlockWithComments(QLatin1String("emptyconstructor"), emptyConstStatement, QLatin1String("Empty Constructor"), 1, false); // Now, as an additional condition we only show the empty constructor block // IF it was desired to be shown if (parentIsClass() && pol->getAutoGenerateConstructors()) emptyConstBlock->setWriteOutText(true); else emptyConstBlock->setWriteOutText(false); // METHODS subsection : ACCESSOR METHODS // // get/create the accessor codeblock HierarchicalCodeBlock * accessorBlock = methodsBlock->getHierarchicalCodeBlock(QLatin1String("accessorMethods"), QLatin1String("Accessor Methods"), 1); // set conditions for showing section comment CodeComment * accessComment = accessorBlock->getComment(); if (!forceDoc() && !hasClassFields()) accessComment->setWriteOutText(false); else accessComment->setWriteOutText(true); // now, 2 sub-sub sections in accessor block // add/update accessor methods for attributes HierarchicalCodeBlock * staticAccessors = accessorBlock->getHierarchicalCodeBlock(QLatin1String("staticAccessorMethods"), QString(), 1); staticAccessors->getComment()->setWriteOutText(false); // never write block comment staticAccessors->addCodeClassFieldMethods(staticAttribClassFields); staticAccessors->addCodeClassFieldMethods(attribClassFields); // add/update accessor methods for associations HierarchicalCodeBlock * regularAccessors = accessorBlock->getHierarchicalCodeBlock(QLatin1String("regularAccessorMethods"), QString(), 1); regularAccessors->getComment()->setWriteOutText(false); // never write block comment regularAccessors->addCodeClassFieldMethods(plainAssocClassFields); regularAccessors->addCodeClassFieldMethods(aggregationClassFields); regularAccessors->addCodeClassFieldMethods(compositionClassFields); // METHODS subsection : Operation methods (which arent constructors) // // get/create the operations codeblock operationsBlock = methodsBlock->getHierarchicalCodeBlock(QLatin1String("operationMethods"), QLatin1String("Operations"), 1); // set conditions for showing section comment CodeComment * ocomment = operationsBlock->getComment(); if (!forceDoc() && !hasOperationMethods) ocomment->setWriteOutText(false); else ocomment->setWriteOutText(true); }
void ANNClassifier::trainClassifier( SuspectLibraryPtr suspectLibrary, QMap<QString,QVariant> trainingParameters ) { bool ok = true; /// @todo add a fetch required parameters method to query which parameters are required for training /// @todo Move the input and output width parameters down into the base class // Fetch the input width for this classifier SOMError::requireCondition( trainingParameters.contains( "inputWidth" ), "Missing required input width parameter" ); inputWidth = trainingParameters[ "inputWidth" ].toInt( &ok ); SOMError::requireCondition( ok, "Failed to convert input width parameter" ); SOMError::requireCondition( inputWidth > 0, "Invalid input size" ); // Fetch the output width for this classifier SOMError::requireCondition( trainingParameters.contains( "outputWidth" ), "Missing required output width parameter" ); outputWidth = trainingParameters[ "outputWidth" ].toInt( &ok ); SOMError::requireCondition( ok, "Failed to convert output width parameter" ); SOMError::requireCondition( outputWidth > 0, "Invalid output size" ); // Fetch the iterations parameter for this classifier int iterations = 0; if( trainingParameters.contains( "iterations" ) ) { iterations = trainingParameters[ "iterations" ].toInt( &ok ); SOMError::requireCondition( ok, "Failed to convert iterations parameter" ); SOMError::requireCondition( iterations > 0, "Invalid iterations value" ); } // Fetch the iterations parameter for this classifier double epsilon = 0.0; if( trainingParameters.contains( "epsilon" ) ) { epsilon = trainingParameters[ "epsilon" ].toDouble( &ok ); SOMError::requireCondition( ok, "Failed to convert epsilon parameter" ); SOMError::requireCondition( epsilon > 0.0, "Invalid epsilon value" ); } QVector< SuspectPtr > suspects = suspectLibrary->suspects(); /* Make an input matrix for training the back-end MLPANN. * This is a matrix composed of vectors the length of the SOM's area ( width x height ) */ cv::Mat_<double> input( suspects.size(), inputWidth, 0.0 ); /* Make an output matrix for trainig the back-end MLPANN. * This is a matrix composed of vectors the length of the number of classification categories. */ cv::Mat_<double> output( suspects.size(), outputWidth, 0.0 ); for( int i=0; i<suspects.size(); i++ ) { SuspectPtr suspect = suspects[i]; HistogramPtr histogram = suspect->histogram(); // Set the input for the training input matrix row to the histogram of the suspect for( int j=0; j<inputWidth; j++ ) input( i, j ) = histogram->bin( j ); // Set the output value for the real category of the suspect to 1. All other values will already be 0 output( i, suspect->realCategory() ) = 1.0; } cv::TermCriteria terminationCriteria; terminationCriteria.type = 0; if( iterations != 0 ) terminationCriteria.type += cv::TermCriteria::MAX_ITER; if( epsilon != 0.0 ) terminationCriteria.type += cv::TermCriteria::EPS; cv::ANN_MLP_TrainParams trainingParams( terminationCriteria, CvANN_MLP_TrainParams::RPROP, iterations, epsilon ); int normFlag = 0; int tmp[4]; // The input layer has one node for each element in the input histograms tmp[0] = inputWidth; // The first hidden layer is half the size of the input layer tmp[1] = inputWidth / 2; // The second input layer is one quarter the size of the input layer tmp[2] = inputWidth / 4; // The output layer has one node for each category tmp[3] = outputWidth; CvMat ls = cvMat( 4, 1, CV_32S, tmp ); // If there is already an MPLANN attached to this HSOM, delete it to start over if( _ann != NULL ) delete _ann; // Create a new MLPANN for the HSOM _ann = new CvANN_MLP( &ls, CvANN_MLP::SIGMOID_SYM ); _ann->train( input, output, cv::Mat(), cv::Mat(), trainingParams, normFlag ); }
void DisplayWidget::setupFragmentShader() { QMap<QString, bool> textureCacheUsed; if (shaderProgram) { shaderProgram->release(); } delete(shaderProgram); shaderProgram = new QGLShaderProgram(this); // Vertex shader bool s = false; s = shaderProgram->addShaderFromSourceCode(QGLShader::Vertex,fragmentSource.vertexSource.join("\n")); if (fragmentSource.vertexSource.count() == 0) { WARNING("No vertex shader found!"); s = false; } if (!s) WARNING("Could not create vertex shader: " + shaderProgram->log()); if (!s) { delete(shaderProgram); shaderProgram = 0; return; } if (!shaderProgram->log().isEmpty()) INFO("Vertex shader compiled with warnings: " + shaderProgram->log()); // Fragment shader s = shaderProgram->addShaderFromSourceCode(QGLShader::Fragment, fragmentSource.getText()); if (!s) WARNING("Could not create fragment shader: " + shaderProgram->log()); if (!s) { delete(shaderProgram); shaderProgram = 0; return; } if (!shaderProgram->log().isEmpty()) INFO("Fragment shader compiled with warnings: " + shaderProgram->log()); s = shaderProgram->link(); if (!s) WARNING("Could not link shaders: " + shaderProgram->log()); if (!s) { delete(shaderProgram); shaderProgram = 0; return; } if (!shaderProgram->log().isEmpty()) INFO("Fragment shader compiled with warnings: " + shaderProgram->log()); s = shaderProgram->bind(); if (!s) WARNING("Could not bind shaders: " + shaderProgram->log()); if (!s) { delete(shaderProgram); shaderProgram = 0; return; } // Setup textures. int u = 0; // Bind first texture to backbuffer int l = shaderProgram->uniformLocation("backbuffer"); if (l != -1) { if (bufferType != None) { glActiveTexture(GL_TEXTURE0+u); // non-standard (>OpenGL 1.3) gl extension GLuint i = backBuffer->texture(); glBindTexture(GL_TEXTURE_2D,i); if (fragmentSource.textureParams.contains("backbuffer")) { setGlTexParameter(fragmentSource.textureParams["backbuffer"]); } shaderProgram->setUniformValue(l, (GLuint)u); //INFO(QString("Binding back buffer (ID: %1) to active texture %2").arg(backBuffer->texture()).arg(u)); //INFO(QString("Setting uniform backbuffer to active texture %2").arg(u)); u++; } else { WARNING("Trying to use a backbuffer, but no bufferType set."); WARNING("Use the buffer define, e.g.: '#buffer RGBA8' "); } } for (QMap<QString, QString>::iterator it = fragmentSource.textures.begin(); it!=fragmentSource.textures.end(); it++) { QString textureName = it.key(); QString texturePath = it.value(); QImage im(texturePath); if (im.isNull() && !texturePath.endsWith(".hdr", Qt::CaseInsensitive)) { WARNING("Failed to load texture: " + QFileInfo(texturePath).absoluteFilePath()); } else { int l = shaderProgram->uniformLocation(textureName); if (l != -1) { if (im.isNull()) { GLuint texture = 0; // set current texture glActiveTexture(GL_TEXTURE0+u); // non-standard (>OpenGL 1.3) gl extension // allocate a texture id if (TextureCache.contains(texturePath)) { textureCacheUsed[texturePath] = true; int textureID = TextureCache[texturePath]; glBindTexture(GL_TEXTURE_2D, textureID ); INFO(QString("Found texture in cache: %1 (id: %2)").arg(texturePath).arg(textureID)); } else { glPixelStorei(GL_UNPACK_ALIGNMENT, 1); glGenTextures(1, &texture ); INFO(QString("Allocated texture ID: %1").arg(texture)); glBindTexture(GL_TEXTURE_2D, texture ); //glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // TODO: If I don't keep this line, HDR images don't work. // It must be a symptom of some kind of error in the OpenGL setup. glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); if (fragmentSource.textureParams.contains(textureName)) { setGlTexParameter(fragmentSource.textureParams[textureName]); } HDRLoaderResult result; HDRLoader::load(texturePath.toAscii().data(), result); INFO(QString("Hdrloader found HDR image: %1 x %2").arg(result.width).arg(result.height)); glTexImage2D(GL_TEXTURE_2D, 0, 0x8815 , result.width, result.height, 0, GL_RGB, GL_FLOAT, result.cols); //INFO(QString("Binding %0 (ID: %1) to active texture %2").arg(textureName+":"+texturePath).arg(texture).arg(u)); TextureCache[texturePath] = texture; textureCacheUsed[texturePath] = true; } shaderProgram->setUniformValue(l, (GLuint)u); //INFO(QString("Setting uniform %0 to active texture %2").arg(textureName).arg(u)); } else { glActiveTexture(GL_TEXTURE0+u); // non-standard (>OpenGL 1.3) gl extension GLuint textureID; if (TextureCache.contains(texturePath)) { textureCacheUsed[texturePath] = true; textureID = TextureCache[texturePath]; INFO(QString("Found texture in cache: %1").arg(texturePath)); } else { textureID = bindTexture(texturePath, GL_TEXTURE_2D, GL_RGBA); TextureCache[texturePath] = textureID; textureCacheUsed[texturePath] = true; } glBindTexture(GL_TEXTURE_2D,textureID); //INFO(QString("Binding %0 (ID: %1) to active texture %2").arg(textureName+":"+texturePath).arg(textureID).arg(u)); shaderProgram->setUniformValue(l, (GLuint)u); //INFO(QString("Setting uniform %0 to active texture %2").arg(textureName).arg(u)); if (fragmentSource.textureParams.contains(textureName)) { setGlTexParameter(fragmentSource.textureParams[textureName]); } } } else { WARNING("Could not locate sampler2D uniform: " + textureName); } u++; } } nextActiveTexture = u; setupBufferShader(); // Check for unused textures QMapIterator<QString, int> i(TextureCache); while (i.hasNext()) { i.next(); if (!textureCacheUsed.contains(i.key())) { INFO("Removing texture from cache: " +i.key()); GLuint id = i.value(); glDeleteTextures(1, &id); TextureCache.remove(i.key()); } else { //INFO("Used texture: " +i.key()); } } }
/** \fn AutoExpire::CalcParams() * Calculates how much space needs to be cleared, and how often. */ void AutoExpire::CalcParams() { VERBOSE(VB_FILE, LOC + "CalcParams()"); vector<FileSystemInfo> fsInfos; if (mainServer) mainServer->GetFilesystemInfos(fsInfos); if (fsInfos.empty()) { QString msg = "ERROR: Filesystem Info cache is empty, unable to " "calculate necessary parameters."; VERBOSE(VB_IMPORTANT, LOC + msg); gCoreContext->LogEntry("mythbackend", LP_WARNING, "Autoexpire CalcParams", msg); return; } size_t maxKBperMin = 0; size_t extraKB = gCoreContext->GetNumSetting("AutoExpireExtraSpace", 0) << 20; QMap<int, uint64_t> fsMap; QMap<int, vector<int> > fsEncoderMap; // we use this copying on purpose. The used_encoders map ensures // that every encoder writes only to one fs. // Copying the data minimizes the time the lock is held instance_lock.lock(); QMap<int, int>::const_iterator ueit = used_encoders.begin(); while (ueit != used_encoders.end()) { fsEncoderMap[*ueit].push_back(ueit.key()); ++ueit; } instance_lock.unlock(); vector<FileSystemInfo>::iterator fsit; for (fsit = fsInfos.begin(); fsit != fsInfos.end(); ++fsit) { if (fsMap.contains(fsit->fsID)) continue; fsMap[fsit->fsID] = 0; size_t thisKBperMin = 0; // append unknown recordings to all fsIDs vector<int>::iterator unknownfs_it = fsEncoderMap[-1].begin(); for (; unknownfs_it != fsEncoderMap[-1].end(); ++unknownfs_it) fsEncoderMap[fsit->fsID].push_back(*unknownfs_it); if (fsEncoderMap.contains(fsit->fsID)) { VERBOSE(VB_FILE, QString( "fsID #%1: Total: %2 GB Used: %3 GB Free: %4 GB") .arg(fsit->fsID) .arg(fsit->totalSpaceKB / 1024.0 / 1024.0, 7, 'f', 1) .arg(fsit->usedSpaceKB / 1024.0 / 1024.0, 7, 'f', 1) .arg(fsit->freeSpaceKB / 1024.0 / 1024.0, 7, 'f', 1)); vector<int>::iterator encit = fsEncoderMap[fsit->fsID].begin(); for (; encit != fsEncoderMap[fsit->fsID].end(); ++encit) { EncoderLink *enc = *(encoderList->find(*encit)); if (!enc->IsConnected() || !enc->IsBusy()) { // remove the encoder since it can't write to any file system VERBOSE(VB_FILE, LOC + QString("Cardid %1: is not recoding, removing it " "from used list.").arg(*encit)); instance_lock.lock(); used_encoders.remove(*encit); instance_lock.unlock(); continue; } long long maxBitrate = enc->GetMaxBitrate(); if (maxBitrate<=0) maxBitrate = 19500000LL; thisKBperMin += (((size_t)maxBitrate)*((size_t)15))>>11; VERBOSE(VB_FILE, QString(" Cardid %1: max bitrate " "%2 Kb/sec, fsID %3 max is now %4 KB/min") .arg(enc->GetCardID()) .arg(enc->GetMaxBitrate() >> 10) .arg(fsit->fsID) .arg(thisKBperMin)); } } fsMap[fsit->fsID] = thisKBperMin; if (thisKBperMin > maxKBperMin) { VERBOSE(VB_FILE, QString(" Max of %1 KB/min for fsID %2 is higher " "than the existing Max of %3 so we'll use this Max instead") .arg(thisKBperMin).arg(fsit->fsID).arg(maxKBperMin)); maxKBperMin = thisKBperMin; } }
// This method will cause the class to rebuild its text representation. // based on the parent classifier object. // For any situation in which this is called, we are either building the code // document up, or replacing/regenerating the existing auto-generated parts. As // such, we will want to insert everything we resonablely will want // during creation. We can set various parts of the document (esp. the // comments) to appear or not, as needed. void CPPHeaderCodeDocument::updateContent( ) { // Gather info on the various fields and parent objects of this class... UMLClassifier * c = getParentClassifier(); CodeGenPolicyExt *pe = UMLApp::app()->policyExt(); CPPCodeGenerationPolicy * policy = dynamic_cast<CPPCodeGenerationPolicy*>(pe); // first, set the global flag on whether or not to show classfield info const CodeClassFieldList * cfList = getCodeClassFieldList(); CodeClassFieldList::const_iterator it = cfList->begin(); CodeClassFieldList::const_iterator end = cfList->end(); for( ; it != end; ++it ) (*it)->setWriteOutMethods(policy->getAutoGenerateAccessors()); // attribute-based ClassFields // we do it this way to have the static fields sorted out from regular ones CodeClassFieldList staticPublicAttribClassFields = getSpecificClassFields (CodeClassField::Attribute, true, Uml::Visibility::Public ); CodeClassFieldList publicAttribClassFields = getSpecificClassFields (CodeClassField::Attribute, false, Uml::Visibility::Public ); CodeClassFieldList staticProtectedAttribClassFields = getSpecificClassFields (CodeClassField::Attribute, true, Uml::Visibility::Protected ); CodeClassFieldList protectedAttribClassFields = getSpecificClassFields (CodeClassField::Attribute, false, Uml::Visibility::Protected ); CodeClassFieldList staticPrivateAttribClassFields = getSpecificClassFields (CodeClassField::Attribute, true, Uml::Visibility::Private ); CodeClassFieldList privateAttribClassFields = getSpecificClassFields (CodeClassField::Attribute, false, Uml::Visibility::Private); // association-based ClassFields // don't care if they are static or not..all are lumped together CodeClassFieldList publicPlainAssocClassFields = getSpecificClassFields ( CodeClassField::PlainAssociation , Uml::Visibility::Public); CodeClassFieldList publicAggregationClassFields = getSpecificClassFields ( CodeClassField::Aggregation, Uml::Visibility::Public); CodeClassFieldList publicCompositionClassFields = getSpecificClassFields ( CodeClassField::Composition, Uml::Visibility::Public ); CodeClassFieldList protPlainAssocClassFields = getSpecificClassFields ( CodeClassField::PlainAssociation , Uml::Visibility::Protected); CodeClassFieldList protAggregationClassFields = getSpecificClassFields ( CodeClassField::Aggregation, Uml::Visibility::Protected); CodeClassFieldList protCompositionClassFields = getSpecificClassFields ( CodeClassField::Composition, Uml::Visibility::Protected); CodeClassFieldList privPlainAssocClassFields = getSpecificClassFields ( CodeClassField::PlainAssociation , Uml::Visibility::Private); CodeClassFieldList privAggregationClassFields = getSpecificClassFields ( CodeClassField::Aggregation, Uml::Visibility::Private); CodeClassFieldList privCompositionClassFields = getSpecificClassFields ( CodeClassField::Composition, Uml::Visibility::Private); bool hasOperationMethods = false; Q_ASSERT(c != NULL); if (c) { UMLOperationList list = c->getOpList(); hasOperationMethods = ! list.isEmpty(); } bool hasNamespace = false; bool isEnumeration = false; bool isInterface = parentIsInterface(); bool hasclassFields = hasClassFields(); bool forcedoc = UMLApp::app()->commonPolicy()->getCodeVerboseDocumentComments(); QString endLine = UMLApp::app()->commonPolicy()->getNewLineEndingChars(); UMLClassifierList superclasses = c->findSuperClassConcepts(); // START GENERATING CODE/TEXT BLOCKS and COMMENTS FOR THE DOCUMENT // // Write the hash define stuff to prevent multiple parsing/inclusion of header QString cppClassName = CodeGenerator::cleanName(c->name()); QString hashDefine = CodeGenerator::cleanName(c->name().toUpper().simplified()); QString defText = "#ifndef "+hashDefine + "_H"+ endLine + "#define "+ hashDefine + "_H"; addOrUpdateTaggedCodeBlockWithComments("hashDefBlock", defText, "", 0, false); // INCLUDE CODEBLOCK // // Q: Why all utils? Isnt just List and Vector the only classes we are using? // A: doesn't matter at all; its more readable to just include '*' and cpp compilers // don't slow down or anything. (TZ) QString includeStatement = ""; bool stringGlobal = policy->stringIncludeIsGlobal(); QString sStartBrak = stringGlobal ? "<" : "\""; QString sEndBrak = stringGlobal ? ">" : "\""; includeStatement.append("#include "+sStartBrak+policy->getStringClassNameInclude()+sEndBrak+endLine); if ( hasObjectVectorClassFields() ) { bool vecGlobal = policy->vectorIncludeIsGlobal(); QString vStartBrak = vecGlobal ? "<" : "\""; QString vEndBrak = vecGlobal ? ">" : "\""; QString value ="#include "+vStartBrak+policy->getVectorClassNameInclude()+vEndBrak; includeStatement.append(value+endLine); } //only include classes in a different package from this class UMLPackageList includes; QMap<UMLPackage *,QString> packageMap; // so we don't repeat packages CodeGenerator::findObjectsRelated(c,includes); foreach(UMLPackage* con, includes ) { if (con->baseType() != Uml::ot_Datatype && !packageMap.contains(con)) { packageMap.insert(con,con->package()); if(con != getParentClassifier()) includeStatement.append("#include \""+CodeGenerator::cleanName(con->name().toLower())+".h\""+endLine); } } // now, add/update the includes codeblock CodeBlockWithComments * inclBlock = addOrUpdateTaggedCodeBlockWithComments("includes", includeStatement, QString(), 0, false); if(includeStatement.isEmpty() && inclBlock->getContentType() == CodeBlock::AutoGenerated) inclBlock->setWriteOutText(false); else inclBlock->setWriteOutText(true); // Using QString usingStatement; foreach(UMLClassifier* classifier, superclasses ) { if(classifier->package()!=c->package() && !classifier->package().isEmpty()) { usingStatement.append("using "+CodeGenerator::cleanName(c->package())+"::"+cleanName(c->name())+';'+endLine); } } CodeBlockWithComments * usingBlock = addOrUpdateTaggedCodeBlockWithComments("using", usingStatement, "", 0, false); if(usingStatement.isEmpty() && usingBlock->getContentType() == CodeBlock::AutoGenerated) usingBlock->setWriteOutText(false); else usingBlock->setWriteOutText(true); // namespace // This needs special treatment. We cant use "nowriteouttext" for this, as // that will prevent the class declaration from being written. Instead, we // check if "hasNamspace" is true or not, and then indent the remaining code // appropriately as well as set the start/end text of this namespace block. if (c->umlPackage() && policy->getPackageIsNamespace()) hasNamespace = true; else hasNamespace = false; // set start/end text of namespace block m_namespaceBlock = getHierarchicalCodeBlock("namespace", "Namespace", 0); if(hasNamespace) { UMLPackageList pkgList = c->packages(); QString pkgs; UMLPackage *pkg; foreach (pkg, pkgList ) { pkgs += "namespace " + CodeGenerator::cleanName(pkg->name()) + " { "; } m_namespaceBlock->setStartText(pkgs); QString closingBraces; foreach (pkg, pkgList ) { closingBraces += "} "; } m_namespaceBlock->setEndText(closingBraces); m_namespaceBlock->getComment()->setWriteOutText(true); } else {
CompiledPythonFragment * getCompiledCode( Table * table, int pkey, const QString & pCode, const QString & codeName ) { CompiledPythonFragment * ret = 0; ensurePythonInitialized(); // Create the key for looking up the code fragment in the cache QPair<Table*,int> codeKey = qMakePair(table,pkey); // Return the cached code fragment, if the code still matches if( codeCache.contains( codeKey ) ) { CompiledPythonFragment * frag = &codeCache[codeKey]; // This should actually be very fast because of QString's // implicit sharing, should usually just be a pointer comparison if( frag->codeString == pCode ) return frag; // Remove from cache if the fragment is out of date // TODO: This should free any references and remove the module // this isn't a big deal though, since code fragments won't // change very often during program execution codeCache.remove( codeKey ); } if( pCode.isEmpty() ) return 0; // Compile the code CompiledPythonFragment frag; frag.codeString = pCode; SIP_BLOCK_THREADS frag.code = (PyCodeObject*)Py_CompileString( pCode.toLatin1(), codeName.toLatin1(), Py_file_input ); SIP_UNBLOCK_THREADS if( !frag.code ) { PyErr_Print(); LOG_5( "PathTemplate:getCompiledCode: Error Compiling Python code for: " + table->schema()->tableName() + " " + QString::number( pkey ) + " " + codeName ); return 0; } // Load the code into a module // This is the only way i could figure out how to make the globals work properly // before i was using PyEval_EvalCode, passing the __main__ dict as the globals // but this wasn't working properly when calling the functions later, because // the import statements were lost. // This method works great and takes less code. // Generate a unique module name QString moduleName = "__" + table->schema()->tableName() + "__" + QString::number(pkey) + "__"; // Returns a NEW ref SIP_BLOCK_THREADS PyObject * module = PyImport_ExecCodeModule(moduleName.toLatin1().data(),(PyObject*)frag.code); if( !module ) { PyErr_Print(); LOG_3( "Unable to execute code module" ); } // Save the modules dict, so we can lookup the function later else { frag.locals = PyModule_GetDict(module); Py_INCREF(frag.locals); codeCache[codeKey] = frag; ret = &codeCache[codeKey]; } SIP_UNBLOCK_THREADS return ret; }
QString message(const QCString &key) { static bool initialized = false; if (!initialized) { //--------------------------------------------------------------------------- // Project related configuration options //--------------------------------------------------------------------------- addMessage("Project", i18n("Project")); addMessage("PROJECT_NAME", i18n("Project name")); addMessage("PROJECT_NUMBER", i18n("Project version")); addMessage("OUTPUT_DIRECTORY", i18n("Output path")); addMessage("CREATE_SUBDIRS", i18n("Distribute the generated docs in 10 subdirectories")); addMessage("OUTPUT_LANGUAGE", i18n("Output language")); addMessage("USE_WINDOWS_ENCODING", i18n("Use MS Windows(tm) font encoding")); addMessage("BRIEF_MEMBER_DESC", i18n("Include brief member descriptions")); addMessage("REPEAT_BRIEF", i18n("Repeat brief member descriptions")); addMessage("ABBREVIATE_BRIEF", i18n("Strip words in brief description")); addMessage("ALWAYS_DETAILED_SEC", i18n("Always include detailed section")); addMessage("INLINE_INHERITED_MEMB", i18n("Inline inherited members")); addMessage("FULL_PATH_NAMES", i18n("Always use full path names")); addMessage("STRIP_FROM_PATH", i18n("Prefix to strip from path names")); addMessage("STRIP_FROM_INC_PATH", i18n("Strip from include path")); addMessage("SHORT_NAMES", i18n("Generate short file names")); addMessage("JAVADOC_AUTOBRIEF", i18n("Use JavaDoc-style brief descriptions")); addMessage("MULTILINE_CPP_IS_BRIEF", i18n("Multiline cpp is brief")); addMessage("DETAILS_AT_TOP", i18n("Details at top")); addMessage("INHERIT_DOCS", i18n("Inherit documentation")); addMessage("SEPARATE_MEMBER_PAGES", i18n("Produce a new page for each member")); addMessage("TAB_SIZE", i18n("Tab size")); addMessage("ALIASES", i18n("Aliases")); addMessage("OPTIMIZE_OUTPUT_FOR_C", i18n("Optimize output for C")); addMessage("OPTIMIZE_OUTPUT_JAVA", i18n("Optimize output for Java")); addMessage("BUILTIN_STL_SUPPORT", i18n("Use built-in STL classes support")); addMessage("DISTRIBUTE_GROUP_DOC", i18n("Use group documentation on undocumented members")); addMessage("SUBGROUPING", i18n("Class members type subgrouping")); //--------------------------------------------------------------------------- // Build related configuration options //--------------------------------------------------------------------------- addMessage("Build", i18n("Build")); addMessage("EXTRACT_ALL", i18n("Extract undocumented entities")); addMessage("EXTRACT_PRIVATE", i18n("Extract private entities")); addMessage("EXTRACT_STATIC", i18n("Extract static entities")); addMessage("EXTRACT_LOCAL_CLASSES", i18n("Extract local classes")); addMessage("EXTRACT_LOCAL_METHODS", i18n("Extract local methods")); addMessage("HIDE_UNDOC_MEMBERS", i18n("Hide undocumented members")); addMessage("HIDE_UNDOC_CLASSES", i18n("Hide undocumented classes")); addMessage("HIDE_FRIEND_COMPOUNDS", i18n("Hide friend compounds")); addMessage("HIDE_IN_BODY_DOCS", i18n("Hide in body docs")); addMessage("INTERNAL_DOCS", i18n("Document internal entities")); addMessage("CASE_SENSE_NAMES", i18n("Use case-sensitive file names")); addMessage("HIDE_SCOPE_NAMES", i18n("Hide name scopes")); addMessage("SHOW_INCLUDE_FILES", i18n("Show included files")); addMessage("INLINE_INFO", i18n("Make inline functions")); addMessage("SORT_MEMBER_DOCS", i18n("Sort member documentation alphabetically")); addMessage("SORT_BY_SCOPE_NAME", i18n("Sort the class list by fully-qualified names")); addMessage("SORT_BRIEF_DOCS", i18n("Sort brief documentation alphabetically")); addMessage("ENABLED_SECTIONS", i18n("Enable conditional sections")); addMessage("GENERATE_TODOLIST", i18n("Generate TODO-list")); addMessage("GENERATE_TESTLIST", i18n("Generate Test-list")); addMessage("GENERATE_BUGLIST", i18n("Generate Bug-list")); addMessage("GENERATE_DEPRECATEDLIST", i18n("Generate Deprecated-list")); addMessage("MAX_INITIALIZER_LINES", i18n("Maximum lines shown for initializers")); addMessage("SHOW_USED_FILES", i18n("Show used files")); addMessage("SHOW_DIRECTORIES", i18n("Show the directory hierarchy")); addMessage("FILE_VERSION_FILTER", i18n("Script to invoke to get the current version for each file")); //--------------------------------------------------------------------------- // configuration options related to warning and progress messages //--------------------------------------------------------------------------- addMessage("Messages", i18n("Messages")); addMessage("QUIET", i18n("Suppress output")); addMessage("WARNINGS", i18n("Show warnings")); addMessage("WARN_IF_UNDOCUMENTED", i18n("Warn about undocumented entities")); addMessage("WARN_IF_DOC_ERROR", i18n("Warn if error in documents")); addMessage("WARN_NO_PARAMDOC", i18n("Warn if function parameters are not documented")); addMessage("WARN_FORMAT", i18n("Warnings format")); addMessage("WARN_LOGFILE", i18n("Write warnings to")); //--------------------------------------------------------------------------- // configuration options related to the input files //--------------------------------------------------------------------------- addMessage("Input", i18n("Input")); addMessage("INPUT", i18n("Input files and directories")); addMessage("FILE_PATTERNS", i18n("Input patterns")); addMessage("RECURSIVE", i18n("Recurse into subdirectories")); addMessage("EXCLUDE", i18n("Exclude from input")); addMessage("EXCLUDE_SYMLINKS", i18n("Exclude symlinks")); addMessage("EXCLUDE_PATTERNS", i18n("Exclude patterns")); addMessage("EXAMPLE_PATH", i18n("Path to examples")); addMessage("EXAMPLE_PATTERNS", i18n("Example patterns")); addMessage("EXAMPLE_RECURSIVE", i18n("Example recursive")); addMessage("IMAGE_PATH", i18n("Path to images")); addMessage("INPUT_FILTER", i18n("Input filter")); addMessage("FILTER_SOURCE_FILES", i18n("Filter input files")); addMessage("FILTER_PATTERNS", i18n("Apply filters on file patterns")); //--------------------------------------------------------------------------- // configuration options related to source browsing //--------------------------------------------------------------------------- addMessage("Source Browser", i18n("Source Browser")); addMessage("SOURCE_BROWSER", i18n("Cross-reference with source files")); addMessage("REFERENCES_LINK_SOURCE", i18n("References will link to source code")); addMessage("USE_HTAGS", i18n("Use links to HTAGS")); addMessage("INLINE_SOURCES", i18n("Inline sources")); addMessage("STRIP_CODE_COMMENTS", i18n("Hide special comment blocks")); addMessage("REFERENCED_BY_RELATION", i18n("Referenced by relation")); addMessage("REFERENCES_RELATION", i18n("References relation")); addMessage("VERBATIM_HEADERS", i18n("Include headers verbatim")); //--------------------------------------------------------------------------- // configuration options related to the alphabetical class index //--------------------------------------------------------------------------- addMessage("Index", i18n("Index")); addMessage("ALPHABETICAL_INDEX", i18n("Generate alphabetical index")); addMessage("COLS_IN_ALPHA_INDEX", i18n("Columns in index")); addMessage("IGNORE_PREFIX", i18n("Prefix to ignore")); //--------------------------------------------------------------------------- // configuration options related to the HTML output //--------------------------------------------------------------------------- addMessage("HTML", i18n("HTML")); addMessage("GENERATE_HTML", i18n("Generate HTML")); addMessage("HTML_OUTPUT", i18n("HTML output directory")); addMessage("HTML_FILE_EXTENSION", i18n("HTML file extension")); addMessage("HTML_HEADER", i18n("Header file")); addMessage("HTML_FOOTER", i18n("Footer file")); addMessage("HTML_STYLESHEET", i18n("Stylesheet")); addMessage("HTML_ALIGN_MEMBERS", i18n("Align members")); addMessage("GENERATE_HTMLHELP", i18n("Generate HTML-help")); addMessage("CHM_FILE", i18n("CHM file")); addMessage("HHC_LOCATION", i18n("HHC location")); addMessage("GENERATE_CHI", i18n("Generate .chi file")); addMessage("BINARY_TOC", i18n("Generate binary TOC")); addMessage("TOC_EXPAND", i18n("Expand TOC")); addMessage("DISABLE_INDEX", i18n("Disable index")); addMessage("ENUM_VALUES_PER_LINE", i18n("Number of enum values per line")); addMessage("GENERATE_TREEVIEW", i18n("Generate treeview")); addMessage("TREEVIEW_WIDTH", i18n("Treeview width")); //--------------------------------------------------------------------------- // configuration options related to the LaTeX output //--------------------------------------------------------------------------- addMessage("LaTeX", i18n("LaTeX")); addMessage("GENERATE_LATEX", i18n("Generate LaTeX")); addMessage("LATEX_OUTPUT", i18n("LaTeX output directory")); addMessage("LATEX_CMD_NAME", i18n("LaTeX command name")); addMessage("MAKEINDEX_CMD_NAME", i18n("MakeIndex command name")); addMessage("COMPACT_LATEX", i18n("Generate compact output")); addMessage("PAPER_TYPE", i18n("Paper type")); addMessage("EXTRA_PACKAGES", i18n("Include extra packages")); addMessage("LATEX_HEADER", i18n("LaTeX Header file")); addMessage("PDF_HYPERLINKS", i18n("Generate PDF hyperlinks")); addMessage("USE_PDFLATEX", i18n("Use pdflatex")); addMessage("LATEX_BATCHMODE", i18n("Use batch mode")); addMessage("LATEX_HIDE_INDICES", i18n("Do not include index chapters")); //--------------------------------------------------------------------------- // configuration options related to the RTF output //--------------------------------------------------------------------------- addMessage("RTF", i18n("RTF")); addMessage("GENERATE_RTF", i18n("Generate RTF")); addMessage("RTF_OUTPUT", i18n("RTF output directory")); addMessage("COMPACT_RTF", i18n("Generate compact output")); addMessage("RTF_HYPERLINKS", i18n("Generate hyperlinks")); addMessage("RTF_STYLESHEET_FILE", i18n("Stylesheet")); addMessage("RTF_EXTENSIONS_FILE", i18n("Extensions file")); //--------------------------------------------------------------------------- // configuration options related to the man page output //--------------------------------------------------------------------------- addMessage("Man", i18n("Man")); addMessage("GENERATE_MAN", i18n("Generate man pages")); addMessage("MAN_OUTPUT", i18n("Man output directory")); addMessage("MAN_EXTENSION", i18n("Man extension")); addMessage("MAN_LINKS", i18n("Generate links")); //--------------------------------------------------------------------------- // configuration options related to the XML output //--------------------------------------------------------------------------- addMessage("XML", i18n("XML")); addMessage("GENERATE_XML", i18n("Generate XML")); addMessage("XML_OUTPUT", i18n("XML output directory")); addMessage("XML_SCHEMA", i18n("XML schema")); addMessage("XML_DTD", i18n("XML DTD file")); addMessage("XML_PROGRAMLISTING", i18n("Dump program listings to the XML output")); //--------------------------------------------------------------------------- // configuration options for the AutoGen Definitions output //--------------------------------------------------------------------------- addMessage("DEF", i18n("DEF")); addMessage("GENERATE_AUTOGEN_DEF", i18n("Generate Autogen DEF")); //--------------------------------------------------------------------------- // configuration options related to the Perl module output //--------------------------------------------------------------------------- addMessage("PerlMod", i18n("Perl")); addMessage("GENERATE_PERLMOD", i18n("Generate Perl module")); addMessage("PERLMOD_LATEX", i18n("Generate PDF and DVI using LaTeX")); addMessage("PERLMOD_PRETTY", i18n("Make the Perl module output human readable")); addMessage("PERLMOD_MAKEVAR_PREFIX", i18n("Perl module variable prefix in the makefiles")); //--------------------------------------------------------------------------- // Configuration options related to the preprocessor //--------------------------------------------------------------------------- addMessage("Preprocessor", i18n("Preprocessor")); addMessage("ENABLE_PREPROCESSING", i18n("Enable preprocessing")); addMessage("MACRO_EXPANSION", i18n("Expand macros")); addMessage("EXPAND_ONLY_PREDEF", i18n("Expand only predefined macros")); addMessage("SEARCH_INCLUDES", i18n("Search for includes")); addMessage("INCLUDE_PATH", i18n("Include path")); addMessage("INCLUDE_FILE_PATTERNS", i18n("Include file patterns")); addMessage("PREDEFINED", i18n("Predefined macros")); addMessage("EXPAND_AS_DEFINED", i18n("Expand as defined")); addMessage("SKIP_FUNCTION_MACROS", i18n("Skip function macros")); //--------------------------------------------------------------------------- // Configuration::addtions related to external references //--------------------------------------------------------------------------- addMessage("External", i18n("External")); addMessage("TAGFILES", i18n("Tagfiles")); addMessage("GENERATE_TAGFILE", i18n("Generate tagfile")); addMessage("ALLEXTERNALS", i18n("List all externals")); addMessage("EXTERNAL_GROUPS", i18n("External groups")); addMessage("PERL_PATH", i18n("Path to Perl")); //--------------------------------------------------------------------------- // Configuration options related to the dot tool //--------------------------------------------------------------------------- addMessage("Dot", i18n("Dot")); addMessage("CLASS_DIAGRAMS", i18n("Generate class diagrams")); addMessage("HIDE_UNDOC_RELATIONS", i18n("Hide undocumented relations")); addMessage("HAVE_DOT", i18n("Use dot")); addMessage("CALLER_GRAPH", i18n("Generate a caller dependency graph")); addMessage("CLASS_GRAPH", i18n("Generate class graphs")); addMessage("COLLABORATION_GRAPH", i18n("Generate collaboration graphs")); addMessage("GROUP_GRAPHS", i18n("Generate a graph showing the direct groups dependencies")); addMessage("UML_LOOK", i18n("Generate UML looking inheritance and colloboration diagrams")); addMessage("TEMPLATE_RELATIONS", i18n("Show relations between templates and their instances")); addMessage("INCLUDE_GRAPH", i18n("Generate include graphs")); addMessage("INCLUDED_BY_GRAPH", i18n("Generate included-by graphs")); addMessage("CALL_GRAPH", i18n("Generate a call dependency graph for every global function or class method")); addMessage("GRAPHICAL_HIERARCHY", i18n("Generate graphical hierarchy")); addMessage("DIRECTORY_GRAPH", i18n("Show the dependencies a directory has on other directories")); addMessage("DOT_IMAGE_FORMAT", i18n("Dot image format")); addMessage("DOT_PATH", i18n("Path to dot")); addMessage("DOTFILE_DIRS", i18n("Directories with extra dot files")); addMessage("MAX_DOT_GRAPH_WIDTH", i18n("Maximum graph width")); addMessage("MAX_DOT_GRAPH_HEIGHT", i18n("Maximum graph height")); addMessage("MAX_DOT_GRAPH_DEPTH", i18n("Maximum graph depth")); addMessage("DOT_TRANSPARENT", i18n("Generate images with a transparent background")); addMessage("DOT_MULTI_TARGETS", i18n("Generate multiple output files in one run")); addMessage("GENERATE_LEGEND", i18n("Generate legend")); addMessage("DOT_CLEANUP", i18n("Remove intermediate files")); addMessage("Search", i18n("Search")); //--------------------------------------------------------------------------- // Configuration::addtions related to the search engine //--------------------------------------------------------------------------- addMessage("SEARCHENGINE", i18n("Search engine")); addMessage("CGI_NAME", i18n("CGI name")); addMessage("CGI_URL", i18n("CGI URL")); addMessage("DOC_URL", i18n("Documentation URL")); addMessage("DOC_ABSPATH", i18n("Absolute path to documentation")); addMessage("BIN_ABSPATH", i18n("Absolute path to doxysearch binary")); addMessage("EXT_DOC_PATHS", i18n("Paths to external documentation")); initialized = true; } if (!sMessages.contains(key)) { kdDebug() << "Unhandled message: " << key << endl; return key; } return sMessages[key]; }
AudioOutput *AudioOutput::OpenAudio(AudioSettings &settings, bool willsuspendpa) { QString &main_device = settings.main_device; AudioOutput *ret = NULL; #ifdef USING_PULSE bool pulsestatus = false; #else { static bool warned = false; if (!warned && IsPulseAudioRunning()) { warned = true; VERBOSE(VB_IMPORTANT, "WARNING: ***Pulse Audio is running***"); } } #endif settings.FixPassThrough(); if (main_device.startsWith("PulseAudio:")) { #ifdef USING_PULSEOUTPUT return new AudioOutputPulseAudio(settings); #else VERBOSE(VB_IMPORTANT, "Audio output device is set to PulseAudio " "but PulseAudio support is not compiled in!"); return NULL; #endif } else if (main_device.startsWith("NULL")) { return new AudioOutputNULL(settings); } #ifdef USING_PULSE if (willsuspendpa) { bool ispulse = false; #ifdef USE_ALSA // Check if using ALSA, that the device doesn't contain the word // "pulse" in its hint if (main_device.startsWith("ALSA:")) { QString device_name = main_device; device_name.remove(0, 5); QMap<QString, QString> *alsadevs = AudioOutputALSA::GetALSADevices("pcm"); if (!alsadevs->empty() && alsadevs->contains(device_name)) { if (alsadevs->value(device_name).contains("pulse", Qt::CaseInsensitive)) { ispulse = true; } } delete alsadevs; } #endif if (main_device.contains("pulse", Qt::CaseInsensitive)) { ispulse = true; } if (!ispulse) { pulsestatus = PulseHandler::Suspend(PulseHandler::kPulseSuspend); } } #endif if (main_device.startsWith("ALSA:")) { #ifdef USE_ALSA settings.TrimDeviceType(); ret = new AudioOutputALSA(settings); #else VERBOSE(VB_IMPORTANT, "Audio output device is set to an ALSA device " "but ALSA support is not compiled in!"); #endif } else if (main_device.startsWith("JACK:")) { #ifdef USE_JACK settings.TrimDeviceType(); ret = new AudioOutputJACK(settings); #else VERBOSE(VB_IMPORTANT, "Audio output device is set to a JACK device " "but JACK support is not compiled in!"); #endif } else if (main_device.startsWith("DirectX:")) { #ifdef USING_MINGW ret = new AudioOutputDX(settings); #else VERBOSE(VB_IMPORTANT, "Audio output device is set to DirectX device " "but DirectX support is not compiled in!"); #endif } else if (main_device.startsWith("Windows:")) { #ifdef USING_MINGW ret = new AudioOutputWin(settings); #else VERBOSE(VB_IMPORTANT, "Audio output device is set to a Windows device " "but Windows support is not compiled in!"); #endif } #if defined(USING_OSS) else ret = new AudioOutputOSS(settings); #elif CONFIG_DARWIN else
void TrackerClient::httpRequestDone(bool error) { if (lastTrackerRequest) { emit stopped(); return; } if (error) { emit connectionError(http.error()); return; } QByteArray response = http.readAll(); http.abort(); BencodeParser parser; if (!parser.parse(response)) { qWarning("Error parsing bencode response from tracker: %s", qPrintable(parser.errorString())); http.abort(); return; } QMap<QByteArray, QVariant> dict = parser.dictionary(); if (dict.contains("failure reason")) { // no other items are present emit failure(QString::fromUtf8(dict.value("failure reason").toByteArray())); return; } if (dict.contains("warning message")) { // continue processing emit warning(QString::fromUtf8(dict.value("warning message").toByteArray())); } if (dict.contains("tracker id")) { // store it trackerId = dict.value("tracker id").toByteArray(); } if (dict.contains("interval")) { // Mandatory item if (requestIntervalTimer != -1) killTimer(requestIntervalTimer); requestIntervalTimer = startTimer(dict.value("interval").toInt() * 1000); } if (dict.contains("peers")) { // store it peers.clear(); QVariant peerEntry = dict.value("peers"); if (peerEntry.type() == QVariant::List) { QList<QVariant> peerTmp = peerEntry.toList(); for (int i = 0; i < peerTmp.size(); ++i) { TorrentPeer tmp; QMap<QByteArray, QVariant> peer = qvariant_cast<QMap<QByteArray, QVariant> >(peerTmp.at(i)); tmp.id = QString::fromUtf8(peer.value("peer id").toByteArray()); tmp.address.setAddress(QString::fromUtf8(peer.value("ip").toByteArray())); tmp.port = peer.value("port").toInt(); peers << tmp; } } else { QByteArray peerTmp = peerEntry.toByteArray(); for (int i = 0; i < peerTmp.size(); i += 6) { TorrentPeer tmp; uchar *data = (uchar *)peerTmp.constData() + i; tmp.port = (int(data[4]) << 8) + data[5]; uint ipAddress = 0; ipAddress += uint(data[0]) << 24; ipAddress += uint(data[1]) << 16; ipAddress += uint(data[2]) << 8; ipAddress += uint(data[3]); tmp.address.setAddress(ipAddress); peers << tmp; } } emit peerListUpdated(peers); } }
static void parse( MetaTranslator *tor, const char *initialContext, const char *defaultContext ) { QMap<QCString, QCString> qualifiedContexts; QStringList namespaces; QCString context; QCString text; QCString com; QCString functionContext = initialContext; QCString prefix; bool utf8 = FALSE; bool missing_Q_OBJECT = FALSE; yyTok = getToken(); while ( yyTok != Tok_Eof ) { switch ( yyTok ) { case Tok_class: /* Partial support for inlined functions. */ yyTok = getToken(); if ( yyBraceDepth == (int) namespaces.count() && yyParenDepth == 0 ) { do { /* This code should execute only once, but we play safe with impure definitions such as 'class Q_EXPORT QMessageBox', in which case 'QMessageBox' is the class name, not 'Q_EXPORT'. */ functionContext = yyIdent; yyTok = getToken(); } while ( yyTok == Tok_Ident ); while ( yyTok == Tok_Gulbrandsen ) { yyTok = getToken(); functionContext += "::"; functionContext += yyIdent; yyTok = getToken(); } if ( yyTok == Tok_Colon ) { missing_Q_OBJECT = TRUE; } else { functionContext = defaultContext; } } break; case Tok_namespace: yyTok = getToken(); if ( yyTok == Tok_Ident ) { QCString ns = yyIdent; yyTok = getToken(); if ( yyTok == Tok_LeftBrace && yyBraceDepth == (int) namespaces.count() + 1 ) namespaces.append( QString(ns) ); } break; case Tok_tr: case Tok_trUtf8: utf8 = ( yyTok == Tok_trUtf8 ); yyTok = getToken(); if ( match(Tok_LeftParen) && matchString(&text) ) { com = ""; if ( match(Tok_RightParen) || (match(Tok_Comma) && matchString(&com) && match(Tok_RightParen)) ) { if ( prefix.isNull() ) { context = functionContext; if ( !namespaces.isEmpty() ) context.prepend( (namespaces.join(QString("::")) + QString("::")).latin1() ); } else { context = prefix; } prefix = (const char *) 0; if ( qualifiedContexts.contains(context) ) context = qualifiedContexts[context]; tor->insert( MetaTranslatorMessage(context, text, com, QString::null, utf8) ); if ( lacks_Q_OBJECT.contains(context) ) { qWarning( "%s:%d: Class '%s' lacks Q_OBJECT macro", (const char *) yyFileName, yyLineNo, (const char *) context ); lacks_Q_OBJECT.remove( context ); } else { needs_Q_OBJECT.insert( context, 0 ); } } } break; case Tok_translate: utf8 = FALSE; yyTok = getToken(); if ( match(Tok_LeftParen) && matchString(&context) && match(Tok_Comma) && matchString(&text) ) { com = ""; if ( match(Tok_RightParen) || (match(Tok_Comma) && matchString(&com) && (match(Tok_RightParen) || match(Tok_Comma) && matchEncoding(&utf8) && match(Tok_RightParen))) ) tor->insert( MetaTranslatorMessage(context, text, com, QString::null, utf8) ); } break; case Tok_Q_OBJECT: missing_Q_OBJECT = FALSE; yyTok = getToken(); break; case Tok_Ident: if ( !prefix.isNull() ) prefix += "::"; prefix += yyIdent; yyTok = getToken(); if ( yyTok != Tok_Gulbrandsen ) prefix = (const char *) 0; break; case Tok_Comment: com = yyComment; com = com.simplifyWhiteSpace(); if ( com.left(sizeof(MagicComment) - 1) == MagicComment ) { com.remove( 0, sizeof(MagicComment) - 1 ); int k = com.find( ' ' ); if ( k == -1 ) { context = com; } else { context = com.left( k ); com.remove( 0, k + 1 ); tor->insert( MetaTranslatorMessage(context, "", com, QString::null, FALSE) ); } /* Provide a backdoor for people using "using namespace". See the manual for details. */ k = 0; while ( (k = context.find("::", k)) != -1 ) { qualifiedContexts.insert( context.mid(k + 2), context ); k++; } } yyTok = getToken(); break; case Tok_Arrow: yyTok = getToken(); if ( yyTok == Tok_tr || yyTok == Tok_trUtf8 ) qWarning( "%s:%d: Cannot invoke tr() like this", (const char *) yyFileName, yyLineNo ); break; case Tok_Gulbrandsen: // at top level? if ( yyBraceDepth == (int) namespaces.count() && yyParenDepth == 0 ) functionContext = prefix; yyTok = getToken(); break; case Tok_RightBrace: case Tok_Semicolon: if ( yyBraceDepth >= 0 && yyBraceDepth + 1 == (int) namespaces.count() ) namespaces.remove( namespaces.fromLast() ); if ( yyBraceDepth == (int) namespaces.count() ) { if ( missing_Q_OBJECT ) { if ( needs_Q_OBJECT.contains(functionContext) ) { qWarning( "%s:%d: Class '%s' lacks Q_OBJECT macro", (const char *) yyFileName, yyLineNo, (const char *) functionContext ); } else { lacks_Q_OBJECT.insert( functionContext, 0 ); } } functionContext = defaultContext; missing_Q_OBJECT = FALSE; } yyTok = getToken(); break; default: yyTok = getToken(); } } if ( yyBraceDepth != 0 ) fprintf( stderr, "%s:%d: Unbalanced braces in C++ code (or abuse of the C++" " preprocessor)\n", (const char *)yyFileName, yyBraceLineNo ); else if ( yyParenDepth != 0 ) fprintf( stderr, "%s:%d: Unbalanced parentheses in C++ code (or abuse of the C++" " preprocessor)\n", (const char *)yyFileName, yyParenLineNo ); }
/////////////////////////////////////// PUBLIC FUNCTIONS //////////////////////////////// // // Function to put all of input fields received via DBus:RequestInput into a // QMap<QString,QString> where key is the input field received and value is // generally blank but can be used for informational text. // // If we asked to log the input request create the log file in /tmp/cmst/input_request.log void ConnmanAgent::createInputMap(const QMap<QString,QVariant>& r_map) { // Initialize our data map input_map.clear(); // QFile object for logging QTextStream log; QFile logfile("/tmp/cmst/input_request.log"); if (b_loginputrequest) { QDir d; d.mkpath("/tmp/cmst"); if (logfile.exists()) logfile.remove(); if (!logfile.open(QIODevice::WriteOnly | QIODevice::Text)) b_loginputrequest = false; else log.setDevice(&logfile); } // Run through the r_map getting the keys and the few values we are interested in. QMap<QString, QVariant>::const_iterator i = r_map.constBegin(); while (i != r_map.constEnd()) { // Lets see what the values contain, but first make sure we can get to them. if (b_loginputrequest) log << "\nMap Key: " << i.key() << "\n"; if (! i.value().canConvert<QDBusArgument>() ) return; const QDBusArgument qdba = i.value().value<QDBusArgument>(); if ( ! qdba.currentType() == QDBusArgument::MapType ) { if (b_loginputrequest) log << "Error - QDBusArgument as the value is not a MapType\n"; return; } // The r_map.value() is a QDBusArgument::MapType so extract this map into a new QMap called m. qdba.beginMap(); QMap<QString,QString> m; m.clear(); if (b_loginputrequest) log << "Extracting the DBusArgument Map...\n"; while ( ! qdba.atEnd() ) { QString k; QVariant v; qdba.beginMapEntry(); qdba >> k >> v; qdba.endMapEntry(); m.insert(k, v.toString()); if (b_loginputrequest) log << "{ " << k << " , " << v.toString() << "}\n"; } // while qdba.endMap(); // Browse through QMap m and get things we need to look at // Types we don' really care about. We ignore "optional" and "alternate" requirements // and only extract the "mandatory" and "informational" requirements with values if (m.contains("Requirement") ) { QString val = QString(); if ( m.value("Requirement").contains("mandatory", Qt::CaseInsensitive) || m.value("Requirement").contains("informational", Qt::CaseInsensitive) ) { if (m.contains("Value") ) val = m.value("Value"); } // if mandatory or informational // create our input_map entry input_map[i.key()] = val; } // if requirement ++i; } // while logfile.close(); return; }
// Some magic required by .ngfp format. void NgfpReader::modifySpecificElemView (const QJsonValue &j_elemview, ElemView *elemview, Project *project, Screen *screen) { auto modifyTabs = [&]() { auto attrs = elemview->getElem()->getAttrs(); QJsonArray j_pages = j_elemview.toObject()["pages"].toArray(); TabsView *tabsview = qobject_cast<TabsView*>(elemview); if (tabsview == nullptr) return; int cur_page = 0; QStringList page_hdrs; tabsview->removeLastPage(); tabsview->removeLastPage(); for (int i = 0; i < j_pages.size(); i++) { page_hdrs.append(j_pages[i].toObject()["caption"].toString()); if (!j_pages[i].toObject().value("default").isUndefined()) cur_page = i; tabsview->appendPage(); containerFromJson(j_pages[i].toObject()["elements"].toArray(), tabsview->getAllContainers().last(), project, screen); // recursion } Attr* attr_page_hdrs = attrs.value("page_hdrs"); attr_page_hdrs->setValueAsVar(page_hdrs); tabsview->headers = page_hdrs; Attr* attr_cur_page = attrs.value("cur_page"); static_cast<Number*>(attr_cur_page)->setMax(page_hdrs.size()); static_cast<Number*>(attr_cur_page)->setValue(cur_page + 1); // because this attr values starts from 1 tabsview->cur_container_index = cur_page; }; auto modifyDateTimePicker = [&]() { auto attrs = elemview->getElem()->getAttrs(); QJsonObject j_attrs = j_elemview.toObject()["attributes"].toObject(); if (j_attrs["datetime"].isNull()) { attrs["date_is_cur"]->setValueAsVar(true); } else { attrs["date_is_cur"]->setValueAsVar(false); if (j_attrs["date_type"].toInt() == 0) attrs["init_date"]->setValueAsVar(QDateTime::fromString(j_attrs["datetime"].toString(), FB_NGFP_DATETIME_FORMAT_D)); else if (j_attrs["date_type"].toInt() == 1) attrs["init_date"]->setValueAsVar(QDateTime::fromString(j_attrs["datetime"].toString(), FB_NGFP_DATETIME_FORMAT_T)); else attrs["init_date"]->setValueAsVar(QDateTime::fromString(j_attrs["datetime"].toString(), FB_NGFP_DATETIME_FORMAT_DT)); } }; auto modifyComboBox = [&]() { // nothing to do here for reading }; auto modifyCounter = [&]() { // nothing to do here for reading }; auto modifyTextEdit = [&]() { // nothing to do here for reading }; if (!j_elemview.isObject()) return; if (elemview == nullptr) return; typedef std::function<void()> ModifierCallback; const QString &elem_name = elemview->getKeyName(); const QMap<QString, ModifierCallback> modifiers = { {{"tabs"}, {modifyTabs}}, {{"datetimepicker"}, {modifyDateTimePicker}}, {{"combobox"}, {modifyComboBox}}, {{"counter"}, {modifyCounter}}, {{"textedit"}, {modifyTextEdit}} }; if (!modifiers.contains(elem_name)) return; modifiers.value(elem_name)(); // call function }
void sortByLexeme(QStringList &sortList) { // Карта для хранения строк с начальной текстовой строкой // Ключ карты - начальная строка, значения - остаток строки QMap<QString, QStringList> strMap; // Карта для хранения строк с начальной числовой строкой // Ключ карты - начальная строка, значения - остаток строки QMap<double, QStringList> numMap; QList<double> sortingKeyNum; // Лист для сортировки числовых ключей QStringList sortingKeyStr; // Лист для сортировки строковых ключей QStringList res; // Результирующий лист QString temp; // Буфер для текущей обрабатываемой строки QString buf; // Буфер для ключа - домена QString str; // Буфер для одного из значений ключа - имени адреса QString aIter; // Буфер для строкого ключа при формировании выходного списка QString aIterKlein; // Буфер для строки из списка для каждой строки из списка double num; // Буфер для хранения ключа для числовой карты double aIterNum; // Буфер для числового ключа при формировании выходного списка // Заполнение карты путей for(int i=0; i<sortList.count(); i++) { // Загрузка в бущер текущей строки для сортировки temp=sortList[i]; // Заполнение карты по числовому ключу if(temp[0].isNumber()) { // Получение ключа buf=temp.section(QRegExp("[A-z]"), 0, 0); // Перевод ключа из строки в число num=buf.toDouble(); // Получение значения str=temp.remove(buf); /*// Заполнение карты, если остаток строки не пустой if(!str.isEmpty()) {*/ if(numMap.contains(num)) { numMap[num]<<str; } else { numMap.insert(num, QStringList(str)); } //} } // Заполнение карты по нечисловому ключу else { // Получение ключа buf=temp.section(QRegExp("\\d"), 0, 0); // Получение значения str=temp.remove(buf); /*// Заполнение карты, если остаток строки не пустой if(!str.isEmpty()) {*/ if(strMap.contains(buf)) { strMap[buf]<<str; } else { strMap.insert(buf, QStringList(str)); } //} } } // Сортировка карты с числовым ключом // Сортировка значений для каждого ключа QMap<double, QStringList>::iterator itn=numMap.begin(); for(;itn!=numMap.end(); itn++) { if(itn.value().count()>1) { sortByLexeme(itn.value()); } } // Записей ключей в лист itn=numMap.begin(); for(;itn!=numMap.end(); itn++) { sortingKeyNum<<itn.key(); } // Сортировка ключей //sortingKeyNum.sort(); qStableSort(sortingKeyNum.begin(), sortingKeyNum.end()); // Сортировка карты со строковым ключом // Сортировка значений для каждого ключа QMap<QString, QStringList>::iterator its=strMap.begin(); for(;its!=strMap.end(); its++) { if(its.value().count()>1) { sortByLexeme(its.value()); } } // Записей ключей в лист its=strMap.begin(); for(;its!=strMap.end(); its++) { sortingKeyStr<<its.key(); } // Сортировка ключей //sortingKeyStr.sort(); qStableSort(sortingKeyStr.begin(), sortingKeyStr.end(), caseInsensitiveLessThan); // Заполнение выходного листа полями из числовой карты for(int j=0; j<sortingKeyNum.count(); j++) { // Загрузка в бущер текущей строки для ключа aIterNum=sortingKeyNum[j]; // Загрузка в выходной лист значений для определенного ключа for(int k=0; k<numMap[aIterNum].count(); k++) { // Загрузка в буфер текущей строки для сортировки aIterKlein=QString::number(aIterNum)+numMap[aIterNum][k]; // Добавление строки в выходной лист res<<aIterKlein; } } // Заполнение выходного листа полями из строковой карты for(int j=0; j<sortingKeyStr.count(); j++) { // Загрузка в бущер текущей строки для ключа aIter=sortingKeyStr[j]; // Загрузка в выходной лист значений для определенного ключа for(int k=0; k<strMap[aIter].count(); k++) { // Загрузка в буфер текущей строки для сортировки aIterKlein=aIter+strMap[aIter][k]; // Добавление строки в выходной лист res<<aIterKlein; } } // Замена данного листа на возвращаемый sortList=res; }
void SyncController::run(bool saveLog, QFile* log) { this->saveLog = saveLog; this->log = log; input.open(stdin, QIODevice::ReadOnly); output.open(stdout, QIODevice::WriteOnly); quint32 cnt; QByteArray ba = input.read(4); QDataStream modify(&ba, QIODevice::ReadOnly); modify>>cnt; if(saveLog) { log->write("\nBytes for read: "+QByteArray::number(cnt)); log->flush(); } ba.clear(); forever { if(saveLog) { log->write("\nTry to read : "+QByteArray::number(cnt-ba.length())+" bytes"); log->flush(); } ba.append(input.read(cnt-ba.length())); if ((quint32)ba.length() >= cnt) { if(saveLog) { log->write("\nEnd readind - bytes limit reached"); log->flush(); } break; } if(saveLog) { log->write("\nBytes readed (part of packet): "+QByteArray::number(ba.length())+" needed: "+QByteArray::number(cnt)); log->flush(); } if (!input.waitForReadyRead(30000)) { if(saveLog) { log->write("\nEnd readind - wait limit reached"); if(!input.atEnd()) log->write(" and not at end"); log->flush(); } if(input.atEnd()) break; } //cnt -= ba.length(); /* if(saveLog) { log->write("\nLets dec waited to : "+QByteArray::number(cnt)); log->flush(); } */ } if(saveLog) { log->write("\nBytes readed: "+QByteArray::number(ba.length())); log->flush(); } QByteArray message; QDataStream in(&ba, QIODevice::ReadOnly); in.setVersion(QDataStream::Qt_5_4); in >> message; message = qUncompress(message); QByteArray command = message.left(message.indexOf('\n')); message = message.mid(command.length()+1); if(saveLog) { log->write("\nCommand:\n"+command); log->write("\nInput:\n"+message); log->flush(); } QByteArray answer; if (command.startsWith("Execute xml")) { sc.setXmlFile(message); QRegularExpression reg("send istate every (?<interations>\\d+) iterations"); QRegularExpressionMatch match = reg.match(command); if(match.hasMatch()) { iterationsToSend = match.captured("interations").toInt(); iterationsCount = 1; connect(&sc, SIGNAL(iterationFinished(SyncState)), this, SLOT(iterationFinished(SyncState))); } sc.run(); if(sc.getState()==SyncCore::syncFail) { answer = "Error\n"+sc.errorString().toUtf8(); } else { QRegularExpression reg("return connection \"(?<connection>.+)\""); QRegularExpressionMatch match = reg.match(command); if(match.hasMatch()) { answer = "Result xml\n"+sc.dump(match.captured("connection")); } else { QRegularExpression reg("return states"); QRegularExpressionMatch match = reg.match(command); if(match.hasMatch()) { QMap<int, SyncState> syncs = sc.getSyncsCompleted(); if(syncs.contains(2)) { SyncState ss = syncs.value(2); answer = "Result states "+ss.name.toUtf8() +" checked:"+QByteArray::number(ss.num) +" inserts:"+QByteArray::number(ss.numIns) +" insfail:"+QByteArray::number(ss.numInsFail) +" deletes:"+QByteArray::number(ss.numDel) +" delfail:"+QByteArray::number(ss.numDelFail) +" updates:"+QByteArray::number(ss.numUpd) +" updfail:"+QByteArray::number(ss.numUpdFail); } } } } } if(saveLog) { log->write("\nOutput:\n"+answer); log->write("\nMessage:\n"+formatMessage(answer).toHex()); } output.write(formatMessage(answer)); output.flush(); output.close(); input.close(); }
void sortByEmail(QStringList &sortList) { // Карта для хранения адресов по доменам // Ключ карты - домен, значения - список адресов этого домена QMap<QString, QStringList> sortingMap; QStringList res; // Результирующий лист QStringList sortingKey; // Лист для сортировки ключей QString temp; // Буфер для текущей обрабатываемой строки QString buf; // Буфер для ключа - домена QString str; // Буфер для одного из значений ключа - имени адреса QString aIter; // Буфер для ключа при формировании выходного списка QString aIterKlein; // Буфер для строки из списка для каждой строки из списка // Заполнение карты адресами for(int i=0; i<sortList.count(); i++) { // Загрузка в бущер текущей строки для сортировки temp=sortList[i]; // Получение домена buf=temp.section("@", 1); // Получение имени str=temp.remove(QString("@")+buf); // Заполнение значение карты или создание поля для ключа if(sortingMap.contains(buf)) { sortingMap[buf]<<str; } else { sortingMap.insert(buf, QStringList(str)); } } // Сортировка значений для каждого ключа QMap<QString, QStringList>::iterator it=sortingMap.begin(); for(;it!=sortingMap.end(); it++) { if(it.value().count()>1) { sortByLexeme(it.value()); } } // Записей ключей в лист it=sortingMap.begin(); for(;it!=sortingMap.end(); it++) { sortingKey<<it.key(); } // Сортировка ключей //sortByLexeme(sortingKey); sortingKey.sort(); // Заполнение выходного листа for(int j=0; j<sortingKey.count(); j++) { // Загрузка в бущер текущей строки для ключа aIter=sortingKey[j]; // Загрузка в выходной лист значений для определенного ключа for(int k=0; k<sortingMap[aIter].count(); k++) { // Загрузка в буфер текущей строки для сортировки aIterKlein=sortingMap[aIter][k]+"@"+aIter; // Добавление строки в выходной лист res<<aIterKlein; } } // Замена данного листа на возвращаемый sortList=res; }
// static Skin SkinConfigWidget::loadSkin(KLFPluginConfigAccess * config, const QString& fn, bool getstylesheet) { Q_UNUSED(getstylesheet) ; KLF_DEBUG_BLOCK(KLF_FUNC_NAME) ; klfDbg("loading skin "<<fn<<", get style sheet="<<getstylesheet) ; Skin skin; skin.fn = fn; QFile f(fn); if ( ! f.open(QIODevice::ReadOnly) ) { qWarning()<<KLF_FUNC_NAME<<": Can't read skin "<<fn<<"!"; return skin; } QDomDocument doc("klf-skin"); QString errMsg; int errLine, errCol; bool r = doc.setContent(&f, false, &errMsg, &errLine, &errCol); if (!r) { qWarning()<<KLF_FUNC_NAME<<": Error parsing file "<<fn<<": "<<errMsg<<" at line "<<errLine<<", col "<<errCol; return skin; } f.close(); QDomElement root = doc.documentElement(); if (root.nodeName() != "klf-skin") { qWarning("%s: Error parsing XML for skin `%s': Bad root node `%s'.\n", KLF_FUNC_NAME, qPrintable(fn), qPrintable(root.nodeName())); return skin; } QMap<QString,QString> defines; QStringList stylesheetpath = QStringList() << QLatin1String(":/plugindata/skin/stylesheets") << config->homeConfigPluginDataDir() + "/stylesheets"; // read XML file QDomNode n; for (n = root.firstChild(); ! n.isNull(); n = n.nextSibling()) { QDomElement e = n.toElement(); // try to convert the node to an element. if ( e.isNull() || n.nodeType() != QDomNode::ElementNode ) continue; if ( e.nodeName() == "name" ) { skin.name = qApp->translate("xmltr_pluginskins", e.text().toUtf8().constData(), "[[tag: <name>]]", QCoreApplication::UnicodeUTF8); continue; } else if ( e.nodeName() == "author" ) { skin.author = e.text(); continue; } else if ( e.nodeName() == "def" ) { QString key = e.attribute("name"); QString value = e.text(); if (QRegExp("^[A-Za-z][A-Za-z0-9_]*$").exactMatch(key)) defines[key] = value; else qWarning()<<KLF_FUNC_NAME<<": file "<<fn<<": Illegal <def> name: "<<key; } else if ( e.nodeName() == "description" ) { skin.description = qApp->translate("xmltr_pluginskins", e.text().toUtf8().constData(), "[[tag: <description>]]", QCoreApplication::UnicodeUTF8); continue; } else if ( e.nodeName() == "stylesheet" ) { QString fnqssbase = e.text().trimmed(); QString fnqss = klfSearchPath(fnqssbase, stylesheetpath); QFile fqss(fnqss); if (fnqss.isEmpty() || !fqss.exists() || !fqss.open(QIODevice::ReadOnly)) { qWarning()<<KLF_FUNC_NAME<<"Can't open qss-stylesheet file "<<fnqssbase <<" while reading skin "<<fn<<"."; continue; } QString ss = QString::fromUtf8(fqss.readAll()); if (!defines.isEmpty()) { // we need to process <def>ines ... QRegExp alldefines_rx = QRegExp("\\b("+QStringList(defines.keys()).join("|")+")\\b"); int k = 0; while ( (k = alldefines_rx.indexIn(ss, k+1)) != -1) { QString key = alldefines_rx.cap(1); KLF_ASSERT_CONDITION( defines.contains(key), "Error: key "<<key<<" found, but not in defines=" <<defines<<"?!?", ++k; continue; ) ; QString value = defines[key]; klfDbg("Substituting def. "<<key<<" by "<<value<<" in style sheet "<<fnqss<<" for "<<fn) ; ss.replace(k, alldefines_rx.matchedLength(), value); k += value.length(); } klfDbg("def-Replaced style sheet is \n"<<ss) ; }
int NuppelDecoder::OpenFile(RingBuffer *rbuffer, bool novideo, char testbuf[kDecoderProbeBufferSize], int) { (void)testbuf; ringBuffer = rbuffer; m_disablevideo = novideo; m_tracks[kTrackTypeVideo].clear(); StreamInfo si(0, 0, 0, 0, 0); m_tracks[kTrackTypeVideo].push_back(si); m_selectedTrack[kTrackTypeVideo] = si; struct rtframeheader frameheader; long long startpos = 0; int foundit = 0; char *space; if (!ReadFileheader(&m_fileheader)) { LOG(VB_GENERAL, LOG_ERR, QString("Error reading file: %1").arg(ringBuffer->GetFilename())); return -1; } while ((QString(m_fileheader.finfo) != "NuppelVideo") && (QString(m_fileheader.finfo) != "MythTVVideo")) { ringBuffer->Seek(startpos, SEEK_SET); char dummychar; ringBuffer->Read(&dummychar, 1); startpos = ringBuffer->GetReadPosition(); if (!ReadFileheader(&m_fileheader)) { LOG(VB_GENERAL, LOG_ERR, QString("Error reading file: %1") .arg(ringBuffer->GetFilename())); return -1; } if (startpos > 20000) { LOG(VB_GENERAL, LOG_ERR, QString("Bad file: '%1'") .arg(ringBuffer->GetFilename())); return -1; } } if (m_fileheader.aspect > .999 && m_fileheader.aspect < 1.001) m_fileheader.aspect = 4.0 / 3; m_current_aspect = m_fileheader.aspect; GetPlayer()->SetKeyframeDistance(m_fileheader.keyframedist); GetPlayer()->SetVideoParams(m_fileheader.width, m_fileheader.height, m_fileheader.fps); m_video_width = m_fileheader.width; m_video_height = m_fileheader.height; m_video_size = m_video_height * m_video_width * 3 / 2; m_keyframedist = m_fileheader.keyframedist; m_video_frame_rate = m_fileheader.fps; if (!ReadFrameheader(&frameheader)) { LOG(VB_GENERAL, LOG_ERR, "File not big enough for a header"); return -1; } if (frameheader.frametype != 'D') { LOG(VB_GENERAL, LOG_ERR, "Illegal file format"); return -1; } space = new char[m_video_size]; if (frameheader.comptype == 'F') { m_ffmpeg_extradatasize = frameheader.packetlength; if (m_ffmpeg_extradatasize > 0) { m_ffmpeg_extradata = new uint8_t[m_ffmpeg_extradatasize]; if (frameheader.packetlength != ringBuffer->Read(m_ffmpeg_extradata, frameheader.packetlength)) { LOG(VB_GENERAL, LOG_ERR, "File not big enough for first frame data"); delete [] m_ffmpeg_extradata; m_ffmpeg_extradata = nullptr; delete [] space; return -1; } } } else { if (frameheader.packetlength != ringBuffer->Read(space, frameheader.packetlength)) { LOG(VB_GENERAL, LOG_ERR, "File not big enough for first frame data"); delete [] space; return -1; } } if ((m_video_height & 1) == 1) { m_video_height--; LOG(VB_GENERAL, LOG_ERR, QString("Incompatible video height, reducing to %1") .arg( m_video_height)); } startpos = ringBuffer->GetReadPosition(); ReadFrameheader(&frameheader); if (frameheader.frametype == 'X') { if (frameheader.packetlength != EXTENDEDSIZE) { LOG(VB_GENERAL, LOG_ERR, "Corrupt file. Bad extended frame."); } else { ringBuffer->Read(&m_extradata, frameheader.packetlength); #if HAVE_BIGENDIAN struct extendeddata *ed = &m_extradata; ed->version = bswap_32(ed->version); ed->video_fourcc = bswap_32(ed->video_fourcc); ed->audio_fourcc = bswap_32(ed->audio_fourcc); ed->audio_sample_rate = bswap_32(ed->audio_sample_rate); ed->audio_bits_per_sample = bswap_32(ed->audio_bits_per_sample); ed->audio_channels = bswap_32(ed->audio_channels); ed->audio_compression_ratio = bswap_32(ed->audio_compression_ratio); ed->audio_quality = bswap_32(ed->audio_quality); ed->rtjpeg_quality = bswap_32(ed->rtjpeg_quality); ed->rtjpeg_luma_filter = bswap_32(ed->rtjpeg_luma_filter); ed->rtjpeg_chroma_filter = bswap_32(ed->rtjpeg_chroma_filter); ed->lavc_bitrate = bswap_32(ed->lavc_bitrate); ed->lavc_qmin = bswap_32(ed->lavc_qmin); ed->lavc_qmax = bswap_32(ed->lavc_qmax); ed->lavc_maxqdiff = bswap_32(ed->lavc_maxqdiff); ed->seektable_offset = bswap_64(ed->seektable_offset); ed->keyframeadjust_offset = bswap_64(ed->keyframeadjust_offset); #endif m_usingextradata = true; ReadFrameheader(&frameheader); } } if (m_usingextradata && m_extradata.seektable_offset > 0) { long long currentpos = ringBuffer->GetReadPosition(); struct rtframeheader seek_frameheader; int seekret = ringBuffer->Seek(m_extradata.seektable_offset, SEEK_SET); if (seekret == -1) { LOG(VB_GENERAL, LOG_ERR, QString("NuppelDecoder::OpenFile(): seek error (%1)") .arg(strerror(errno))); } ReadFrameheader(&seek_frameheader); if (seek_frameheader.frametype != 'Q') { LOG(VB_GENERAL, LOG_ERR, QString("Invalid seektable (frametype %1)") .arg((int)seek_frameheader.frametype)); } else { if (seek_frameheader.packetlength > 0) { char *seekbuf = new char[seek_frameheader.packetlength]; ringBuffer->Read(seekbuf, seek_frameheader.packetlength); int numentries = seek_frameheader.packetlength / sizeof(struct seektable_entry); struct seektable_entry ste; int offset = 0; ste.file_offset = 0; ste.keyframe_number = 0; m_positionMapLock.lock(); m_positionMap.clear(); m_positionMap.reserve(numentries); for (int z = 0; z < numentries; z++) { memcpy(&ste, seekbuf + offset, sizeof(struct seektable_entry)); #if HAVE_BIGENDIAN ste.file_offset = bswap_64(ste.file_offset); ste.keyframe_number = bswap_32(ste.keyframe_number); #endif offset += sizeof(struct seektable_entry); PosMapEntry e = {ste.keyframe_number, ste.keyframe_number * m_keyframedist, ste.file_offset}; m_positionMap.push_back(e); uint64_t frame_num = ste.keyframe_number * m_keyframedist; m_frameToDurMap[frame_num] = frame_num * 1000 / m_video_frame_rate; m_durToFrameMap[m_frameToDurMap[frame_num]] = frame_num; } m_hasFullPositionMap = true; m_totalLength = (int)((ste.keyframe_number * m_keyframedist * 1.0) / m_video_frame_rate); m_totalFrames = (long long)ste.keyframe_number * m_keyframedist; m_positionMapLock.unlock(); GetPlayer()->SetFileLength(m_totalLength, m_totalFrames); delete [] seekbuf; } else LOG(VB_GENERAL, LOG_ERR, "0 length seek table"); } ringBuffer->Seek(currentpos, SEEK_SET); } if (m_usingextradata && m_extradata.keyframeadjust_offset > 0 && m_hasFullPositionMap) { long long currentpos = ringBuffer->GetReadPosition(); struct rtframeheader kfa_frameheader; int kfa_ret = ringBuffer->Seek(m_extradata.keyframeadjust_offset, SEEK_SET); if (kfa_ret == -1) { LOG(VB_GENERAL, LOG_ERR, QString("NuppelDecoder::OpenFile(): keyframeadjust (%1)") .arg(strerror(errno))); } ringBuffer->Read(&kfa_frameheader, FRAMEHEADERSIZE); if (kfa_frameheader.frametype != 'K') { LOG(VB_GENERAL, LOG_ERR, QString("Invalid key frame adjust table (frametype %1)") .arg((int)kfa_frameheader.frametype)); } else { if (kfa_frameheader.packetlength > 0) { char *kfa_buf = new char[kfa_frameheader.packetlength]; ringBuffer->Read(kfa_buf, kfa_frameheader.packetlength); int numentries = kfa_frameheader.packetlength / sizeof(struct kfatable_entry); struct kfatable_entry kfate; int offset = 0; int adjust = 0; QMap<long long, int> keyFrameAdjustMap; for (int z = 0; z < numentries; z++) { memcpy(&kfate, kfa_buf + offset, sizeof(struct kfatable_entry)); #if HAVE_BIGENDIAN kfate.adjust = bswap_32(kfate.adjust); kfate.keyframe_number = bswap_32(kfate.keyframe_number); #endif offset += sizeof(struct kfatable_entry); keyFrameAdjustMap[kfate.keyframe_number] = kfate.adjust; adjust += kfate.adjust; } m_hasKeyFrameAdjustTable = true; m_totalLength -= (int)(adjust / m_video_frame_rate); m_totalFrames -= adjust; GetPlayer()->SetFileLength(m_totalLength, m_totalFrames); adjust = 0; { QMutexLocker locker(&m_positionMapLock); for (uint i = 0; i < m_positionMap.size(); i++) { long long adj = m_positionMap[i].adjFrame; if (keyFrameAdjustMap.contains(adj)) adjust += keyFrameAdjustMap[adj]; m_positionMap[i].adjFrame -= adjust; } } delete [] kfa_buf; } else LOG(VB_GENERAL, LOG_ERR, "0 length key frame adjust table"); } ringBuffer->Seek(currentpos, SEEK_SET); } while (frameheader.frametype != 'A' && frameheader.frametype != 'V' && frameheader.frametype != 'S' && frameheader.frametype != 'T' && frameheader.frametype != 'R') { ringBuffer->Seek(startpos, SEEK_SET); char dummychar; ringBuffer->Read(&dummychar, 1); startpos = ringBuffer->GetReadPosition(); if (!ReadFrameheader(&frameheader)) { delete [] space; return -1; } if (startpos > 20000) { delete [] space; return -1; } } foundit = 0; m_effdsp = m_audio_samplerate * 100; m_audio->SetEffDsp(m_effdsp); if (m_usingextradata) { m_effdsp = m_extradata.audio_sample_rate * 100; m_audio->SetEffDsp(m_effdsp); m_audio_samplerate = m_extradata.audio_sample_rate; #if HAVE_BIGENDIAN // Why only if using extradata? m_audio_bits_per_sample = m_extradata.audio_bits_per_sample; #endif AudioFormat format = FORMAT_NONE; switch (m_extradata.audio_bits_per_sample) { case 8: format = FORMAT_U8; break; case 16: format = FORMAT_S16; break; case 24: format = FORMAT_S24; break; case 32: format = FORMAT_S32; break; } m_audio->SetAudioParams(format, m_extradata.audio_channels, m_extradata.audio_channels, AV_CODEC_ID_NONE, m_extradata.audio_sample_rate, false /* AC3/DTS pass through */); m_audio->ReinitAudio(); foundit = 1; } while (!foundit) { if (frameheader.frametype == 'S') { if (frameheader.comptype == 'A') { m_effdsp = frameheader.timecode; if (m_effdsp > 0) { m_audio->SetEffDsp(m_effdsp); foundit = 1; continue; } } } if (frameheader.frametype != 'R' && frameheader.packetlength != 0) { if (frameheader.packetlength != ringBuffer->Read(space, frameheader.packetlength)) { foundit = 1; continue; } } long long startpos2 = ringBuffer->GetReadPosition(); foundit = !ReadFrameheader(&frameheader); bool framesearch = false; while (frameheader.frametype != 'A' && frameheader.frametype != 'V' && frameheader.frametype != 'S' && frameheader.frametype != 'T' && frameheader.frametype != 'R' && frameheader.frametype != 'X') { if (!framesearch) LOG(VB_GENERAL, LOG_INFO, "Searching for frame header."); framesearch = true; ringBuffer->Seek(startpos2, SEEK_SET); char dummychar; ringBuffer->Read(&dummychar, 1); startpos2 = ringBuffer->GetReadPosition(); foundit = !ReadFrameheader(&frameheader); if (foundit) break; } } delete [] space; m_setreadahead = false; // mpeg4 encodes are small enough that this shouldn't matter if (m_usingextradata && m_extradata.video_fourcc == FOURCC_DIVX) m_setreadahead = true; m_bitrate = 0; unsigned min_bitrate = 1000; if (m_usingextradata && m_extradata.video_fourcc == FOURCC_DIVX) { // Use video bitrate, ignore negligible audio bitrate m_bitrate = m_extradata.lavc_bitrate / 1000; } m_bitrate = max(m_bitrate, min_bitrate); // set minimum 1 Mb/s to be safe LOG(VB_PLAYBACK, LOG_INFO, QString("Setting bitrate to %1 Kb/s").arg(m_bitrate)); ringBuffer->UpdateRawBitrate(GetRawBitrate()); m_videosizetotal = 0; m_videoframesread = 0; ringBuffer->Seek(startpos, SEEK_SET); m_buf = (unsigned char*)av_malloc(m_video_size); m_strm = (unsigned char*)av_malloc(m_video_size * 2); if (m_hasFullPositionMap) return 1; if (SyncPositionMap()) return 1; return 0; }
bool MDesktopEntry::readDesktopFile(QIODevice &device, QMap<QString, QString> &desktopEntriesMap) { bool valid = true; // Group header is of form [groupname] // The group name is captured // Group names may contain all ASCII characters except for [ and ] and control characters QRegExp groupHeaderRE("\\[([\\0040-\\0132\\0134\\0136-\\0176]+)\\]"); // Key-value pair is of form Key=Value or Key[localization]=Value // The first capture is the key and the second capture is the value QRegExp keyValueRE("([A-Za-z0-9-]+" // key "(?:\\[[[email protected]]+\\])?" // optional localization ")" // end key capturing "\\s*=\\s*" // equals "(.*)"); // value QString currentGroup; QStringList groupNames; QTextStream stream(&device); stream.setCodec(QTextCodec::codecForName("UTF-8")); while (!stream.atEnd()) { QString line = stream.readLine().trimmed(); if (!line.isEmpty() && !line.startsWith('#')) { if (keyValueRE.exactMatch(line) && !currentGroup.isEmpty()) { // A key-value line was found. Prepend the key with the current group name. QString desktopKey = currentGroup + '/' + keyValueRE.cap(1); // Check whether it's already in the map if (!desktopEntriesMap.contains(desktopKey)) { QString value = keyValueRE.cap(2); // Check whether this is a known multivalue key if (desktopKey == CategoriesKey || desktopKey == OnlyShowInKey || desktopKey == NotShowInKey || desktopKey == MimeTypeKey) { if (value.endsWith("\\;") || !value.endsWith(';')) { // Multivalue doesn't end with a semicolon so mark the desktop entry invalid qDebug() << "Value for multivalue key" << desktopKey << "does not end in a semicolon"; valid = false; } } // Add the value to the desktop entries map desktopEntriesMap.insert(desktopKey, value); } else { // Key is already present in the map so issue a warning qDebug() << "Key" << desktopKey << "already defined. Value" << keyValueRE.cap(2) << "is ignored"; } } else if (groupHeaderRE.exactMatch(line)) { // A group header line was found and if it's not already defined, set it as current group if (!groupNames.contains(groupHeaderRE.cap(1), Qt::CaseSensitive)) { if (groupNames.isEmpty() && groupHeaderRE.cap(1) != "Desktop Entry") { qDebug() << "Desktop entry should start with group name \"Desktop Entry\" "; valid = false; } else { groupNames.push_back(groupHeaderRE.cap(1)); currentGroup = groupHeaderRE.cap(1); } } // Redefining a group name will cause the desktop entry to become invalid but still parsed by the parser. else { currentGroup = groupHeaderRE.cap(1); qDebug() << "Multiple definitions of group" << groupHeaderRE.cap(1); valid = false; } } else { qDebug() << "Invalid .desktop entry line:" << line; } } } return valid; }
void Application::init() { // Initialise the unicorn base class first! unicorn::Application::init(); if ( !currentSession() ) { // there won't be a current session if one wasn't created by the wizard QMap<QString, QString> lastSession = unicorn::Session::lastSessionData(); if ( lastSession.contains( "username" ) && lastSession.contains( "sessionKey" ) ) changeSession( lastSession[ "username" ], lastSession[ "sessionKey" ] ); } initiateLogin( !currentSession() ); // QNetworkDiskCache* diskCache = new QNetworkDiskCache(this); // diskCache->setCacheDirectory( lastfm::dir::cache().path() ); // lastfm::nam()->setCache( diskCache ); m_menuBar = new QMenuBar( 0 ); /// tray tray(); // this will initialise m_tray if it doesn't already exist /// tray menu QMenu* menu = new QMenu; menu->addMenu( new UserMenu() )->setText( "Accounts" ); m_show_window_action = menu->addAction( tr("Show Scrobbler")); m_show_window_action->setShortcut( Qt::CTRL + Qt::META + Qt::Key_S ); menu->addSeparator(); { m_love_action = menu->addAction( tr("Love") ); m_love_action->setCheckable( true ); QIcon loveIcon; loveIcon.addFile( ":/meta_love_OFF_REST.png", QSize( 16, 16 ), QIcon::Normal, QIcon::Off ); loveIcon.addFile( ":/meta_love_ON_REST.png", QSize( 16, 16 ), QIcon::Normal, QIcon::On ); m_love_action->setIcon( loveIcon ); m_love_action->setEnabled( false ); connect( m_love_action, SIGNAL(triggered(bool)), SLOT(changeLovedState(bool))); } { m_tag_action = menu->addAction(tr("Tag")+ELLIPSIS); m_tag_action->setIcon( QIcon( ":/meta_tag_REST.png" ) ); m_tag_action->setEnabled( false ); connect( m_tag_action, SIGNAL(triggered()), SLOT(onTagTriggered())); } { m_share_action = menu->addAction(tr("Share")+ELLIPSIS); m_share_action->setIcon( QIcon( ":/meta_share_REST.png" ) ); m_share_action->setEnabled( false ); connect( m_share_action, SIGNAL(triggered()), SLOT(onShareTriggered())); } { m_ban_action = new QAction( tr( "Ban" ), this ); QIcon banIcon; banIcon.addFile( ":/controls_ban_REST.png" ); m_ban_action->setIcon( banIcon ); m_ban_action->setEnabled( false ); } { m_play_action = new QAction( tr( "Play" ), this ); m_play_action->setCheckable( true ); QIcon playIcon; playIcon.addFile( ":/controls_pause_REST.png", QSize(), QIcon::Normal, QIcon::On ); playIcon.addFile( ":/controls_play_REST.png", QSize(), QIcon::Normal, QIcon::Off ); m_play_action->setIcon( playIcon ); } { m_skip_action = new QAction( tr( "Skip" ), this ); QIcon skipIcon; skipIcon.addFile( ":/controls_skip_REST.png" ); m_skip_action->setIcon( skipIcon ); m_skip_action->setEnabled( false ); } #ifdef Q_WS_X11 menu->addSeparator(); m_scrobble_ipod_action = menu->addAction( tr( "Scrobble iPod..." ) ); connect( m_scrobble_ipod_action, SIGNAL( triggered() ), ScrobbleService::instance().deviceScrobbler(), SLOT( onScrobbleIpodTriggered() ) ); #endif menu->addSeparator(); m_visit_profile_action = menu->addAction( tr( "Visit Last.fm profile" ) ); connect( m_visit_profile_action, SIGNAL( triggered() ), SLOT( onVisitProfileTriggered() ) ); menu->addSeparator(); m_submit_scrobbles_toggle = menu->addAction( tr("Enable Scrobbling") ); m_submit_scrobbles_toggle->setCheckable( true ); bool scrobblingOn = unicorn::UserSettings().value( "scrobblingOn", true ).toBool(); m_submit_scrobbles_toggle->setChecked( scrobblingOn ); ScrobbleService::instance().scrobbleSettingsChanged(); connect( m_submit_scrobbles_toggle, SIGNAL(toggled(bool)), SLOT(onScrobbleToggled(bool)) ); connect( this, SIGNAL(scrobbleToggled(bool)), &ScrobbleService::instance(), SLOT(scrobbleSettingsChanged()) ); menu->addSeparator(); QAction* quit = menu->addAction(tr("Quit %1").arg( applicationName())); connect(quit, SIGNAL(triggered()), SLOT(quit())); m_tray->setContextMenu(menu); /// MainWindow m_mw = new MainWindow( m_menuBar ); m_mw->addWinThumbBarButton( m_love_action ); m_mw->addWinThumbBarButton( m_ban_action ); m_mw->addWinThumbBarButton( m_play_action ); m_mw->addWinThumbBarButton( m_skip_action ); m_toggle_window_action = new QAction( this ), SLOT( trigger()); #ifndef Q_OS_LINUX AudioscrobblerSettings settings; setRaiseHotKey( settings.raiseShortcutModifiers(), settings.raiseShortcutKey() ); #endif m_skip_action->setShortcut( Qt::CTRL + Qt::Key_Right ); m_tag_action->setShortcut( Qt::CTRL + Qt::Key_T ); m_share_action->setShortcut( Qt::CTRL + Qt::Key_S ); m_love_action->setShortcut( Qt::CTRL + Qt::Key_L ); m_ban_action->setShortcut( Qt::CTRL + Qt::Key_B ); // make the love buttons sychronised connect(this, SIGNAL(lovedStateChanged(bool)), m_love_action, SLOT(setChecked(bool))); // tell the radio that the scrobbler's love state has changed connect(this, SIGNAL(lovedStateChanged(bool)), SLOT(sendBusLovedStateChanged(bool))); // update the love buttons if love was pressed in the radio connect(this, SIGNAL(busLovedStateChanged(bool)), m_love_action, SLOT(setChecked(bool))); connect(this, SIGNAL(busLovedStateChanged(bool)), SLOT(onBusLovedStateChanged(bool))); // tell everyone that is interested that data about the current track has been fetched connect( m_mw, SIGNAL(trackGotInfo(XmlQuery)), SIGNAL(trackGotInfo(XmlQuery))); connect( m_mw, SIGNAL(albumGotInfo(XmlQuery)), SIGNAL(albumGotInfo(XmlQuery))); connect( m_mw, SIGNAL(artistGotInfo(XmlQuery)), SIGNAL(artistGotInfo(XmlQuery))); connect( m_mw, SIGNAL(artistGotEvents(XmlQuery)), SIGNAL(artistGotEvents(XmlQuery))); connect( m_mw, SIGNAL(trackGotTopFans(XmlQuery)), SIGNAL(trackGotTopFans(XmlQuery))); connect( m_mw, SIGNAL(trackGotTags(XmlQuery)), SIGNAL(trackGotTags(XmlQuery))); connect( m_mw, SIGNAL(finished()), SIGNAL(finished())); connect( m_mw, SIGNAL(trackGotInfo(XmlQuery)), this, SLOT(onTrackGotInfo(XmlQuery))); connect( m_show_window_action, SIGNAL( triggered()), SLOT( showWindow()), Qt::QueuedConnection ); connect( m_toggle_window_action, SIGNAL( triggered()), SLOT( toggleWindow()), Qt::QueuedConnection ); connect( this, SIGNAL(messageReceived(QStringList)), SLOT(onMessageReceived(QStringList)) ); connect( this, SIGNAL( sessionChanged( unicorn::Session* ) ), &ScrobbleService::instance(), SLOT( onSessionChanged( unicorn::Session* ) ) ); connect( &ScrobbleService::instance(), SIGNAL(trackStarted(Track,Track)), SLOT(onTrackStarted(Track,Track))); connect( &ScrobbleService::instance(), SIGNAL(paused(bool)), SLOT(onTrackPaused(bool))); connect( &RadioService::instance(), SIGNAL(trackSpooled(Track)), SLOT(onTrackSpooled(Track)) ); // clicking on a system tray message should show the scrobbler connect( m_tray, SIGNAL(messageClicked()), m_show_window_action, SLOT(trigger())); // make sure cached scrobbles get submitted when the connection comes back online connect( m_icm, SIGNAL(up(QString)), &ScrobbleService::instance(), SLOT(submitCache()) ); emit messageReceived( arguments() ); #ifdef Q_OS_MAC m_notify = new Notify( this ); connect( m_notify, SIGNAL(clicked()), SLOT(showWindow()) ); new CommandReciever( this ); #endif }
static QMap<QString, Field> getFields(QDomElement record, bool* foundStrings = 0) { QDomNodeList types = record.elementsByTagName("type"); QMap<QString, QString> extraTypes; QMap<QString, QString> extraTypesDefaults; for (int i = 0; i < types.size(); i++) { QDomElement e = types.at(i).toElement(); extraTypes[e.attribute("name")] = e.attribute("type"); if (e.elementsByTagName("enum").size() > 0) extraTypesDefaults[e.attribute("name")] = e.elementsByTagName("enum").at(0).toElement().attribute("name"); } QDomNodeList fields = record.elementsByTagName("field"); QMap<QString, Field> map; for (int i = 0; i < fields.size(); i++) { QDomElement e = fields.at(i).toElement(); QString name = e.attribute("name"); if (!name.startsWith("reserved")) { map[name] = Field(name, getFieldType(e.attribute("type"), e.attribute("size").toUInt(), map[name].type, extraTypes)); if (foundStrings && map[name].type == "QString") *foundStrings = true; if (hasParentNode(e, "array")) { map[name].isArray = true; } if (e.elementsByTagName("enum").size() > 0) { map[name].isEnum = true; map[name].type = ucFirst(name); map[name].defaultValue = e.elementsByTagName("enum").at(0).toElement().attribute("name"); } if (extraTypes.contains(e.attribute("type"))) { map[name].isEnum = true; map[name].type = e.attribute("type"); map[name].defaultValue = extraTypesDefaults[e.attribute("type")]; } if (e.hasAttribute("default")) map[name].defaultValue = e.attribute("default"); } } for (int i = 0; i < fields.size(); i++) { QDomElement e = fields.at(i).toElement(); if (e.hasAttribute("length")) { QString name = e.attribute("length"); if (map.contains(name)) { map[name].isStringLength = true; map[name].lengthFor = e.attribute("name"); } } } QDomNodeList arrays = record.elementsByTagName("array"); for (int i = 0; i < arrays.size(); i++) { QDomElement e = arrays.at(i).toElement(); QString name = e.attribute("length"); if (map.contains(name)) { Field& field = map[name]; field.isArrayLength = true; QDomNodeList afields = e.elementsByTagName("field"); for (int j = 0; j < afields.size(); j++) { QDomElement af = afields.at(j).toElement(); QString fname = af.attribute("name"); if (!fname.startsWith("reserved")) field.arrayFields.append(map[fname]); } } } return map; }
QDomDocument LibraryTreeWidget::toXml() const { QDomDocument doc; QDomElement root = doc.createElement("project"); QDomElement properties = doc.createElement("properties"); // graphics options properties.setAttribute("scaleMode", properties_.scaleMode); properties.setAttribute("logicalWidth", properties_.logicalWidth); properties.setAttribute("logicalHeight", properties_.logicalHeight); QDomElement imageScales = doc.createElement("imageScales"); for (size_t i = 0; i < properties_.imageScales.size(); ++i) { QDomElement scale = doc.createElement("scale"); scale.setAttribute("suffix", properties_.imageScales[i].first); scale.setAttribute("scale", properties_.imageScales[i].second); imageScales.appendChild(scale); } properties.appendChild(imageScales); properties.setAttribute("orientation", properties_.orientation); properties.setAttribute("fps", properties_.fps); // iOS options properties.setAttribute("retinaDisplay", properties_.retinaDisplay); properties.setAttribute("autorotation", properties_.autorotation); // input options properties.setAttribute("mouseToTouch", properties_.mouseToTouch ? 1 : 0); properties.setAttribute("touchToMouse", properties_.touchToMouse ? 1 : 0); properties.setAttribute("mouseTouchOrder", properties_.mouseTouchOrder); // export options properties.setAttribute("architecture", properties_.architecture); properties.setAttribute("assetsOnly", properties_.assetsOnly ? 1 : 0); properties.setAttribute("iosDevice", properties_.iosDevice); properties.setAttribute("packageName", properties_.packageName); properties.setAttribute("encryptCode", properties_.encryptCode); properties.setAttribute("encryptAssets", properties_.encryptAssets); root.appendChild(properties); doc.appendChild(root); QTreeWidgetItem* rootitem = invisibleRootItem(); if (rootitem->childCount()) rootitem = rootitem->child(0); std::stack<std::pair<QTreeWidgetItem*, QDomElement> > stack; stack.push(std::make_pair(rootitem, root)); while (stack.empty() == false) { QTreeWidgetItem* item = stack.top().first; QDomElement element = stack.top().second; stack.pop(); for (int i = 0; i < item->childCount(); ++i) { QTreeWidgetItem* childItem = item->child(i); QMap<QString, QVariant> data = childItem->data(0, Qt::UserRole).toMap(); QString fileName = data["filename"].toString(); QDomElement childElement = doc.createElement(fileName.isEmpty() ? "folder" : "file"); if (fileName.isEmpty() == false) { childElement.setAttribute("source", fileName); if (data.contains("downsizing") && data["downsizing"].toBool()) childElement.setAttribute("downsizing", 1); if (data.contains("excludeFromExecution") && data["excludeFromExecution"].toBool()) childElement.setAttribute("excludeFromExecution", 1); } else childElement.setAttribute("name", childItem->text(0)); element.appendChild(childElement); stack.push(std::make_pair(childItem, childElement)); } } std::vector<std::pair<QString, QString> > dependencies = dependencyGraph_.dependencies(); for (std::size_t i = 0; i < dependencies.size(); ++i) { QDomElement childElement = doc.createElement("dependency"); childElement.setAttribute("from", dependencies[i].first); childElement.setAttribute("to", dependencies[i].second); root.appendChild(childElement); } return doc; }