void Rest::write(Xml& xml) const { xml.stag(name()); ChordRest::writeProperties(xml); xml.etag(); }
void CAppConfig::SetLastSelectedGame(const char *aGameName) { TPtrC8 name((const TUint8*)aGameName); SetConfig(KCfgLastSelectedGame, TConfig(EConfigText8, &name)); }
QString BitcoinUnits::formatWithUnit(int unit, qint64 amount, bool plussign) { return format(unit, amount, plussign) + QString(" ") + name(unit); }
echo_plugin::echo_plugin() : log_(boost::log::keywords::channel = uid()) { BOOST_LOG_SEV(log_, logging::trace) << name() << " created"; }
void AbstractParam::restoreValue(QSettings& settings) { if ((type() != QVariant::Invalid) && !name().isEmpty()) { QVariant v = settings.value(name()); setValue(v); } }
void UmlOperation::gen_uml_decl() { if (isAbstract()) fw.write("abstract, "); if (isClassMember()) fw.write("static, "); write(visibility()); writeq(name()); const Q3ValueList<UmlParameter> & pa = params(); unsigned npa = pa.count(); unsigned rank; const char * sep = "("; for (rank = 0; rank != npa; rank += 1) { const UmlParameter & p = pa[rank]; fw.write(sep); sep = ", "; switch (p.dir) { case InputOutputDirection: fw.write("inout "); break; case InputDirection: fw.write("in "); break; default: // OutputDirection fw.write("out "); } writeq(p.name); fw.write(" : "); write(p.type); Q3CString s = p.default_value; if (!s.isEmpty()) { if (s[0] != '=') fw.write(" = "); writeq(s); } } fw.write((rank == 0) ? "() : " : ") : "); write(returnType()); sep = ", exceptions : "; const Q3ValueList<UmlTypeSpec> e = exceptions(); unsigned n = e.count(); for (unsigned index2 = 0; index2 != n; index2 += 1) { fw.write(sep); sep = ", "; write(e[index2]); } }
// // R_InitTextures // Initializes the texture list // with the textures from the world map. // void R_InitTextures (void) { maptexture_t* mtexture; texture_t* texture; mappatch_t* mpatch; texpatch_t* patch; int i; int j; int* maptex; int* maptex2; int* maptex1; std::string name(9,'0'); char* names; char* name_p; int* patchlookup; int totalwidth; int nummappatches; int offset; int maxoff; int maxoff2; int numtextures1; int numtextures2; int* directory; int temp1; int temp2; int temp3; // Load the patch names from pnames.lmp. names = (char*)WadManager::getLump ("PNAMES"); nummappatches = *((int *)names) ; name_p = names+4; patchlookup = (int*)alloca (nummappatches*sizeof(*patchlookup)); for (i=0 ; i<nummappatches ; i++) { name = std::string(name_p+i*8, 8); patchlookup[i] = WadManager::checkNumForName (name); } // Load the map texture definitions from textures.lmp. // The data is contained in one or two lumps, // TEXTURE1 for shareware, plus TEXTURE2 for commercial. maptex = maptex1 = (int*)WadManager::getLump ("TEXTURE1"); numtextures1 = *maptex; maxoff = WadManager::getLumpLength (WadManager::getNumForName ("TEXTURE1")); directory = maptex+1; if (WadManager::checkNumForName ("TEXTURE2") != -1) { maptex2 = (int*)WadManager::getLump ("TEXTURE2"); numtextures2 = *maptex2; maxoff2 = WadManager::getLumpLength (WadManager::getNumForName ("TEXTURE2")); } else { maptex2 = NULL; numtextures2 = 0; maxoff2 = 0; } numtextures = numtextures1 + numtextures2; textures = (texture_t**)malloc (numtextures*sizeof(void*)); texturecolumnlump = (short**)malloc (numtextures*sizeof(void*)); texturecolumnofs = (unsigned short**)malloc (numtextures*sizeof(void*)); texturecomposite = (unsigned char**)malloc (numtextures*sizeof(void*)); texturecompositesize = (int*)malloc (numtextures*sizeof(void*)); texturewidthmask = (int*)malloc (numtextures*sizeof(void*)); textureheight = (int*)malloc (numtextures*sizeof(void*)); totalwidth = 0; // Really complex printing shit... temp1 = WadManager::getNumForName ("S_START"); // P_??????? temp2 = WadManager::getNumForName ("S_END") - 1; temp3 = ((temp2-temp1+63)/64) + ((numtextures+63)/64); printf("["); for (i = 0; i < temp3; i++) printf(" "); printf(" ]"); for (i = 0; i < temp3; i++) printf("\x8"); printf("\x8\x8\x8\x8\x8\x8\x8\x8\x8\x8"); for (i=0 ; i<numtextures ; i++, directory++) { if (!(i&63)) printf ("."); if (i == numtextures1) { // Start looking in second texture file. maptex = maptex2; maxoff = maxoff2; directory = maptex+1; } offset = *directory; if (offset > maxoff) I_Error ("R_InitTextures: bad texture directory"); mtexture = (maptexture_t *) ( (unsigned char *)maptex + offset); texture = textures[i] = (texture_t*)malloc (sizeof(texture_t) + sizeof(texpatch_t)*(mtexture->patchcount-1)); texture->width = mtexture->width; texture->height = mtexture->height; texture->patchcount = mtexture->patchcount; memcpy (texture->name, mtexture->name, sizeof(texture->name)); mpatch = &mtexture->patches[0]; patch = &texture->patches[0]; for (j=0 ; j<texture->patchcount ; j++, mpatch++, patch++) { patch->originx = mpatch->originx; patch->originy = mpatch->originy; patch->patch = patchlookup[short(mpatch->patch)]; if (patch->patch == -1) { I_Error ("R_InitTextures: Missing patch in texture %s", texture->name); } } texturecolumnlump[i] = (short*)malloc (texture->width*2); texturecolumnofs[i] = (unsigned short*)malloc (texture->width*2); j = 1; while (j*2 <= texture->width) j<<=1; texturewidthmask[i] = j-1; textureheight[i] = texture->height<<FRACBITS; totalwidth += texture->width; } // Precalculate whatever possible. for (i=0 ; i<numtextures ; i++) R_GenerateLookup (i); // Create translation table for global animation. texturetranslation = (int*)malloc ((numtextures+1)*4); for (i=0 ; i<numtextures ; i++) texturetranslation[i] = i; }
void Cat::move(){ cout << "Move like " << name() << " the Cat" << endl; }
Cat::~Cat(){ cout << "Remove "<< name() << " the Cat" << endl; }
Person_i(const char* n, CORBA::Long bal) { name(n); balance(bal); }
void Cat::act(){ cout << "Act playful, " << name() <<" the Cat" << endl; }
ATTR_COLD void device_t::connect_late(const pstring &t1, const pstring &t2) { setup().register_link_fqn(name() + "." + t1, name() + "." + t2); }
void CGUI::Xeromyces_ReadObject(XMBElement Element, CXeromyces* pFile, IGUIObject* pParent, std::vector<std::pair<CStr, CStr> >& NameSubst, boost::unordered_set<VfsPath>& Paths, u32 nesting_depth) { ENSURE(pParent); XMBAttributeList attributes = Element.GetAttributes(); CStr type(attributes.GetNamedItem(pFile->GetAttributeID("type"))); if (type.empty()) type = "empty"; // Construct object from specified type // henceforth, we need to do a rollback before aborting. // i.e. releasing this object IGUIObject* object = ConstructObject(type); if (!object) { LOGERROR("GUI: Unrecognized object type \"%s\"", type.c_str()); return; } // Cache some IDs for element attribute names, to avoid string comparisons #define ELMT(x) int elmt_##x = pFile->GetElementID(#x) #define ATTR(x) int attr_##x = pFile->GetAttributeID(#x) ELMT(object); ELMT(action); ELMT(repeat); ELMT(translatableAttribute); ELMT(translate); ELMT(attribute); ELMT(keep); ELMT(include); ATTR(style); ATTR(type); ATTR(name); ATTR(hotkey); ATTR(z); ATTR(on); ATTR(file); ATTR(directory); ATTR(id); ATTR(context); // // Read Style and set defaults // // If the setting "style" is set, try loading that setting. // // Always load default (if it's available) first! // CStr argStyle(attributes.GetNamedItem(attr_style)); if (m_Styles.count("default") == 1) object->LoadStyle(*this, "default"); if (!argStyle.empty()) { if (m_Styles.count(argStyle) == 0) LOGERROR("GUI: Trying to use style '%s' that doesn't exist.", argStyle.c_str()); else object->LoadStyle(*this, argStyle); } bool NameSet = false; bool ManuallySetZ = false; CStrW inclusionPath; CStr hotkeyTag; for (XMBAttribute attr : attributes) { // If value is "null", then it is equivalent as never being entered if (CStr(attr.Value) == "null") continue; // Ignore "type" and "style", we've already checked it if (attr.Name == attr_type || attr.Name == attr_style) continue; if (attr.Name == attr_name) { CStr name(attr.Value); for (const std::pair<CStr, CStr>& sub : NameSubst) name.Replace(sub.first, sub.second); object->SetName(name); NameSet = true; continue; } if (attr.Name == attr_hotkey) hotkeyTag = attr.Value; if (attr.Name == attr_z) ManuallySetZ = true; if (object->SetSetting(pFile->GetAttributeString(attr.Name), attr.Value.FromUTF8(), true) != PSRETURN_OK) LOGERROR("GUI: (object: %s) Can't set \"%s\" to \"%s\"", object->GetPresentableName(), pFile->GetAttributeString(attr.Name), attr.Value); } // Check if name isn't set, generate an internal name in that case. if (!NameSet) { object->SetName("__internal(" + CStr::FromInt(m_InternalNameNumber) + ")"); ++m_InternalNameNumber; } if (!hotkeyTag.empty()) m_HotkeyObjects[hotkeyTag].push_back(object); CStrW caption(Element.GetText().FromUTF8()); if (!caption.empty()) object->SetSetting("caption", caption, true); for (XMBElement child : Element.GetChildNodes()) { // Check what name the elements got int element_name = child.GetNodeName(); if (element_name == elmt_object) { // Call this function on the child Xeromyces_ReadObject(child, pFile, object, NameSubst, Paths, nesting_depth); } else if (element_name == elmt_action) { // Scripted <action> element // Check for a 'file' parameter CStrW filename(child.GetAttributes().GetNamedItem(attr_file).FromUTF8()); CStr code; // If there is a file, open it and use it as the code if (!filename.empty()) { Paths.insert(filename); CVFSFile scriptfile; if (scriptfile.Load(g_VFS, filename) != PSRETURN_OK) { LOGERROR("Error opening GUI script action file '%s'", utf8_from_wstring(filename)); throw PSERROR_GUI_JSOpenFailed(); } code = scriptfile.DecodeUTF8(); // assume it's UTF-8 } XMBElementList grandchildren = child.GetChildNodes(); if (!grandchildren.empty()) // The <action> element contains <keep> and <translate> tags. for (XMBElement grandchild : grandchildren) { if (grandchild.GetNodeName() == elmt_translate) code += g_L10n.Translate(grandchild.GetText()); else if (grandchild.GetNodeName() == elmt_keep) code += grandchild.GetText(); } else // It’s pure JavaScript code. // Read the inline code (concatenating to the file code, if both are specified) code += CStr(child.GetText()); CStr action = CStr(child.GetAttributes().GetNamedItem(attr_on)); // We need to set the GUI this object belongs to because RegisterScriptHandler requires an associated GUI. object->SetGUI(this); object->RegisterScriptHandler(action.LowerCase(), code, this); } else if (element_name == elmt_repeat) { Xeromyces_ReadRepeat(child, pFile, object, NameSubst, Paths, nesting_depth); } else if (element_name == elmt_translatableAttribute) { // This is an element in the form “<translatableAttribute id="attributeName">attributeValue</translatableAttribute>”. CStr attributeName(child.GetAttributes().GetNamedItem(attr_id)); // Read the attribute name. if (attributeName.empty()) { LOGERROR("GUI: ‘translatableAttribute’ XML element with empty ‘id’ XML attribute found. (object: %s)", object->GetPresentableName().c_str()); continue; } CStr value(child.GetText()); if (value.empty()) continue; CStr context(child.GetAttributes().GetNamedItem(attr_context)); // Read the context if any. if (!context.empty()) { CStr translatedValue(g_L10n.TranslateWithContext(context, value)); object->SetSetting(attributeName, translatedValue.FromUTF8(), true); } else { CStr translatedValue(g_L10n.Translate(value)); object->SetSetting(attributeName, translatedValue.FromUTF8(), true); } } else if (element_name == elmt_attribute) { // This is an element in the form “<attribute id="attributeName"><keep>Don’t translate this part // </keep><translate>but translate this one.</translate></attribute>”. CStr attributeName(child.GetAttributes().GetNamedItem(attr_id)); // Read the attribute name. if (attributeName.empty()) { LOGERROR("GUI: ‘attribute’ XML element with empty ‘id’ XML attribute found. (object: %s)", object->GetPresentableName().c_str()); continue; } CStr translatedValue; for (XMBElement grandchild : child.GetChildNodes()) { if (grandchild.GetNodeName() == elmt_translate) translatedValue += g_L10n.Translate(grandchild.GetText()); else if (grandchild.GetNodeName() == elmt_keep) translatedValue += grandchild.GetText(); } object->SetSetting(attributeName, translatedValue.FromUTF8(), true); } else if (element_name == elmt_include) { CStrW filename(child.GetAttributes().GetNamedItem(attr_file).FromUTF8()); CStrW directory(child.GetAttributes().GetNamedItem(attr_directory).FromUTF8()); if (!filename.empty()) { if (!directory.empty()) LOGWARNING("GUI: Include element found with file name (%s) and directory name (%s). Only the file will be processed.", utf8_from_wstring(filename), utf8_from_wstring(directory)); Paths.insert(filename); CXeromyces XeroIncluded; if (XeroIncluded.Load(g_VFS, filename, "gui") != PSRETURN_OK) { LOGERROR("GUI: Error reading included XML: '%s'", utf8_from_wstring(filename)); continue; } XMBElement node = XeroIncluded.GetRoot(); if (node.GetNodeName() != XeroIncluded.GetElementID("object")) { LOGERROR("GUI: Error reading included XML: '%s', root element must have be of type 'object'.", utf8_from_wstring(filename)); continue; } if (nesting_depth+1 >= MAX_OBJECT_DEPTH) { LOGERROR("GUI: Too many nested GUI includes. Probably caused by a recursive include attribute. Abort rendering '%s'.", utf8_from_wstring(filename)); continue; } Xeromyces_ReadObject(node, &XeroIncluded, object, NameSubst, Paths, nesting_depth+1); } else if (!directory.empty()) { if (nesting_depth+1 >= MAX_OBJECT_DEPTH) { LOGERROR("GUI: Too many nested GUI includes. Probably caused by a recursive include attribute. Abort rendering '%s'.", utf8_from_wstring(directory)); continue; } VfsPaths pathnames; vfs::GetPathnames(g_VFS, directory, L"*.xml", pathnames); for (const VfsPath& path : pathnames) { // as opposed to loading scripts, don't care if it's loaded before // one might use the same parts of the GUI in different situations Paths.insert(path); CXeromyces XeroIncluded; if (XeroIncluded.Load(g_VFS, path, "gui") != PSRETURN_OK) { LOGERROR("GUI: Error reading included XML: '%s'", path.string8()); continue; } XMBElement node = XeroIncluded.GetRoot(); if (node.GetNodeName() != XeroIncluded.GetElementID("object")) { LOGERROR("GUI: Error reading included XML: '%s', root element must have be of type 'object'.", path.string8()); continue; } Xeromyces_ReadObject(node, &XeroIncluded, object, NameSubst, Paths, nesting_depth+1); } } else LOGERROR("GUI: 'include' XML element must have valid 'file' or 'directory' attribute found. (object %s)", object->GetPresentableName().c_str()); } else { // Try making the object read the tag. if (!object->HandleAdditionalChildren(child, pFile)) LOGERROR("GUI: (object: %s) Reading unknown children for its type", object->GetPresentableName().c_str()); } } if (!ManuallySetZ) { // Set it automatically to 10 plus its parents bool absolute; GUI<bool>::GetSetting(object, "absolute", absolute); if (absolute) // If the object is absolute, we'll have to get the parent's Z buffered, // and add to that! GUI<float>::SetSetting(object, "z", pParent->GetBufferedZ() + 10.f, true); else // If the object is relative, then we'll just store Z as "10" GUI<float>::SetSetting(object, "z", 10.f, true); } try { if (pParent == m_BaseObject) AddObject(object); else pParent->AddChild(object); } catch (PSERROR_GUI& e) { LOGERROR("GUI error: %s", e.what()); } }
void UmlComponent::write(FileOut & out) { const char * k = (parent()->kind() == anUseCase) ? "ownedUseCase" : ((_uml_20) ? "ownedMember" : "packagedElement"); out.indent(); out << "<" << k << " xmi:type=\"uml:Component\""; out.id(this); out << " name=\""; out.quote((const char*)name());//[jasa] ambiguous call out << "\">\n"; out.indent(+1); write_description_properties(out); const Q3PtrVector<UmlItem> ch = children(); unsigned n = ch.size(); unsigned index; for (index = 0; index != n; index += 1) ch[index]->write(out); // provided const Q3PtrVector< UmlClass > & prov = providedClasses(); n = prov.size(); for (index = 0; index != n; index += 1) { UmlClass * cl = prov[index]; out.indent(); out << "<interfaceRealization xmi:type=\"uml:InterfaceRealization\""; out.id_prefix(this, "PROV_", index); out.ref(cl, "supplier"); out.ref(this, "client"); out.ref(cl, "contract"); out << "/>\n"; } // realizing const Q3PtrVector< UmlClass > & rea = realizingClasses(); n = rea.size(); for (index = 0; index != n; index += 1) { UmlClass * cl = rea[index]; out.indent(); out << "<realization xmi:type=\"uml:ComponentRealization\""; out.id_prefix(this, "REA_", index); out.ref(cl, "supplier"); out.ref(this, "client"); out.ref(cl, "realizingClassifier"); out << "/>\n"; } out.indent(-1); out.indent(); out << "</" << k << ">\n"; // required const Q3PtrVector< UmlClass > & req = requiredClasses(); n = req.size(); for (index = 0; index != n; index += 1) { UmlClass * cl = req[index]; out.indent(); out << "<" << k << " xmi:type=\"uml:Usage\""; out.id_prefix(this, "REQ_", index); out.ref(cl, "supplier"); out.ref(this, "client"); out << "/>\n"; } unload(); }
int QResourceRoot::findNode(const QString &_path, const QLocale &locale) const { QString path = _path; { QString root = mappingRoot(); if(!root.isEmpty()) { if(root == path) { path = QLatin1Char('/'); } else { if(!root.endsWith(QLatin1Char('/'))) root += QLatin1Char('/'); if(path.size() >= root.size() && path.startsWith(root)) path = path.mid(root.length()-1); if(path.isEmpty()) path = QLatin1Char('/'); } } } #ifdef DEBUG_RESOURCE_MATCH qDebug() << "!!!!" << "START" << path << locale.country() << locale.language(); #endif if(path == QLatin1String("/")) return 0; //the root node is always first int child_count = (tree[6] << 24) + (tree[7] << 16) + (tree[8] << 8) + (tree[9] << 0); int child = (tree[10] << 24) + (tree[11] << 16) + (tree[12] << 8) + (tree[13] << 0); //now iterate up the tree int node = -1; QStringSplitter splitter(path); while (child_count && splitter.hasNext()) { QStringRef segment = splitter.next(); #ifdef DEBUG_RESOURCE_MATCH qDebug() << " CHILDREN" << segment; for(int j = 0; j < child_count; ++j) { qDebug() << " " << child+j << " :: " << name(child+j); } #endif const uint h = qt_hash(segment); //do the binary search for the hash int l = 0, r = child_count-1; int sub_node = (l+r+1)/2; while(r != l) { const uint sub_node_hash = hash(child+sub_node); if(h == sub_node_hash) break; else if(h < sub_node_hash) r = sub_node - 1; else l = sub_node; sub_node = (l + r + 1) / 2; } sub_node += child; //now do the "harder" compares bool found = false; if(hash(sub_node) == h) { while(sub_node > child && hash(sub_node-1) == h) //backup for collisions --sub_node; for(; sub_node < child+child_count && hash(sub_node) == h; ++sub_node) { //here we go... if(name(sub_node) == segment) { found = true; int offset = findOffset(sub_node); #ifdef DEBUG_RESOURCE_MATCH qDebug() << " TRY" << sub_node << name(sub_node) << offset; #endif offset += 4; //jump past name const short flags = (tree[offset+0] << 8) + (tree[offset+1] << 0); offset += 2; if(!splitter.hasNext()) { if(!(flags & Directory)) { const short country = (tree[offset+0] << 8) + (tree[offset+1] << 0); offset += 2; const short language = (tree[offset+0] << 8) + (tree[offset+1] << 0); offset += 2; #ifdef DEBUG_RESOURCE_MATCH qDebug() << " " << "LOCALE" << country << language; #endif if(country == locale.country() && language == locale.language()) { #ifdef DEBUG_RESOURCE_MATCH qDebug() << "!!!!" << "FINISHED" << __LINE__ << sub_node; #endif return sub_node; } else if((country == QLocale::AnyCountry && language == locale.language()) || (country == QLocale::AnyCountry && language == QLocale::C && node == -1)) { node = sub_node; } continue; } else { #ifdef DEBUG_RESOURCE_MATCH qDebug() << "!!!!" << "FINISHED" << __LINE__ << sub_node; #endif return sub_node; } } if(!(flags & Directory)) return -1; child_count = (tree[offset+0] << 24) + (tree[offset+1] << 16) + (tree[offset+2] << 8) + (tree[offset+3] << 0); offset += 4; child = (tree[offset+0] << 24) + (tree[offset+1] << 16) + (tree[offset+2] << 8) + (tree[offset+3] << 0); break; } } } if(!found) break; } #ifdef DEBUG_RESOURCE_MATCH qDebug() << "!!!!" << "FINISHED" << __LINE__ << node; #endif return node; }
uidEvent_t Event::uid() const { std::ostringstream ss; ss << name() << "-" << element()->uid(); return ss.str(); }
void cNPC::postload( unsigned int version ) { if ( stablemasterSerial_ != INVALID_SERIAL ) { pos_.setInternalMap(); } cBaseChar::postload( version ); SERIAL owner = ( SERIAL ) owner_; owner_ = 0; setOwner( dynamic_cast<P_PLAYER>( World::instance()->findChar( owner ) ) ); if ( wanderType() == enFollowTarget ) setWanderType( enFreely ); if ( stablemasterSerial() == INVALID_SERIAL && !pos_.isInternalMap() ) { MapObjects::instance()->add( this ); } // If our stablemaster is missing, remove us if ( stablemasterSerial_ != INVALID_SERIAL ) { cUObject *stablemaster = World::instance()->findObject( stablemasterSerial_ ); if ( !stablemaster ) { Console::instance()->log( LOG_WARNING, tr( "Removing NPC %1 (0x%2) because of invalid stablemaster 0x%3.\n" ).arg( name() ).arg( serial_, 0, 16 ).arg( stablemasterSerial_, 0, 16 ) ); stablemasterSerial_ = INVALID_SERIAL; remove(); } } }
int facebook_json_parser::parse_messages(std::string *pData, std::vector<facebook_message>* messages, std::map< std::string, facebook_notification* >* notifications) { // remove old received messages from map for (std::map<std::string, int>::iterator it = proto->facy.messages_ignore.begin(); it != proto->facy.messages_ignore.end();) { if (it->second > FACEBOOK_IGNORE_COUNTER_LIMIT) { it = proto->facy.messages_ignore.erase(it); } else { it->second++; // increase counter on each request ++it; } } JSONNode root = JSONNode::parse(pData->substr(9).c_str()); if (!root) return EXIT_FAILURE; const JSONNode &ms = root["ms"]; if (!ms) return EXIT_FAILURE; for (auto it = ms.begin(); it != ms.end(); ++it) { const JSONNode &type = (*it)["type"]; if (!type) continue; std::string t = type.as_string(); if (t == "delta") { // new messaging stuff const JSONNode &delta_ = (*it)["delta"]; if (!delta_) continue; const JSONNode &cls_ = delta_["class"]; std::string cls = cls_.as_string(); if (cls == "NewMessage") { const JSONNode &meta_ = delta_["messageMetadata"]; if (!meta_) { proto->debugLogA("json::parse_messages - No messageMetadata element"); continue; } const JSONNode &sender_fbid = meta_["actorFbId"]; // who send the message const JSONNode &body = delta_["body"]; // message text, could be empty if there is only attachment (or sticker) const JSONNode &mid = meta_["messageId"]; const JSONNode ×tamp = meta_["timestamp"]; if (!sender_fbid || !mid || !timestamp) continue; std::string id = sender_fbid.as_string(); std::string message_id = mid.as_string(); std::string message_text = body.as_string(); const JSONNode &other_user_id_ = meta_["threadKey"]["otherUserFbId"]; // for whom the message is (only for single conversations) const JSONNode &thread_fbid_ = meta_["threadKey"]["threadFbId"]; // thread of the message (only for multi chat conversations) std::string other_user_id = other_user_id_ ? other_user_id_.as_string() : ""; std::string thread_id = !other_user_id_ && thread_fbid_ ? "id." + thread_fbid_.as_string() : ""; // NOTE: we must add "id." prefix as this is threadFbId and we want threadId (but only for multi chats) // Process attachements and stickers parseAttachments(proto, &message_text, delta_, other_user_id, false); // Ignore duplicits or messages sent from miranda if (ignore_duplicits(proto, message_id, message_text)) continue; message_text = utils::text::trim(message_text, true); facebook_message message; message.isChat = other_user_id.empty(); message.isIncoming = (id != proto->facy.self_.user_id); message.isUnread = message.isIncoming; message.message_text = message_text; message.time = utils::time::from_string(timestamp.as_string()); message.user_id = message.isChat ? id : other_user_id; message.message_id = message_id; message.thread_id = thread_id; messages->push_back(message); } else if (cls == "ReadReceipt") { // user read message // when read const JSONNode &time_ = delta_["actionTimestampMs"]; if (!time_) continue; time_t timestamp = utils::time::from_string(time_.as_string()); // for multi chats (not available for single) const JSONNode &actor_ = delta_["actorFbId"]; // who read the message const JSONNode &thread_ = delta_["threadKey"]["threadFbId"]; // chat thread // for single chats (not available for multi) const JSONNode &reader_ = delta_["threadKey"]["otherUserFbId"]; // who read the message if (actor_ && thread_) { // multi chat // ignore if disabled if (!proto->m_enableChat) continue; std::string readerId = actor_.as_string(); std::string tid = "id." + thread_.as_string(); // NOTE: threadFbId means just numeric id of thread, without "id." prefix. We add it here to have it consistent with other methods (where threadId is used) MCONTACT hContact = proto->ChatIDToHContact(tid); proto->facy.insert_reader(hContact, timestamp, readerId); } else if (reader_) { // single chat std::string userId = reader_.as_string(); MCONTACT hContact = proto->ContactIDToHContact(userId); proto->facy.insert_reader(hContact, timestamp); } } else if (cls == "NoOp") { // contains numNoOps=1 (or probably other number) in delta element, but I don't know what is it for continue; } else { // DeliveryReceipt, MarkRead, ThreadDelete proto->debugLogA("json::parse_messages - Unknown class '%s'", cls.c_str()); } } else if (t == "messaging") { // various messaging stuff (received and sent messages, getting seen info) const JSONNode &ev_ = (*it)["event"]; if (!ev_) continue; std::string ev = ev_.as_string(); if (ev == "deliver") { // inbox message (multiuser or direct) const JSONNode &msg = (*it)["message"]; const JSONNode &sender_fbid = msg["sender_fbid"]; const JSONNode &sender_name = msg["sender_name"]; const JSONNode &body = msg["body"]; // looks like there is either "tid" or "other_user_fbid" (or both) const JSONNode &tid = msg["tid"]; const JSONNode &mid = msg["mid"]; const JSONNode ×tamp = msg["timestamp"]; if (!sender_fbid || !sender_name || !body || !mid || !timestamp) continue; const JSONNode &is_filtered = (*it)["is_filtered_content"]; // TODO: is it still here? perhaps it is replaced with msg["is_spoof_warning"] or something else? //const JSONNode &is_spoof_warning = msg["is_spoof_warning"]; //const JSONNode &is_silent = msg["is_silent"]; //const JSONNode &is_unread = msg["is_unread"]; std::string id = sender_fbid.as_string(); std::string message_id = mid.as_string(); std::string message_text = body.as_string(); std::string thread_id = tid.as_string(); std::string other_user_id = msg["other_user_fbid"].as_string(); // Process attachements and stickers parseAttachments(proto, &message_text, msg, other_user_id, true); // Ignore duplicits or messages sent from miranda if (!body || ignore_duplicits(proto, message_id, message_text)) continue; if (is_filtered.as_bool() && message_text.empty()) message_text = Translate("This message is no longer available, because it was marked as abusive or spam."); message_text = utils::text::trim(message_text, true); facebook_message message; message.isChat = other_user_id.empty(); message.isIncoming = (id != proto->facy.self_.user_id); message.isUnread = message.isIncoming; message.message_text = message_text; message.time = utils::time::from_string(timestamp.as_string()); message.user_id = (!message.isChat && !message.isIncoming) ? other_user_id : id; message.message_id = message_id; message.thread_id = thread_id; if (message.user_id.empty()) { proto->debugLogA(" !!! JSON: deliver message event with empty user_id (thread_id %s)\n%s", message.thread_id.empty() ? "empty too" : "exists", (*it).as_string().c_str()); if (!message.thread_id.empty()) { message.user_id = proto->ThreadIDToContactID(message.thread_id); // TODO: Check if we have contact with this user_id in friendlist and otherwise do something different? } } messages->push_back(message); } } else if (t == "notification_json") { // event notification const JSONNode &nodes = (*it)["nodes"]; // Create notifications chatroom (if it doesn't exists), because we will be writing to it new notifications here proto->PrepareNotificationsChatRoom(); for (auto itNodes = nodes.begin(); itNodes != nodes.end(); ++itNodes) { const JSONNode &text_ = (*itNodes)["unaggregatedTitle"]; // notifications one by one, not grouped if (!text_) continue; const JSONNode &text = text_["text"]; const JSONNode &url = (*itNodes)["url"]; const JSONNode &alert_id = (*itNodes)["alert_id"]; const JSONNode &icon_ = (*itNodes)["icon"]["uri"]; const JSONNode &time_ = (*itNodes)["timestamp"]; if (!time_) continue; const JSONNode &time = time_["time"]; if (!time || !text || !url || !alert_id) continue; time_t timestamp = utils::time::from_string(time.as_string()); if (timestamp > proto->facy.last_notification_time_) { // Only new notifications proto->facy.last_notification_time_ = timestamp; facebook_notification* notification = new facebook_notification(); notification->text = utils::text::slashu_to_utf8(text.as_string()); notification->link = url.as_string(); notification->id = alert_id.as_string(); notification->time = timestamp; notification->setIcon(icon_.as_string()); // Fix notification ID std::string::size_type pos = notification->id.find(":"); if (pos != std::string::npos) notification->id = notification->id.substr(pos + 1); // Write notification to chatroom proto->UpdateNotificationsChatRoom(notification); // If it's unseen, remember it, otherwise forget it (here it will always be unseen) if (notifications->find(notification->id) == notifications->end() && !notification->seen) notifications->insert(std::make_pair(notification->id, notification)); else delete notification; } } } else if (t == "m_notification") { const JSONNode &data = (*it)["data"]; if (!data) continue; const JSONNode &appId_ = data["app_id"]; const JSONNode &type_ = data["type"]; if (appId_.as_string() == "2356318349" || type_.as_string() == "friend_confirmed") { // Friendship notifications const JSONNode &body_ = data["body"]; const JSONNode &html_ = body_["__html"]; const JSONNode &href_ = data["href"]; const JSONNode &unread_ = data["unread"]; const JSONNode &alertId_ = data["alert_id"]; if (!html_ || !href_ || !unread_ || unread_.as_int() == 0) continue; std::string text = utils::text::remove_html(utils::text::slashu_to_utf8(html_.as_string())); std::string url = href_.as_string(); std::string alert_id = alertId_.as_string(); // Notify it, if user wants to be notified if (proto->getByte(FACEBOOK_KEY_EVENT_FRIENDSHIP_ENABLE, DEFAULT_EVENT_FRIENDSHIP_ENABLE)) { proto->NotifyEvent(proto->m_tszUserName, ptrT(mir_utf8decodeT(text.c_str())), NULL, FACEBOOK_EVENT_FRIENDSHIP, &url, alert_id.empty() ? NULL : &alert_id); } } } else if (t == "jewel_requests_add") { // New friendship request, load them all with real names (because there is only user_id in "from" field) proto->ForkThread(&FacebookProto::ProcessFriendRequests, NULL); } else if (t == "typ") { // chat typing notification const JSONNode &from = (*it)["from"]; if (!from) continue; facebook_user fbu; fbu.user_id = from.as_string(); fbu.type = CONTACT_FRIEND; // only friends are able to send typing notifications MCONTACT hContact = proto->AddToContactList(&fbu); const JSONNode &st = (*it)["st"]; if (st.as_int() == 1) proto->StartTyping(hContact); else proto->StopTyping(hContact); } else if (t == "ttyp") { // multi chat typing notification if (!proto->m_enableChat) continue; const JSONNode &from_ = (*it)["from"]; const JSONNode &thread_ = (*it)["thread"]; const JSONNode &st_ = (*it)["st"]; if (!from_ || !thread_ || !st_) continue; std::string tid = thread_.as_string(); std::string from_id = from_.as_string(); auto itRoom = proto->facy.chat_rooms.find(thread_.as_string()); if (itRoom != proto->facy.chat_rooms.end()) { facebook_chatroom *chatroom = itRoom->second; std::map<std::string, std::string> participants = chatroom->participants; auto participant = participants.find(from_id); if (participant == participants.end()) { // TODO: load name of this participant std::string name = from_id; proto->AddChatContact(tid.c_str(), from_id.c_str(), name.c_str()); } participant = participants.find(from_id); if (participant != participants.end()) { MCONTACT hChatContact = proto->ChatIDToHContact(tid); ptrT name(mir_utf8decodeT(participant->second.c_str())); if (st_.as_int() == 1) { StatusTextData st = { 0 }; st.cbSize = sizeof(st); mir_sntprintf(st.tszText, TranslateT("%s is typing a message..."), name); CallService(MS_MSG_SETSTATUSTEXT, (WPARAM)hChatContact, (LPARAM)&st); } else CallService(MS_MSG_SETSTATUSTEXT, (WPARAM)hChatContact); // TODO: support proper MS_PROTO_CONTACTISTYPING service for chatrooms (when it will be implemented) } } } else if (t == "privacy_changed") { // settings changed const JSONNode &event_type = (*it)["event"]; const JSONNode &event_data = (*it)["data"]; if (!event_type || !event_data) continue; std::string et = event_type.as_string(); if (et == "visibility_update") { // change of chat status const JSONNode &visibility = event_data["visibility"]; bool isVisible = visibility && visibility.as_bool(); proto->debugLogA(" Requested chat switch to %s", isVisible ? "Online" : "Offline"); // If actual status is not what server says, change it (handle also local away status, which means online) if (isVisible != (proto->m_iStatus != ID_STATUS_INVISIBLE)) proto->SetStatus(isVisible ? ID_STATUS_ONLINE : ID_STATUS_INVISIBLE); } } else if (t == "chatproxy-presence") { const JSONNode &buddyList = (*it)["buddyList"]; if (!buddyList) continue; for (auto itNodes = buddyList.begin(); itNodes != buddyList.end(); ++itNodes) { std::string id = (*itNodes).name(); MCONTACT hContact = proto->ContactIDToHContact(id); if (!hContact) { // FIXME: What to do, when we don't have this contact? What does it mean? // fbu->type = CONTACT_FRIEND; // add this contact as a friend? // fbu->handle = AddToContactList(fbu); continue; } // TODO: Check for friends existence/inexistence? Here we should get all friends (but we're already doing friendslist request, so we should have fresh data already) const JSONNode &p_ = (*itNodes)["p"]; // possible values: 0, 2 (something more?) (might not be present) const JSONNode &lat_ = (*itNodes)["lat"]; // timestamp of last activity (could be 0) (is always present) const JSONNode &vc_ = (*itNodes)["vc"]; // possible values: 0, 8, 10 (something more?) (might not be present) int status = ID_STATUS_DND; // DND to easily spot some problem, as we expect it will always be p==0 or p==2 below // Probably means presence: 0 = away, 2 = online, when not present then that probably means don't change that status if (p_) { int p = p_.as_int(); if (p == 0) status = ID_STATUS_AWAY; else if (p == 2) status = ID_STATUS_ONLINE; if (proto->getWord(hContact, "Status", 0) != status) proto->setWord(hContact, "Status", status); } // Last active time if (lat_) { time_t last_active = utils::time::from_string(lat_.as_string()); if (proto->getDword(hContact, "LastActiveTS", 0) != last_active) { if (last_active > 0) proto->setDword(hContact, "LastActiveTS", last_active); else proto->delSetting(hContact, "LastActiveTS"); } } // Probably means client: guess 0 = web, 8 = messenger, 10 = something else? if (vc_) { int vc = vc_.as_int(); TCHAR *client; if (vc == 0) { client = _T(FACEBOOK_CLIENT_WEB); } else if (vc == 8) { client = _T(FACEBOOK_CLIENT_MESSENGER); // I was online on Miranda, but when looked at myself at messenger.com I had icon of Messenger. } else if (vc == 10) { client = _T(FACEBOOK_CLIENT_MOBILE); } else { client = _T(FACEBOOK_CLIENT_OTHER); } ptrT oldClient(proto->getTStringA(hContact, "MirVer")); if (!oldClient || mir_tstrcmp(oldClient, client)) proto->setTString(hContact, "MirVer", client); } } } else if (t == "buddylist_overlay") { // TODO: This is now supported also via /ajax/mercury/tabs_presence.php request (probably) // additional info about user status (status, used client) const JSONNode &overlay = (*it)["overlay"]; if (!overlay) continue; for (auto itNodes = overlay.begin(); itNodes != overlay.end(); ++itNodes) { std::string id = (*itNodes).name(); MCONTACT hContact = proto->ContactIDToHContact(id); if (!hContact) { // FIXME: What to do, when we don't have this contact? What does it mean? // fbu->type = CONTACT_FRIEND; // add this contact as a friend? // fbu->handle = AddToContactList(fbu); continue; } // TODO: Check for friends existence/inexistence? /* if (getByte(fbu->handle, FACEBOOK_KEY_CONTACT_TYPE, 0) != CONTACT_FRIEND) { setByte(fbu->handle, FACEBOOK_KEY_CONTACT_TYPE, CONTACT_FRIEND); // TODO: remove that popup and use "Contact added you" event? } // Wasn't contact removed from "server-list" someday? if (getDword(fbu->handle, FACEBOOK_KEY_DELETED, 0)) { delSetting(fbu->handle, FACEBOOK_KEY_DELETED); std::string url = FACEBOOK_URL_PROFILE + fbu->user_id; std::string contactname = getContactName(this, fbu->handle, !fbu->real_name.empty() ? fbu->real_name.c_str() : fbu->user_id.c_str()); ptrT szTitle(mir_utf8decodeT(contactname.c_str())); NotifyEvent(szTitle, TranslateT("Contact is back on server-list."), fbu->handle, FACEBOOK_EVENT_FRIENDSHIP, &url); } */ /* ptrT client(getTStringA(fbu->handle, "MirVer")); if (!client || mir_tstrcmp(client, fbu->getMirVer())) setTString(fbu->handle, "MirVer", fbu->getMirVer()); */ const JSONNode &a_ = (*itNodes)["a"]; // possible values: 0, 2 (something more?) const JSONNode &la_ = (*itNodes)["la"]; // timestamp of last activity (could be 0) const JSONNode &s_ = (*itNodes)["s"]; // possible values: push (something more?) const JSONNode &vc_ = (*itNodes)["vc"]; // possible values: 0, 8, 10 (something more?) // Friller account has also these: // const JSONNode &ol_ = (*itNodes)["ol"]; // possible values: -1 (when goes to offline), 0 (when goes back online) (something more?) // const JSONNode &p_ = (*itNodes)["p"]; // class with fbAppStatus, messengerStatus, otherStatus, status, webStatus int status = ID_STATUS_FREECHAT; // FREECHAT to easily spot some problem, as we expect it will always be p==0 or p==2 below if (a_) { int a = a_.as_int(); if (a == 0) status = ID_STATUS_OFFLINE; else if (a == 2) status = ID_STATUS_ONLINE; } else { status = ID_STATUS_OFFLINE; } if (proto->getWord(hContact, "Status", 0) != status) proto->setWord(hContact, "Status", status); if (la_ && status != ID_STATUS_ONLINE) { time_t last_active = utils::time::from_string(la_.as_string()); // we should set IdleTS only when contact is IDLE, or OFFLINE if (proto->getDword(hContact, "IdleTS", 0) != last_active) { if (/*(fbu->idle || status == ID_STATUS_OFFLINE) &&*/ last_active > 0) proto->setDword(hContact, "IdleTS", last_active); else proto->delSetting(hContact, "IdleTS"); } /*if (proto->getDword(hContact, "LastActiveTS", 0) != last_active) { if (last_active > 0) proto->setDword(hContact, "LastActiveTS", last_active); else proto->delSetting(hContact, "LastActiveTS"); }*/ } else { proto->delSetting(hContact, "IdleTS"); } if (s_) { // what to do with this? } // Probably means client: guess 0 = web, 8 = messenger, 10 = something else? if (vc_) { TCHAR *client = _T(FACEBOOK_CLIENT_WEB); /*if (vc == 0) { // means active some time ago? (on messenger or also on web) client = _T(FACEBOOK_CLIENT_WEB); } else if (vc == 8) { client = _T(FACEBOOK_CLIENT_MESSENGER); // I was online on Miranda, but when looked at myself at messenger.com I had icon of Messenger. } else if (vc == 10) { // means actually active on messenger client = _T(FACEBOOK_CLIENT_MOBILE); } else { client = _T(FACEBOOK_CLIENT_OTHER); }*/ ptrT oldClient(proto->getTStringA(hContact, "MirVer")); if (!oldClient || mir_tstrcmp(oldClient, client)) proto->setTString(hContact, "MirVer", client); } } } else if (t == "ticker_update:home") { if (!proto->getByte(FACEBOOK_KEY_EVENT_TICKER_ENABLE, DEFAULT_EVENT_TICKER_ENABLE)) continue; const JSONNode &actor_ = (*it)["actor"]; const JSONNode &story_ = (*it)["story_xhp"]; std::string text = story_.as_string(); text = utils::text::html_entities_decode(utils::text::slashu_to_utf8(text)); std::string url = utils::text::source_get_value(&text, 3, "\"tickerStoryLink\"", "href=\"", "\""); std::string story_type = utils::text::source_get_value2(&text, "\"type\":\"", "\""); std::string story_class = utils::text::source_get_value2(&text, "\"entstory_class\":\"", "\""); text = utils::text::trim(utils::text::remove_html(text)); std::string userId = actor_.as_string(); MCONTACT hContact = proto->ContactIDToHContact(userId); proto->debugLogA("+++ Got ticker type='%s' class='%s'", story_type.c_str(), story_class.c_str()); if (!text.empty()) proto->NotifyEvent(proto->m_tszUserName, ptrT(mir_utf8decodeT(text.c_str())), hContact, FACEBOOK_EVENT_TICKER, &url); } else if (t == "mercury") { // rename multi user chat, video call, ... const JSONNode &actions_ = (*it)["actions"]; if (!actions_) continue; for (unsigned int i = 0; i < actions_.size(); i++) { const JSONNode &action_ = actions_[i]; const JSONNode &thread_id_ = action_["thread_id"]; const JSONNode &log_body_ = action_["log_message_body"]; const JSONNode &log_data_ = action_["log_message_data"]; const JSONNode &log_type_ = action_["log_message_type"]; if (!log_data_ || !log_body_ || !thread_id_ || !log_type_) continue; std::string thread_id = thread_id_.as_string(); std::string logType = log_type_.as_string(); std::string message_text = log_body_.as_string(); if (logType == "log:video-call") { std::string id = action_["other_user_fbid"].as_string(); std::string message_id = action_["message_id"].as_string(); facebook_message message; message.isChat = false; message.isUnread = true; message.isIncoming = (id != proto->facy.self_.user_id); message.message_text = message_text; message.time = utils::time::from_string(action_["timestamp"].as_string()); message.user_id = id; message.message_id = message_id; message.thread_id = thread_id; message.type = CALL; messages->push_back(message); } else { // TODO: check for other types, now we expect this is rename chat if (!proto->m_enableChat) continue; std::string name = log_data_["name"].as_string(); // proto->RenameChat(thread_id.c_str(), name.c_str()); // this don't work, why? proto->setStringUtf(proto->ChatIDToHContact(thread_id), FACEBOOK_KEY_NICK, name.c_str()); proto->UpdateChat(thread_id.c_str(), NULL, NULL, message_text.c_str()); } } } else if (t == "notifications_read" || t == "notifications_seen") { ScopedLock s(proto->facy.notifications_lock_); const JSONNode &alerts = (*it)["alert_ids"]; for (auto itAlerts = alerts.begin(); itAlerts != alerts.end(); ++itAlerts) { std::string id = (*itAlerts).as_string(); auto itAlert = notifications->find(id); if (itAlert != notifications->end()) { if (itAlert->second->hWndPopup != NULL) PUDeletePopup(itAlert->second->hWndPopup); // close popup delete itAlert->second; notifications->erase(itAlert); } } } else continue; } return EXIT_SUCCESS; }
void UmlOperation::html(Q3CString, unsigned int, unsigned int) { define(); fw.write("<table><tr><td><div class=\"element\">Operation <b>"); writeq(name()); fw.write("</b></div></td></tr></table>"); Q3CString s = description(); if (! s.isEmpty()) { fw.write("<p>"); if (! javaDecl().isEmpty()) gen_java_decl(s, TRUE); else if (! phpDecl().isEmpty()) gen_php_decl(s, TRUE); else if (! pythonDecl().isEmpty()) gen_python_decl(s, TRUE); else gen_cpp_decl(s, TRUE); fw.write("<br /></p>"); } fw.write("<p>Declaration :</p><ul>"); fw.write("<li>Uml : "); gen_uml_decl(); fw.write("</li>"); s = cppDecl(); if (!s.isEmpty()) { fw.write("<li>C++ : "); gen_cpp_decl(s, FALSE); fw.write("</li>"); } s = javaDecl(); if (!s.isEmpty()) { fw.write("<li>Java : "); gen_java_decl(s, FALSE); fw.write("</li>"); } s = phpDecl(); if (!s.isEmpty()) { fw.write("<li>Php : "); gen_php_decl(s, FALSE); fw.write("</li>"); } s = pythonDecl(); if (!s.isEmpty()) { fw.write("<li>Python : "); gen_python_decl(s, FALSE); fw.write("</li>"); } fw.write("</ul>"); annotation_constraint(); write_properties(); unload(FALSE, FALSE); }
KoColorSpace *YCbCrF32ColorSpace::clone() const { return new YCbCrF32ColorSpace(name(), profile()->clone()); }
echo_plugin::~echo_plugin() { BOOST_LOG_SEV(log_, logging::trace) << name() << " destroyed"; boost::log::core::get()->flush(); /// FIXME: At reworking logging }
void link_check::do_url( const string & url, const string & library_name, const path & source_path, bool no_link_errors, bool allow_external_content ) // precondition: source_path.is_complete() { if(!no_link_errors && url.empty()) { ++m_invalid_errors; error( library_name, source_path, string(name()) + " empty URL." ); return; } // Decode ampersand encoded characters. string decoded_url = is_css(source_path) ? url : decode_ampersands(url); if(decoded_url.empty()) { if(!no_link_errors) { ++m_invalid_errors; error( library_name, source_path, string(name()) + " invalid URL (invalid ampersand encodings): " + url ); } return; } boost::smatch m; if(!boost::regex_match(decoded_url, m, url_decompose_regex)) { if(!no_link_errors) { ++m_invalid_errors; error( library_name, source_path, string(name()) + " invalid URL: " + decoded_url ); } return; } bool scheme_matched = m[2].matched, authority_matched = m[4].matched, //query_matched = m[7].matched, fragment_matched = m[9].matched; std::string scheme(m[2]), authority(m[4]), url_path(m[5]), //query(m[7]), fragment(m[9]); // Check for external content if(!allow_external_content && (authority_matched || scheme_matched)) { if(!no_link_errors) { ++m_invalid_errors; error( library_name, source_path, string(name()) + " external content: " + decoded_url ); } } // Protocol checks if(scheme_matched) { if(scheme == "http" || scheme == "https") { // All http links should have a hostname. Generally if they don't // it's by mistake. If they shouldn't, then a protocol isn't // required. if(!authority_matched) { if(!no_link_errors) { ++m_invalid_errors; error( library_name, source_path, string(name()) + " no hostname: " + decoded_url ); } } return; } else if(scheme == "file") { if(!no_link_errors) { ++m_invalid_errors; error( library_name, source_path, string(name()) + " invalid URL (hardwired file): " + decoded_url ); } } else if(scheme == "mailto" || scheme == "ftp" || scheme == "news" || scheme == "javascript") { if ( !no_link_errors && is_css(source_path) ) { ++m_invalid_errors; error( library_name, source_path, string(name()) + " invalid protocol for css: " + decoded_url ); } } else { if(!no_link_errors) { ++m_invalid_errors; error( library_name, source_path, string(name()) + " unknown protocol: " + decoded_url ); } } return; } // Hostname without protocol. if(authority_matched) { if(!no_link_errors) { ++m_invalid_errors; error( library_name, source_path, string(name()) + " invalid URL (hostname without protocol): " + decoded_url ); } } // Check the fragment identifier if ( fragment_matched ) { if ( is_css(source_path) ) { if ( !no_link_errors ) { ++m_invalid_errors; error( library_name, source_path, string(name()) + " fragment link in CSS: " + decoded_url ); } } else { if ( !no_link_errors && fragment.find( '#' ) != string::npos ) { ++m_bookmark_errors; error( library_name, source_path, string(name()) + " invalid bookmark: " + decoded_url ); } } // No more to do if it's just a fragment identifier if(url_path.empty()) return; } // Detect characters banned by RFC2396: if ( !no_link_errors && decoded_url.find_first_of( " <>\"{}|\\^[]'" ) != string::npos ) { ++m_invalid_errors; error( library_name, source_path, string(name()) + " invalid character in URL: " + decoded_url ); } // Check that we actually have a path. if(url_path.empty()) { if(!no_link_errors) { ++m_invalid_errors; error( library_name, source_path, string(name()) + " invalid URL (empty path in relative url): " + decoded_url ); } } // Decode percent and ampersand encoded characters. string decoded_path = decode_percents(url_path); if(decoded_path.empty()) { if(!no_link_errors) { ++m_invalid_errors; error( library_name, source_path, string(name()) + " invalid URL (invalid character encodings): " + decoded_url ); } return; } // strip url of references to current dir if ( decoded_path[0]=='.' && decoded_path[1]=='/' ) decoded_path.erase( 0, 2 ); // url is relative source_path.branch() // convert to target_path, which is_complete() path target_path; try { target_path = source_path.branch_path() /= path( decoded_path, fs::no_check ); } catch ( const fs::filesystem_error & ) { if(!no_link_errors) { ++m_invalid_errors; error( library_name, source_path, string(name()) + " invalid URL (error resolving path): " + decoded_url ); } return; } // create a m_paths entry if necessary std::pair< const string, int > entry( relative_to( target_path, fs::initial_path() ), 0 ); m_path_map::iterator itr( m_paths.find( entry.first ) ); if ( itr == m_paths.end() ) { if ( fs::exists( target_path ) ) entry.second = m_present; itr = m_paths.insert( entry ).first; } // itr now points to the m_paths entry itr->second |= m_linked_to; // if target isn't present, the link is broken if ( !no_link_errors && (itr->second & m_present) == 0 ) { ++m_broken_errors; error( library_name, source_path, string(name()) + " broken link: " + decoded_url ); } }
void AbstractParam::saveValue(QSettings& settings) { if ((type() != QVariant::Invalid) && !name().isEmpty()) { settings.setValue(name(), value()); } }
void TcxReader::readTrackpoint(CTrack *track, int lap) { Q_ASSERT(isStartElement() && name() == "Trackpoint"); CTrack::pt_t *pt = new CTrack::pt_t(); pt->lat = pold.lat; pt->lon = pold.lon; pt->ele = pold.ele; pt->distance = pold.distance; pt->heartReateBpm = pold.heartReateBpm; while (!atEnd()) { readNext(); if (isEndElement()) break; if (isStartElement()) { if (name() == "Time") { QDateTime time(QDateTime::fromString(readElementText(), Qt::ISODate)); time.setTimeSpec(Qt::UTC); pt->timestamp = time.toTime_t(); } else if (name() == "AltitudeMeters") { pt->ele = readElementText().toDouble(); pold.ele = pt->ele; } else if (name() == "DistanceMeters") { pt->distance = readElementText().toDouble(); pold.distance = pt->distance; } else if (name() == "Position") { readPosition(pt); pold.lat = pt->lat; pold.lon = pt->lon; firstPositionFound = true; } else if (name() == "HeartRateBpm") { readHeartRateBpm(pt); pold.heartReateBpm = pt->heartReateBpm; } else if (name() == "Cadence") { //readCadenceRpm(pt); pt->cadenceRpm = readElementText().toInt(); pold.cadenceRpm = pt->cadenceRpm; } else readUnknownElement(); } } pt->_lat=pt->lat; pt->_lon=pt->lon; pt->_ele=pt->ele; if (firstPositionFound) { *track << *pt; } }
static void define(backend::source_generator &src) { define( src, name() ); }
bool Script::executeCommand(int index, MasterTimer* timer, QList<Universe *> universes) { if (index < 0 || index >= m_lines.size()) { qWarning() << "Invalid command index:" << index; return false; } QList <QStringList> tokens = m_lines[index]; if (tokens.isEmpty() == true) return true; // Empty line bool continueLoop = true; QString error; if (tokens[0].size() < 2) { error = QString("Syntax error"); } else if (tokens[0][0] == Script::startFunctionCmd) { error = handleStartFunction(tokens, timer); } else if (tokens[0][0] == Script::stopFunctionCmd) { error = handleStopFunction(tokens); } else if (tokens[0][0] == Script::waitCmd) { // Waiting should break out of the execution loop to prevent skipping // straight to the next command. If there is no error in wait parsing, // we must wait at least one cycle. error = handleWait(tokens); if (error.isEmpty() == true) continueLoop = false; } else if (tokens[0][0] == Script::waitKeyCmd) { // Waiting for a key should break out of the execution loop to prevent // skipping straight to the next command. If there is no error in waitkey // parsing,we must wait at least one cycle. error = handleWaitKey(tokens); if (error.isEmpty() == true) continueLoop = false; } else if (tokens[0][0] == Script::setFixtureCmd) { error = handleSetFixture(tokens, universes); } else if (tokens[0][0] == Script::labelCmd) { error = handleLabel(tokens); } else if (tokens[0][0] == Script::jumpCmd) { // Jumping can cause an infinite non-waiting loop, causing starvation // among other functions. Therefore, the script must relinquish its // time slot after each jump. If there is no error in jumping, the jump // must have happened. error = handleJump(tokens); if (error.isEmpty() == true) continueLoop = false; } else { error = QString("Unknown command: %1").arg(tokens[0][0]); } if (error.isEmpty() == false) qWarning() << QString("Script:%1, line:%2, error:%3").arg(name()).arg(index).arg(error); return continueLoop; }
//---------------------------------------------------------------------------- void medOpMML3ParameterViewTest::CompareImages(mafString test_name) //---------------------------------------------------------------------------- { char *file = __FILE__; std::string name(file); int slashIndex = name.find_last_of('\\'); name = name.substr(slashIndex+1); int pointIndex = name.find_last_of('.'); name = name.substr(0, pointIndex); mafString controlOriginFile=MED_DATA_ROOT; //controlOriginFile << "/Test_OpMML3ParameterView/"; controlOriginFile << "/"; controlOriginFile << name.c_str(); controlOriginFile << "_"; controlOriginFile << "image"; controlOriginFile << test_name.GetCStr(); controlOriginFile << ".jpg"; fstream controlStream; controlStream.open(controlOriginFile.GetCStr()); // visualization control m_RenderWindow->OffScreenRenderingOn(); vtkWindowToImageFilter *w2i; vtkNEW(w2i); w2i->SetInput(m_RenderWindow); //w2i->SetMagnification(magnification); w2i->Update(); m_RenderWindow->OffScreenRenderingOff(); //write comparing image vtkJPEGWriter *w; vtkNEW(w); w->SetInput(w2i->GetOutput()); mafString imageFile=MED_DATA_ROOT; if(!controlStream) { imageFile << "/"; imageFile << name.c_str(); imageFile << "_"; imageFile << "image"; } else { imageFile << "/"; imageFile << name.c_str(); imageFile << "_"; imageFile << "comp"; } imageFile << test_name.GetCStr(); imageFile << ".jpg"; w->SetFileName(imageFile.GetCStr()); w->Write(); if(!controlStream) { controlStream.close(); vtkDEL(w); vtkDEL(w2i); return; } controlStream.close(); //read original Image vtkJPEGReader *rO; vtkNEW(rO); mafString imageFileOrig=MED_DATA_ROOT; imageFileOrig << "/"; imageFileOrig << name.c_str(); imageFileOrig << "_"; imageFileOrig << "image"; imageFileOrig << test_name.GetCStr(); imageFileOrig << ".jpg"; rO->SetFileName(imageFileOrig.GetCStr()); rO->Update(); vtkImageData *imDataOrig = rO->GetOutput(); //read compared image vtkJPEGReader *rC; vtkNEW(rC); rC->SetFileName(imageFile.GetCStr()); rC->Update(); vtkImageData *imDataComp = rC->GetOutput(); vtkImageMathematics *imageMath = vtkImageMathematics::New(); imageMath->SetInput1(imDataOrig); imageMath->SetInput2(imDataComp); imageMath->SetOperationToSubtract(); imageMath->Update(); double srR[2] = {-1,1}; imageMath->GetOutput()->GetPointData()->GetScalars()->GetRange(srR); CPPUNIT_ASSERT(srR[0] == 0.0 && srR[1] == 0.0); // end visualization control vtkDEL(imageMath); vtkDEL(rC); vtkDEL(rO); vtkDEL(w); vtkDEL(w2i); }
// ----------------------------------------------------------------------------- // Parses a preprocessor directive at [tz]'s current token // ----------------------------------------------------------------------------- bool ParseTreeNode::parsePreprocessor(Tokenizer& tz) { // Log::debug(wxString::Format("Preprocessor %s", CHR(tz.current().text))); // #define if (tz.current() == "#define") parser_->define(tz.next().text); // #if(n)def else if (tz.current() == "#ifdef" || tz.current() == "#ifndef") { // Continue if condition succeeds bool test = true; if (tz.current() == "#ifndef") test = false; auto define = tz.next().text; if (parser_->defined(define) == test) return true; // Failed condition, skip section int skip = 0; while (true) { auto& token = tz.next(); if (token == "#endif") skip--; else if (token == "#ifdef") skip++; else if (token == "#ifndef") skip++; // TODO: #else if (skip < 0) break; } } // #include else if (tz.current() == "#include") { // Include entry at the given path if we have an archive dir set if (archive_dir_) { // Get entry to include auto inc_path = tz.next().text; auto archive = archive_dir_->archive(); auto inc_entry = archive->entryAtPath(archive_dir_->path() + inc_path); if (!inc_entry) // Try absolute path inc_entry = archive->entryAtPath(inc_path); // Log::debug(wxString::Format("Include %s", CHR(inc_path))); if (inc_entry) { // Save the current dir and set it to the included entry's dir auto orig_dir = archive_dir_; archive_dir_ = inc_entry->parentDir(); // Parse text in the entry Tokenizer inc_tz; inc_tz.openMem(inc_entry->data(), inc_entry->name()); bool ok = parse(inc_tz); // Reset dir and abort if parsing failed archive_dir_ = orig_dir; if (!ok) return false; } else logError(tz, fmt::format("Include entry {} not found", inc_path)); } else tz.adv(); // Skip include path } // #endif (ignore) else if (tz.current() == "#endif") return true; // TODO: #else // Unrecognised else logError(tz, fmt::format("Unrecognised preprocessor directive \"{}\"", tz.current().text)); return true; }
// ----------------------------------------------------------------------------- // Reads in a text definition of a language. See slade.pk3 for // formatting examples // ----------------------------------------------------------------------------- bool TextLanguage::readLanguageDefinition(MemChunk& mc, string_view source) { Tokenizer tz; // Open the given text data if (!tz.openMem(mc, source)) { Log::warning("Unable to open language definition {}", source); return false; } // Parse the definition text ParseTreeNode root; if (!root.parse(tz)) return false; // Get parsed data for (unsigned a = 0; a < root.nChildren(); a++) { auto node = root.childPTN(a); // Create language auto lang = new TextLanguage(node->name()); // Check for inheritance if (!node->inherit().empty()) { auto inherit = fromId(node->inherit()); if (inherit) inherit->copyTo(lang); else Log::warning("Warning: Language {} inherits from undefined language {}", node->name(), node->inherit()); } // Parse language info for (unsigned c = 0; c < node->nChildren(); c++) { auto child = node->childPTN(c); auto pn_lower = StrUtil::lower(child->name()); // Language name if (pn_lower == "name") lang->setName(child->stringValue()); // Comment begin else if (pn_lower == "comment_begin") { lang->setCommentBeginList(child->stringValues()); } // Comment end else if (pn_lower == "comment_end") { lang->setCommentEndList(child->stringValues()); } // Line comment else if (pn_lower == "comment_line") { lang->setLineCommentList(child->stringValues()); } // Preprocessor else if (pn_lower == "preprocessor") lang->setPreprocessor(child->stringValue()); // Case sensitive else if (pn_lower == "case_sensitive") lang->setCaseSensitive(child->boolValue()); // Doc comment else if (pn_lower == "comment_doc") lang->setDocComment(child->stringValue()); // Keyword lookup link else if (pn_lower == "keyword_link") lang->word_lists_[WordType::Keyword].lookup_url = child->stringValue(); // Constant lookup link else if (pn_lower == "constant_link") lang->word_lists_[WordType::Constant].lookup_url = child->stringValue(); // Function lookup link else if (pn_lower == "function_link") lang->f_lookup_url_ = child->stringValue(); // Jump blocks else if (pn_lower == "blocks") { for (unsigned v = 0; v < child->nValues(); v++) lang->jump_blocks_.push_back(child->stringValue(v)); } else if (pn_lower == "blocks_ignore") { for (unsigned v = 0; v < child->nValues(); v++) lang->jb_ignore_.push_back(child->stringValue(v)); } // Block begin else if (pn_lower == "block_begin") lang->block_begin_ = child->stringValue(); // Block end else if (pn_lower == "block_end") lang->block_end_ = child->stringValue(); // Preprocessor block begin else if (pn_lower == "pp_block_begin") { for (unsigned v = 0; v < child->nValues(); v++) lang->pp_block_begin_.push_back(child->stringValue(v)); } // Preprocessor block end else if (pn_lower == "pp_block_end") { for (unsigned v = 0; v < child->nValues(); v++) lang->pp_block_end_.push_back(child->stringValue(v)); } // Word block begin else if (pn_lower == "word_block_begin") { for (unsigned v = 0; v < child->nValues(); v++) lang->word_block_begin_.push_back(child->stringValue(v)); } // Word block end else if (pn_lower == "word_block_end") { for (unsigned v = 0; v < child->nValues(); v++) lang->word_block_end_.push_back(child->stringValue(v)); } // Keywords else if (pn_lower == "keywords") { // Go through values for (unsigned v = 0; v < child->nValues(); v++) { auto val = child->stringValue(v); // Check for '$override' if (StrUtil::equalCI(val, "$override")) { // Clear any inherited keywords lang->clearWordList(WordType::Keyword); } // Not a special symbol, add as keyword else lang->addWord(WordType::Keyword, val); } } // Constants else if (pn_lower == "constants") { // Go through values for (unsigned v = 0; v < child->nValues(); v++) { auto val = child->stringValue(v); // Check for '$override' if (StrUtil::equalCI(val, "$override")) { // Clear any inherited constants lang->clearWordList(WordType::Constant); } // Not a special symbol, add as constant else lang->addWord(WordType::Constant, val); } } // Types else if (pn_lower == "types") { // Go through values for (unsigned v = 0; v < child->nValues(); v++) { auto val = child->stringValue(v); // Check for '$override' if (StrUtil::equalCI(val, "$override")) { // Clear any inherited constants lang->clearWordList(WordType::Type); } // Not a special symbol, add as constant else lang->addWord(WordType::Type, val); } } // Properties else if (pn_lower == "properties") { // Go through values for (unsigned v = 0; v < child->nValues(); v++) { auto val = child->stringValue(v); // Check for '$override' if (StrUtil::equalCI(val, "$override")) { // Clear any inherited constants lang->clearWordList(WordType::Property); } // Not a special symbol, add as constant else lang->addWord(WordType::Property, val); } } // Functions else if (pn_lower == "functions") { bool lang_has_void = lang->isWord(Keyword, "void") || lang->isWord(Type, "void"); if (lang->id_ != "zscript") { // Go through children (functions) for (unsigned f = 0; f < child->nChildren(); f++) { auto child_func = child->childPTN(f); string params; // Simple definition if (child_func->nChildren() == 0) { if (child_func->stringValue(0).empty()) { if (lang_has_void) params = "void"; else params = ""; } else { params = child_func->stringValue(0); } // Add function lang->addFunction( child_func->name(), params, "", "", !StrUtil::contains(child_func->name(), '.'), child_func->type()); // Add args for (unsigned v = 1; v < child_func->nValues(); v++) lang->addFunction(child_func->name(), child_func->stringValue(v)); } // Full definition else { string name = child_func->name(); vector<string> args; string desc; string deprecated; for (unsigned p = 0; p < child_func->nChildren(); p++) { auto child_prop = child_func->childPTN(p); if (child_prop->name() == "args") { for (unsigned v = 0; v < child_prop->nValues(); v++) args.push_back(child_prop->stringValue(v)); } else if (child_prop->name() == "description") desc = child_prop->stringValue(); else if (child_prop->name() == "deprecated") deprecated = child_prop->stringValue(); } if (args.empty() && lang_has_void) args.emplace_back("void"); for (unsigned as = 0; as < args.size(); as++) lang->addFunction(name, args[as], desc, deprecated, as == 0, child_func->type()); } } } // ZScript function info which cannot be parsed from (g)zdoom.pk3 else { ZFuncExProp ex_prop; for (unsigned f = 0; f < child->nChildren(); f++) { auto child_func = child->childPTN(f); for (unsigned p = 0; p < child_func->nChildren(); ++p) { auto child_prop = child_func->childPTN(p); if (child_prop->name() == "description") ex_prop.description = child_prop->stringValue(); else if (child_prop->name() == "deprecated_f") ex_prop.deprecated_f = child_prop->stringValue(); } lang->zfuncs_ex_props_.emplace(child_func->name(), ex_prop); } } } } } return true; }
forlist (ptr in list) { if (strequal(key, name(caar(ptr))) is 0) { return car(ptr); } }