RelationType getRelationType() const { return static_cast<RelationType>(attribute() >> fmwk_orientation_digits); }
void Tilemap::add_tileset(std::map<unsigned, Surface>& tiles, xml_node node) { int first_gid = node.attribute("firstgid").as_int(); int id_cnt = 0; int tilewidth = node.attribute("tilewidth").as_int(); int tileheight = node.attribute("tileheight").as_int(); pugi::xml_node image = node.child("image"); const char *source = image.attribute("source").value(); int width = image.attribute("width").as_int(); int height = image.attribute("height").as_int(); #if 0 std::cerr << "Adding tileset:" << " Name: " << node.attribute("name").value() << " Gid: " << first_gid << " Tilewidth: " << tilewidth << " Tileheight: " << tileheight << " Source: " << source << " Width: " << width << " Height: " << height << std::endl; #endif if (!width || !height || !tilewidth || !tileheight) throw std::logic_error("Tilemap is malformed."); SurfaceCache cache; Blit::Surface surf = cache.from_image(Utils::join(dir, "/", source)); if (surf.rect().w != width || surf.rect().h != height) throw std::logic_error("Tilemap geometry does not correspond with image values."); std::map<std::basic_string<char>, std::basic_string<char> > global_attr = get_attributes(node.child("properties"), "property"); #if 0 std::cerr << "Dumping attrs:" << std::endl; for (auto& attr : global_attr) std::cerr << "Found global attr (" << attr.first << " => " << attr.second << ")." << std::endl; std::cerr << "Dumped attrs." << std::endl; #endif for (int y = 0; y < height; y += tileheight) { for (int x = 0; x < width; x += tilewidth, id_cnt++) { int id = first_gid + id_cnt; tiles[id] = surf.sub({{x, y}, tilewidth, tileheight}); std::copy(global_attr.begin(), global_attr.end(), std::inserter(tiles[id].attr(), tiles[id].attr().begin())); } } // Load all attributes for a tile into the surface. for (auto tile = node.child("tile"); tile; tile = tile.next_sibling("tile")) { int id = first_gid + tile.attribute("id").as_int(); std::map<std::basic_string<char>, std::basic_string<char> > attrs = get_attributes(tile.child("properties"), "property"); std::copy(global_attr.begin(), global_attr.end(), std::inserter(attrs, attrs.begin())); auto itr = attrs.find("sprite"); if (itr != attrs.end()) tiles[id] = cache.from_sprite(Utils::join(dir, "/", itr->second)); tiles[id].attr() = std::move(attrs); } }
bool OsmAnd::OnlineMapRasterTileProvider_P::obtainTile(const TileId tileId, const ZoomLevel zoom, std::shared_ptr<const MapTile>& outTile, const IQueryController* const queryController) { // Check provider can supply this zoom level if(zoom > owner->maxZoom || zoom < owner->minZoom) { outTile.reset(); return true; } // Check if requested tile is already being processed, and wait until that's done // to mark that as being processed. lockTile(tileId, zoom); // Check if requested tile is already in local storage. const auto tileLocalRelativePath = QString::number(zoom) + QDir::separator() + QString::number(tileId.x) + QDir::separator() + QString::number(tileId.y) + QLatin1String(".tile"); QFileInfo localFile; { QMutexLocker scopedLocker(&_localCachePathMutex); localFile.setFile(_localCachePath.filePath(tileLocalRelativePath)); } if(localFile.exists()) { // Since tile is in local storage, it's safe to unmark it as being processed unlockTile(tileId, zoom); // If local file is empty, it means that requested tile does not exist (has no data) if(localFile.size() == 0) { outTile.reset(); return true; } auto bitmap = new SkBitmap(); SkFILEStream fileStream(qPrintable(localFile.absoluteFilePath())); if(!SkImageDecoder::DecodeStream(&fileStream, bitmap, SkBitmap::Config::kNo_Config, SkImageDecoder::kDecodePixels_Mode)) { LogPrintf(LogSeverityLevel::Error, "Failed to decode tile file '%s'", qPrintable(localFile.absoluteFilePath())); delete bitmap; return false; } assert(bitmap->width() == bitmap->height()); assert(bitmap->width() == owner->providerTileSize); // Return tile auto tile = new MapBitmapTile(bitmap, owner->alphaChannelData); outTile.reset(tile); return true; } // Since tile is not in local cache (or cache is disabled, which is the same), // the tile must be downloaded from network: // If network access is disallowed, return failure if(!_networkAccessAllowed) { // Before returning, unlock tile unlockTile(tileId, zoom); return false; } // Check if there is free download slot. If all download slots are used, wait for one to be freed if(owner->maxConcurrentDownloads > 0) { QMutexLocker scopedLocker(&_currentDownloadsCounterMutex); while(_currentDownloadsCounter >= owner->maxConcurrentDownloads) _currentDownloadsCounterChanged.wait(&_currentDownloadsCounterMutex); _currentDownloadsCounter++; } // Perform synchronous download auto tileUrl = owner->urlPattern; tileUrl .replace(QLatin1String("${zoom}"), QString::number(zoom)) .replace(QLatin1String("${x}"), QString::number(tileId.x)) .replace(QLatin1String("${y}"), QString::number(tileId.y)); const auto networkReply = Network::Downloader::download(tileUrl); // Free download slot { QMutexLocker scopedLocker(&_currentDownloadsCounterMutex); _currentDownloadsCounter--; _currentDownloadsCounterChanged.wakeAll(); } // Ensure that all directories are created in path to local tile localFile.dir().mkpath(localFile.dir().absolutePath()); // If there was error, check what the error was auto networkError = networkReply->error(); if(networkError != QNetworkReply::NetworkError::NoError) { const auto httpStatus = networkReply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(); LogPrintf(LogSeverityLevel::Warning, "Failed to download tile from %s (HTTP status %d)", qPrintable(tileUrl), httpStatus); // 404 means that this tile does not exist, so create a zero file if(httpStatus == 404) { // Save to a file QFile tileFile(localFile.absoluteFilePath()); if(tileFile.open(QIODevice::WriteOnly | QIODevice::Truncate)) { tileFile.close(); // Unlock the tile unlockTile(tileId, zoom); networkReply->deleteLater(); return true; } else { LogPrintf(LogSeverityLevel::Error, "Failed to mark tile as non-existent with empty file '%s'", qPrintable(localFile.absoluteFilePath())); // Unlock the tile unlockTile(tileId, zoom); return false; } } // Unlock the tile unlockTile(tileId, zoom); return false; } // Save data to a file #if OSMAND_DEBUG LogPrintf(LogSeverityLevel::Info, "Downloaded tile from %s", qPrintable(tileUrl)); #endif const auto& data = networkReply->readAll(); // Save to a file QFile tileFile(localFile.absoluteFilePath()); if(tileFile.open(QIODevice::WriteOnly | QIODevice::Truncate)) { tileFile.write(data); tileFile.close(); #if OSMAND_DEBUG LogPrintf(LogSeverityLevel::Info, "Saved tile from %s to %s", qPrintable(tileUrl), qPrintable(localFile.absoluteFilePath())); #endif } else LogPrintf(LogSeverityLevel::Error, "Failed to save tile to '%s'", qPrintable(localFile.absoluteFilePath())); // Unlock tile, since local storage work is done unlockTile(tileId, zoom); // Decode in-memory auto bitmap = new SkBitmap(); if(!SkImageDecoder::DecodeMemory(data.data(), data.size(), bitmap, SkBitmap::Config::kNo_Config, SkImageDecoder::kDecodePixels_Mode)) { LogPrintf(LogSeverityLevel::Error, "Failed to decode tile file from '%s'", qPrintable(tileUrl)); delete bitmap; return false; } assert(bitmap->width() == bitmap->height()); assert(bitmap->width() == owner->providerTileSize); // Return tile auto tile = new MapBitmapTile(bitmap, owner->alphaChannelData); outTile.reset(tile); return true; }
void RunBufferVisitor(const std::string& buffer, V& visitor) { TIMER(L"profile2 visitor"); // The buffer doesn't necessarily start at the beginning of an item // (we just grabbed it from some arbitrary point in the middle), // so scan forwards until we find a sync marker. // (This is probably pretty inefficient.) u32 realStart = (u32)-1; // the start point decided by the scan algorithm for (u32 start = 0; start + 1 + sizeof(CProfiler2::RESYNC_MAGIC) <= buffer.length(); ++start) { if (buffer[start] == CProfiler2::ITEM_SYNC && memcmp(buffer.c_str() + start + 1, &CProfiler2::RESYNC_MAGIC, sizeof(CProfiler2::RESYNC_MAGIC)) == 0) { realStart = start; break; } } ENSURE(realStart != (u32)-1); // we should have found a sync point somewhere in the buffer u32 pos = realStart; // the position as we step through the buffer double lastTime = -1; // set to non-negative by EVENT_SYNC; we ignore all items before that // since we can't compute their absolute times while (pos < buffer.length()) { u8 type = buffer[pos]; ++pos; switch (type) { case CProfiler2::ITEM_NOP: { // ignore break; } case CProfiler2::ITEM_SYNC: { u8 magic[sizeof(CProfiler2::RESYNC_MAGIC)]; double t; memcpy(magic, buffer.c_str()+pos, ARRAY_SIZE(magic)); ENSURE(memcmp(magic, &CProfiler2::RESYNC_MAGIC, sizeof(CProfiler2::RESYNC_MAGIC)) == 0); pos += sizeof(CProfiler2::RESYNC_MAGIC); memcpy(&t, buffer.c_str()+pos, sizeof(t)); pos += sizeof(t); lastTime = t; visitor.OnSync(lastTime); break; } case CProfiler2::ITEM_EVENT: { CProfiler2::SItem_dt_id item; memcpy(&item, buffer.c_str()+pos, sizeof(item)); pos += sizeof(item); if (lastTime >= 0) { lastTime = lastTime + (double)item.dt; visitor.OnEvent(lastTime, item.id); } break; } case CProfiler2::ITEM_ENTER: { CProfiler2::SItem_dt_id item; memcpy(&item, buffer.c_str()+pos, sizeof(item)); pos += sizeof(item); if (lastTime >= 0) { lastTime = lastTime + (double)item.dt; visitor.OnEnter(lastTime, item.id); } break; } case CProfiler2::ITEM_LEAVE: { CProfiler2::SItem_dt_id item; memcpy(&item, buffer.c_str()+pos, sizeof(item)); pos += sizeof(item); if (lastTime >= 0) { lastTime = lastTime + (double)item.dt; visitor.OnLeave(lastTime, item.id); } break; } case CProfiler2::ITEM_ATTRIBUTE: { u32 len; memcpy(&len, buffer.c_str()+pos, sizeof(len)); ENSURE(len <= CProfiler2::MAX_ATTRIBUTE_LENGTH); pos += sizeof(len); std::string attribute(buffer.c_str()+pos, buffer.c_str()+pos+len); pos += len; if (lastTime >= 0) { visitor.OnAttribute(attribute); } break; } default: debug_warn(L"Invalid profiler item when parsing buffer"); return; } } };
void OSRunner::registerValue(const std::string& name, const std::string& value) { Attribute attribute(name,value); registerAttribute(attribute); }
void XmlSettingsDialog::ParseEntity (const QDomElement& entity, QWidget *baseWidget) { QDomElement item = entity.firstChildElement ("item"); while (!item.isNull ()) { ParseItem (item, baseWidget); item = item.nextSiblingElement ("item"); } auto gbox = entity.firstChildElement ("groupbox"); while (!gbox.isNull ()) { const auto box = new QGroupBox (GetLabel (gbox)); box->setSizePolicy (QSizePolicy::Expanding, QSizePolicy::Preferred); const auto groupLayout = new QGridLayout (); groupLayout->setContentsMargins (2, 2, 2, 2); box->setLayout (groupLayout); ParseEntity (gbox, box); const auto lay = qobject_cast<QGridLayout*> (baseWidget->layout ()); lay->addWidget (box, lay->rowCount (), 0, 1, 2); gbox = gbox.nextSiblingElement ("groupbox"); } auto scroll = entity.firstChildElement ("scrollarea"); while (!scroll.isNull ()) { const auto area = new QScrollArea (); if (scroll.hasAttribute ("horizontalScroll")) { const auto& attr = scroll.attribute ("horizontalScroll"); if (attr == "on") area->setHorizontalScrollBarPolicy (Qt::ScrollBarAlwaysOn); else if (attr == "off") area->setHorizontalScrollBarPolicy (Qt::ScrollBarAlwaysOff); } if (scroll.hasAttribute ("verticalScroll")) { const auto& attr = scroll.attribute ("verticalScroll"); if (attr == "on") area->setVerticalScrollBarPolicy (Qt::ScrollBarAlwaysOn); else if (attr == "off") area->setVerticalScrollBarPolicy (Qt::ScrollBarAlwaysOff); } area->setSizePolicy (QSizePolicy::Expanding, QSizePolicy::Expanding); const auto areaWidget = new QFrame; areaWidget->setSizePolicy (QSizePolicy::Expanding, QSizePolicy::Expanding); const auto areaLayout = new QGridLayout; areaWidget->setLayout (areaLayout); ParseEntity (scroll, areaWidget); area->setWidget (areaWidget); area->setWidgetResizable (true); areaWidget->show (); const auto lay = qobject_cast<QGridLayout*> (baseWidget->layout ()); const auto thisRow = lay->rowCount (); lay->addWidget (area, thisRow, 0, 1, 2); lay->setRowStretch (thisRow, 1); scroll = scroll.nextSiblingElement ("scrollarea"); } auto tab = entity.firstChildElement ("tab"); if (!tab.isNull ()) { const auto tabs = new QTabWidget; const auto lay = qobject_cast<QGridLayout*> (baseWidget->layout ()); lay->addWidget (tabs, lay->rowCount (), 0, 1, 2); while (!tab.isNull ()) { const auto page = new QWidget; const auto widgetLay = new QGridLayout; widgetLay->setContentsMargins (0, 0, 0, 0); page->setLayout (widgetLay); tabs->addTab (page, GetLabel (tab)); ParseEntity (tab, page); tab = tab.nextSiblingElement ("tab"); widgetLay->addItem (new QSpacerItem (0, 0, QSizePolicy::Minimum, QSizePolicy::Expanding), widgetLay->rowCount (), 0, 1, 1); } } }
/* The ultimate line painting function. Currently missing features: - draw indent lines */ void KateRenderer::paintTextLine(QPainter& paint, KateLineLayoutPtr range, int xStart, int xEnd, const KTextEditor::Cursor* cursor) { Q_ASSERT(range->isValid()); // kDebug( 13033 )<<"KateRenderer::paintTextLine"; // font data const QFontMetricsF &fm = config()->fontMetrics(); int currentViewLine = -1; if (cursor && cursor->line() == range->line()) currentViewLine = range->viewLineForColumn(cursor->column()); paintTextLineBackground(paint, range, currentViewLine, xStart, xEnd); if (range->layout()) { bool drawSelection = m_view->selection() && showSelections() && m_view->selectionRange().overlapsLine(range->line()); // Draw selection in block selecton mode. We need 2 kinds of selections that QTextLayout::draw can't render: // - past-end-of-line selection and // - 0-column-wide selection (used to indicate where text will be typed) if (drawSelection && m_view->blockSelection()) { int selectionStartColumn = m_doc->fromVirtualColumn(range->line(), m_doc->toVirtualColumn(m_view->selectionRange().start())); int selectionEndColumn = m_doc->fromVirtualColumn(range->line(), m_doc->toVirtualColumn(m_view->selectionRange().end())); QBrush selectionBrush = config()->selectionColor(); if (selectionStartColumn != selectionEndColumn) { KateTextLayout lastLine = range->viewLine(range->viewLineCount() - 1); if (selectionEndColumn > lastLine.startCol()) { int selectionStartX = (selectionStartColumn > lastLine.startCol()) ? cursorToX(lastLine, selectionStartColumn, true) : 0; int selectionEndX = cursorToX(lastLine, selectionEndColumn, true); paint.fillRect(QRect(selectionStartX - xStart, (int)lastLine.lineLayout().y(), selectionEndX - selectionStartX, lineHeight()), selectionBrush); } } else { const int selectStickWidth = 2; KateTextLayout selectionLine = range->viewLine(range->viewLineForColumn(selectionStartColumn)); int selectionX = cursorToX(selectionLine, selectionStartColumn, true); paint.fillRect(QRect(selectionX - xStart, (int)selectionLine.lineLayout().y(), selectStickWidth, lineHeight()), selectionBrush); } } QVector<QTextLayout::FormatRange> additionalFormats; if (range->length() > 0) { // We may have changed the pen, be absolutely sure it gets set back to // normal foreground color before drawing text for text that does not // set the pen color paint.setPen(attribute(KTextEditor::HighlightInterface::dsNormal)->foreground().color()); // Draw the text :) if (drawSelection) { // FIXME toVector() may be a performance issue additionalFormats = decorationsForLine(range->textLine(), range->line(), true).toVector(); range->layout()->draw(&paint, QPoint(-xStart,0), additionalFormats); } else { range->layout()->draw(&paint, QPoint(-xStart,0)); } } QBrush backgroundBrush; bool backgroundBrushSet = false; // Loop each individual line for additional text decoration etc. QListIterator<QTextLayout::FormatRange> it = range->layout()->additionalFormats(); QVectorIterator<QTextLayout::FormatRange> it2 = additionalFormats; for (int i = 0; i < range->viewLineCount(); ++i) { KateTextLayout line = range->viewLine(i); // Determine the background to use, if any, for the end of this view line backgroundBrushSet = false; while (it2.hasNext()) { const QTextLayout::FormatRange& fr = it2.peekNext(); if (fr.start > line.endCol()) break; if (fr.start + fr.length > line.endCol()) { if (fr.format.hasProperty(QTextFormat::BackgroundBrush)) { backgroundBrushSet = true; backgroundBrush = fr.format.background(); } goto backgroundDetermined; } it2.next(); } while (it.hasNext()) { const QTextLayout::FormatRange& fr = it.peekNext(); if (fr.start > line.endCol()) break; if (fr.start + fr.length > line.endCol()) { if (fr.format.hasProperty(QTextFormat::BackgroundBrush)) { backgroundBrushSet = true; backgroundBrush = fr.format.background(); } break; } it.next(); } backgroundDetermined: // Draw selection or background color outside of areas where text is rendered if (!m_printerFriendly ) { bool draw = false; QBrush drawBrush; if (m_view->selection() && !m_view->blockSelection() && m_view->lineEndSelected(line.end(true))) { draw = true; drawBrush = config()->selectionColor(); } else if (backgroundBrushSet && !m_view->blockSelection()) { draw = true; drawBrush = backgroundBrush; } if (draw) { int fillStartX = line.endX() - line.startX() + line.xOffset() - xStart; int fillStartY = lineHeight() * i; int width= xEnd - xStart - fillStartX; int height= lineHeight(); // reverse X for right-aligned lines if (range->layout()->textOption().alignment() == Qt::AlignRight) fillStartX = 0; if (width > 0) { QRect area(fillStartX, fillStartY, width, height); paint.fillRect(area, drawBrush); } } } // Draw indent lines if (showIndentLines() && i == 0) { const qreal w = spaceWidth(); const int lastIndentColumn = range->textLine()->indentDepth(m_tabWidth); for (int x = m_indentWidth; x < lastIndentColumn; x += m_indentWidth) { paintIndentMarker(paint, x * w + 1 - xStart, range->line()); } } // draw an open box to mark non-breaking spaces const QString& text = range->textLine()->string(); int y = lineHeight() * i + fm.ascent() - fm.strikeOutPos(); int nbSpaceIndex = text.indexOf(nbSpaceChar, line.lineLayout().xToCursor(xStart)); while (nbSpaceIndex != -1 && nbSpaceIndex < line.endCol()) { int x = line.lineLayout().cursorToX(nbSpaceIndex); if (x > xEnd) break; paintNonBreakSpace(paint, x - xStart, y); nbSpaceIndex = text.indexOf(nbSpaceChar, nbSpaceIndex + 1); } // draw tab stop indicators if (showTabs()) { int tabIndex = text.indexOf(tabChar, line.lineLayout().xToCursor(xStart)); while (tabIndex != -1 && tabIndex < line.endCol()) { int x = line.lineLayout().cursorToX(tabIndex); if (x > xEnd) break; paintTabstop(paint, x - xStart + spaceWidth()/2.0, y); tabIndex = text.indexOf(tabChar, tabIndex + 1); } } // draw trailing spaces if (showTrailingSpaces()) { int spaceIndex = line.endCol() - 1; int trailingPos = range->textLine()->lastChar(); if (trailingPos < 0) trailingPos = 0; if (spaceIndex >= trailingPos) { while (spaceIndex >= line.startCol() && text.at(spaceIndex).isSpace()) { if (text.at(spaceIndex) != '\t' || !showTabs()) paintTrailingSpace(paint, line.lineLayout().cursorToX(spaceIndex) - xStart + spaceWidth()/2.0, y); --spaceIndex; } } } } // draw word-wrap-honor-indent filling if ( (range->viewLineCount() > 1) && range->shiftX() && (range->shiftX() > xStart) ) { if (backgroundBrushSet) paint.fillRect(0, lineHeight(), range->shiftX() - xStart, lineHeight() * (range->viewLineCount() - 1), backgroundBrush); paint.fillRect(0, lineHeight(), range->shiftX() - xStart, lineHeight() * (range->viewLineCount() - 1), QBrush(config()->wordWrapMarkerColor(), Qt::Dense4Pattern)); } // Draw caret if (drawCaret() && cursor && range->includesCursor(*cursor)) { int caretWidth, lineWidth = 2; QColor color; QTextLine line = range->layout()->lineForTextPosition(qMin(cursor->column(), range->length())); // Determine the caret's style caretStyles style = caretStyle(); // Make the caret the desired width if (style == Line) { caretWidth = lineWidth; } else if (line.isValid() && cursor->column() < range->length()) { caretWidth = int(line.cursorToX(cursor->column() + 1) - line.cursorToX(cursor->column())); if (caretWidth < 0) { caretWidth = -caretWidth; } } else { caretWidth = spaceWidth(); } // Determine the color if (m_caretOverrideColor.isValid()) { // Could actually use the real highlighting system for this... // would be slower, but more accurate for corner cases color = m_caretOverrideColor; } else { // search for the FormatRange that includes the cursor foreach (const QTextLayout::FormatRange &r, range->layout()->additionalFormats()) { if ((r.start <= cursor->column() ) && ( (r.start + r.length) > cursor->column())) { // check for Qt::NoBrush, as the returned color is black() and no invalid QColor QBrush foregroundBrush = r.format.foreground(); if (foregroundBrush != Qt::NoBrush) { color = r.format.foreground().color(); } break; } } // still no color found, fall back to default style if (!color.isValid()) color = attribute(KTextEditor::HighlightInterface::dsNormal)->foreground().color(); } // Clip the caret - Qt's caret has a habit of intruding onto other lines. paint.save(); paint.setClipRect(0, line.lineNumber() * lineHeight(), xEnd - xStart, lineHeight()); switch(style) { case Line : paint.setPen(QPen(color, caretWidth)); break; case Block : // use a gray caret so it's possible to see the character color.setAlpha(128); paint.setPen(QPen(color, caretWidth)); break; case Underline : paint.setClipRect(0, lineHeight() - lineWidth, xEnd - xStart, lineWidth); break; case Half : color.setAlpha(128); paint.setPen(QPen(color, caretWidth)); paint.setClipRect(0, lineHeight() / 2, xEnd - xStart, lineHeight() / 2); break; } if (cursor->column() <= range->length()) { range->layout()->drawCursor(&paint, QPoint(-xStart,0), cursor->column(), caretWidth); } else { // Off the end of the line... must be block mode. Draw the caret ourselves. const KateTextLayout& lastLine = range->viewLine(range->viewLineCount() - 1); int x = cursorToX(lastLine, KTextEditor::Cursor(range->line(), cursor->column()), true); if ((x >= xStart) && (x <= xEnd)) { paint.fillRect(x - xStart, (int)lastLine.lineLayout().y(), caretWidth, lineHeight(), color); } } paint.restore(); }
//----------------------------------------------------------------------------------------------- XMLAttribute XMLNode::GetAttributeByName( const std::string& attributeName ) const { XMLAttribute attribute( m_node.attribute( attributeName.c_str() ) ); return attribute; }
/* Free an allocated name buffer */ xfree (PathName); /* Return the success code */ return RetCode; } /*****************************************************************************/ /* InputData functions */ /*****************************************************************************/ static void IDMarkStart (CharSource* S attribute ((unused))) /* Mark the start of the next token */ { /* Nothing to do here */ } static void IDNextChar (CharSource* S) /* Read the next character from the input text */ { C = *S->V.Data.Pos++; if (C == '\0') { /* End of input data */ --S->V.Data.Pos; C = EOF;
ParticleSystem::Node::Node() : m_geometry(attribute(), 0, sizeof(Vertex)) { setMaterial(&m_material); setGeometry(&m_geometry); m_geometry.setDrawingMode(GL_TRIANGLE_STRIP); }
void wb_volume::nextAref(pwr_tCid cid, pwr_sAttrRef *arp, pwr_sAttrRef *oarp) { tree_sTable *catt_tt = m_vrep->merep()->catt_tt(); int bd_size; if (!catt_tt) throw wb_error(LDH__CATT); wb_orep *op = m_vrep->object(&m_sts, arp->Objid); if (evenSts()) return; // Get body size wb_cdrep *cd = m_vrep->merep()->cdrep(&m_sts, cid); if (evenSts()) return; wb_bdrep *bd = cd->bdrep(&m_sts, pwr_eBix_rt); if (oddSts()) { bd_size = bd->size(); delete bd; } else bd_size = 0; delete cd; op->ref(); if (op->cid() == cid) { // Find next object in class list wb_orep *ol = m_vrep->next(&m_sts, op); if (oddSts()) { *oarp = pwr_cNAttrRef; oarp->Objid = ol->oid(); oarp->Flags.b.Object = 1; oarp->Size = bd_size; oarp->Body = cdh_cidToBid( cid, pwr_eBix_rt); ol->unref(); op->unref(); return; } else { // Find first attribute object merep_sClassAttrKey key; merep_sClassAttr *item; pwr_tCid hostCid = 0; key.subCid = cid; key.hostCid = 0; key.idx = 0; for (item = (merep_sClassAttr*) tree_FindSuccessor(&m_sts, catt_tt, &key); item && item->key.subCid == cid; item = (merep_sClassAttr*) tree_FindSuccessor(&m_sts, catt_tt, &item->key)) { if (cd && item->key.hostCid == hostCid) // Same class with other index continue; hostCid = item->key.hostCid; wb_orep *ol = m_vrep->object(&m_sts, item->key.hostCid); if (oddSts()) { ol->ref(); *oarp = pwr_cNAttrRef; oarp->Objid = ol->oid(); oarp->Flags.b.ObjectAttr = 1; oarp->Size = bd_size; oarp->Offset = item->offset[0]; oarp->Body = cdh_cidToBid( cid, pwr_eBix_rt); ol->unref(); op->unref(); if (item->flags[0] & PWR_MASK_DISABLEATTR) { wb_attribute a = attribute(oarp); if (a.disabled()) { pwr_sAttrRef aref = *oarp; nextAref(cid, &aref, oarp); } } return; } } op->unref(); m_sts = LDH__NONEXT; return; } } // Find next attribute object in current object merep_sClassAttrKey key; merep_sClassAttr *item; int first_offset = 0; key.subCid = cid; key.hostCid = op->cid(); key.idx = 0; for (item = (merep_sClassAttr*)tree_Find(&m_sts, catt_tt, &key); item && item->key.subCid == cid && item->key.hostCid == op->cid(); item = (merep_sClassAttr*)tree_FindSuccessor(&m_sts, catt_tt, &item->key)) { // Find next offset for (int i = 0; i < item->numOffset; i++) { if (i == 0 && item->key.idx == 0) first_offset = item->offset[0]; if (item->offset[i] > arp->Offset) { *oarp = pwr_cNAttrRef; oarp->Objid = op->oid(); oarp->Flags.b.ObjectAttr = 1; oarp->Offset = item->offset[i]; oarp->Size = bd_size; oarp->Body = cdh_cidToBid( cid, pwr_eBix_rt); op->unref(); if (item->flags[0] & PWR_MASK_DISABLEATTR) { wb_attribute a = attribute(oarp); if (a.disabled()) { pwr_sAttrRef aref = *oarp; nextAref(cid, &aref, oarp); } } return; } } } // Find first attribute in next object wb_orep *ol = m_vrep->next(&m_sts, op); if (oddSts()) { ol->ref(); *oarp = pwr_cNAttrRef; oarp->Objid = ol->oid(); oarp->Flags.b.ObjectAttr = 1; oarp->Offset = first_offset; oarp->Size = bd_size; oarp->Body = cdh_cidToBid( cid, pwr_eBix_rt); ol->unref(); op->unref(); if (item->flags[0] & PWR_MASK_DISABLEATTR) { wb_attribute a = attribute(oarp); if (a.disabled()) { pwr_sAttrRef aref = *oarp; nextAref(cid, &aref, oarp); } } return; } // Find first offset in first object of next class key.subCid = cid; key.hostCid = op->cid(); key.idx = 0; for (item = (merep_sClassAttr*) tree_Find(&m_sts, catt_tt, &key); item && item->key.subCid == cid; item = (merep_sClassAttr*) tree_FindSuccessor(&m_sts, catt_tt, &item->key)) { if (item->key.hostCid == key.hostCid) continue; wb_orep *ol = m_vrep->object(&m_sts, item->key.hostCid); if (oddSts()) { ol->ref(); *oarp = pwr_cNAttrRef; oarp->Objid = ol->oid(); oarp->Flags.b.ObjectAttr = 1; oarp->Offset = item->offset[0]; oarp->Size = bd_size; oarp->Body = cdh_cidToBid( cid, pwr_eBix_rt); ol->unref(); op->unref(); if (item->flags[0] & PWR_MASK_DISABLEATTR) { wb_attribute a = attribute(oarp); if (a.disabled()) { pwr_sAttrRef aref = *oarp; nextAref(cid, &aref, oarp); } } return; } } m_sts = LDH__NONEXT; op->unref(); }
bool ModelBaker::compressMesh(FBXMesh& mesh, bool hasDeformers, FBXNode& dracoMeshNode, GetMaterialIDCallback materialIDCallback) { if (mesh.wasCompressed) { handleError("Cannot re-bake a file that contains compressed mesh"); return false; } Q_ASSERT(mesh.normals.size() == 0 || mesh.normals.size() == mesh.vertices.size()); Q_ASSERT(mesh.colors.size() == 0 || mesh.colors.size() == mesh.vertices.size()); Q_ASSERT(mesh.texCoords.size() == 0 || mesh.texCoords.size() == mesh.vertices.size()); int64_t numTriangles{ 0 }; for (auto& part : mesh.parts) { if ((part.quadTrianglesIndices.size() % 3) != 0 || (part.triangleIndices.size() % 3) != 0) { handleWarning("Found a mesh part with invalid index data, skipping"); continue; } numTriangles += part.quadTrianglesIndices.size() / 3; numTriangles += part.triangleIndices.size() / 3; } if (numTriangles == 0) { return false; } draco::TriangleSoupMeshBuilder meshBuilder; meshBuilder.Start(numTriangles); bool hasNormals{ mesh.normals.size() > 0 }; bool hasColors{ mesh.colors.size() > 0 }; bool hasTexCoords{ mesh.texCoords.size() > 0 }; bool hasTexCoords1{ mesh.texCoords1.size() > 0 }; bool hasPerFaceMaterials = (materialIDCallback) ? (mesh.parts.size() > 1 || materialIDCallback(0) != 0 ) : true; bool needsOriginalIndices{ hasDeformers }; int normalsAttributeID { -1 }; int colorsAttributeID { -1 }; int texCoordsAttributeID { -1 }; int texCoords1AttributeID { -1 }; int faceMaterialAttributeID { -1 }; int originalIndexAttributeID { -1 }; const int positionAttributeID = meshBuilder.AddAttribute(draco::GeometryAttribute::POSITION, 3, draco::DT_FLOAT32); if (needsOriginalIndices) { originalIndexAttributeID = meshBuilder.AddAttribute( (draco::GeometryAttribute::Type)DRACO_ATTRIBUTE_ORIGINAL_INDEX, 1, draco::DT_INT32); } if (hasNormals) { normalsAttributeID = meshBuilder.AddAttribute(draco::GeometryAttribute::NORMAL, 3, draco::DT_FLOAT32); } if (hasColors) { colorsAttributeID = meshBuilder.AddAttribute(draco::GeometryAttribute::COLOR, 3, draco::DT_FLOAT32); } if (hasTexCoords) { texCoordsAttributeID = meshBuilder.AddAttribute(draco::GeometryAttribute::TEX_COORD, 2, draco::DT_FLOAT32); } if (hasTexCoords1) { texCoords1AttributeID = meshBuilder.AddAttribute( (draco::GeometryAttribute::Type)DRACO_ATTRIBUTE_TEX_COORD_1, 2, draco::DT_FLOAT32); } if (hasPerFaceMaterials) { faceMaterialAttributeID = meshBuilder.AddAttribute( (draco::GeometryAttribute::Type)DRACO_ATTRIBUTE_MATERIAL_ID, 1, draco::DT_UINT16); } auto partIndex = 0; draco::FaceIndex face; uint16_t materialID; for (auto& part : mesh.parts) { materialID = (materialIDCallback) ? materialIDCallback(partIndex) : partIndex; auto addFace = [&](QVector<int>& indices, int index, draco::FaceIndex face) { int32_t idx0 = indices[index]; int32_t idx1 = indices[index + 1]; int32_t idx2 = indices[index + 2]; if (hasPerFaceMaterials) { meshBuilder.SetPerFaceAttributeValueForFace(faceMaterialAttributeID, face, &materialID); } meshBuilder.SetAttributeValuesForFace(positionAttributeID, face, &mesh.vertices[idx0], &mesh.vertices[idx1], &mesh.vertices[idx2]); if (needsOriginalIndices) { meshBuilder.SetAttributeValuesForFace(originalIndexAttributeID, face, &mesh.originalIndices[idx0], &mesh.originalIndices[idx1], &mesh.originalIndices[idx2]); } if (hasNormals) { meshBuilder.SetAttributeValuesForFace(normalsAttributeID, face, &mesh.normals[idx0], &mesh.normals[idx1], &mesh.normals[idx2]); } if (hasColors) { meshBuilder.SetAttributeValuesForFace(colorsAttributeID, face, &mesh.colors[idx0], &mesh.colors[idx1], &mesh.colors[idx2]); } if (hasTexCoords) { meshBuilder.SetAttributeValuesForFace(texCoordsAttributeID, face, &mesh.texCoords[idx0], &mesh.texCoords[idx1], &mesh.texCoords[idx2]); } if (hasTexCoords1) { meshBuilder.SetAttributeValuesForFace(texCoords1AttributeID, face, &mesh.texCoords1[idx0], &mesh.texCoords1[idx1], &mesh.texCoords1[idx2]); } }; for (int i = 0; (i + 2) < part.quadTrianglesIndices.size(); i += 3) { addFace(part.quadTrianglesIndices, i, face++); } for (int i = 0; (i + 2) < part.triangleIndices.size(); i += 3) { addFace(part.triangleIndices, i, face++); } partIndex++; } auto dracoMesh = meshBuilder.Finalize(); if (!dracoMesh) { handleWarning("Failed to finalize the baking of a draco Geometry node"); return false; } // we need to modify unique attribute IDs for custom attributes // so the attributes are easily retrievable on the other side if (hasPerFaceMaterials) { dracoMesh->attribute(faceMaterialAttributeID)->set_unique_id(DRACO_ATTRIBUTE_MATERIAL_ID); } if (hasTexCoords1) { dracoMesh->attribute(texCoords1AttributeID)->set_unique_id(DRACO_ATTRIBUTE_TEX_COORD_1); } if (needsOriginalIndices) { dracoMesh->attribute(originalIndexAttributeID)->set_unique_id(DRACO_ATTRIBUTE_ORIGINAL_INDEX); } draco::Encoder encoder; encoder.SetAttributeQuantization(draco::GeometryAttribute::POSITION, 14); encoder.SetAttributeQuantization(draco::GeometryAttribute::TEX_COORD, 12); encoder.SetAttributeQuantization(draco::GeometryAttribute::NORMAL, 10); encoder.SetSpeedOptions(0, 5); draco::EncoderBuffer buffer; encoder.EncodeMeshToBuffer(*dracoMesh, &buffer); FBXNode dracoNode; dracoNode.name = "DracoMesh"; auto value = QVariant::fromValue(QByteArray(buffer.data(), (int)buffer.size())); dracoNode.properties.append(value); dracoMeshNode = dracoNode; // Mesh compression successful return true return true; }
void SVGInterpolationType::apply(const InterpolableValue& interpolableValue, const NonInterpolableValue* nonInterpolableValue, InterpolationEnvironment& environment) const { environment.svgElement().setWebAnimatedAttribute(attribute(), appliedSVGValue(interpolableValue, nonInterpolableValue)); }
attribute_type getOrientation() const { return attribute() & fmwk_orientation_mask; }
void Tag::parse(const QString &p_tagStr, Document *p_write) { attrs.clear(); m_tagStr = p_tagStr; uint strLength = m_tagStr.length(); cleanStr = m_tagStr; m_write = p_write; if (!m_tagStr.startsWith("<")) { type = Text; return; } m_nameLine = m_area.bLine; m_nameCol = m_area.bCol + 1; uint pos = 1; while (pos < strLength && !m_tagStr[pos].isSpace() && m_tagStr[pos] != '>' && m_tagStr[pos] != '\n') { pos++; } name = m_tagStr.mid(1, pos - 1); int nameSpacePos = name.find(':'); if (nameSpacePos != -1) { nameSpace = name.left(nameSpacePos); name = name.mid(++nameSpacePos); m_nameCol += nameSpacePos; } QString attrStr; TagAttr attr; attr.special = false; //by default non of the attributes are special while (pos < strLength && m_tagStr[pos].isSpace()) pos++; int sPos = pos; int valueStartPos = 0; while (pos < strLength) { //find the attribute name while (pos < strLength && !m_tagStr[pos].isSpace() && m_tagStr[pos] != '=') { pos++; } attr.name = m_tagStr.mid(sPos, pos - sPos); if (attr.name.endsWith(">") && pos == strLength) { attr.name = attr.name.left(attr.name.length() - 1).lower(); if (!attr.name.stripWhiteSpace().isEmpty()) { attr.nameLine = m_tagStr.left(sPos).contains('\n') + m_area.bLine; if (attr.nameLine == m_area.bLine) attr.nameCol = sPos + m_area.bCol; else attr.nameCol = m_tagStr.left(sPos).section('\n',-1).length(); attr.value = (dtd != 0) ? dtd->booleanTrue : QString("checked"); attr.valueCol = attr.nameCol; attr.valueLine = attr.nameLine; attr.quoted = false; attrs.append(attr); } break; } if (dtd && !dtd->caseSensitive) attr.name = attr.name.lower(); attr.nameLine = m_tagStr.left(sPos).contains('\n') + m_area.bLine; if (attr.nameLine == m_area.bLine) attr.nameCol = sPos + m_area.bCol; else attr.nameCol = m_tagStr.left(sPos).section('\n',-1).length(); while (pos < m_tagStr.length() && m_tagStr[pos].isSpace()) pos++; //if the attribute is just listed and there is no value specified, //treate it as a "true" boolean if (m_tagStr[pos] != '=' || pos == strLength) { attr.value = (dtd != 0) ? dtd->booleanTrue : QString("checked"); attr.valueCol = attr.nameCol; attr.valueLine = attr.nameLine; attr.quoted = false; pos--; } else { pos++; while (pos < strLength && m_tagStr[pos].isSpace()) pos++; if (m_tagStr[pos] == '\'' || m_tagStr[pos] == '"') { attr.quoted = true; valueStartPos = pos + 1; QChar quotation = m_tagStr[pos]; pos += 1; while (pos < strLength && (m_tagStr[pos] != quotation || (m_tagStr[pos] == quotation && m_tagStr[pos-1] == '\\'))) { pos++; } attr.value = m_tagStr.mid(valueStartPos, pos - valueStartPos); } else { attr.quoted = false; valueStartPos = pos; while (pos < strLength && !m_tagStr[pos].isSpace()) pos++; if (pos == strLength) pos--; attr.value = m_tagStr.mid(valueStartPos, pos - valueStartPos); } attr.valueLine = m_tagStr.left(valueStartPos).contains('\n') + m_area.bLine; if (attr.valueLine == m_area.bLine) attr.valueCol = valueStartPos + m_area.bCol; else attr.valueCol = m_tagStr.left(valueStartPos).section('\n',-1).length(); } attrs.append(attr); //go to the first non-space char. This is where the next attribute name starts pos++; while (pos < strLength && m_tagStr[pos].isSpace()) pos++; sPos = pos++; } //add the tag to the document usertag list if it's not present in the dtd if (m_tagStr.startsWith("<") && m_tagStr.endsWith(">") && dtd) { //QString tagName = (m_parsingDTD->caseSensitive) ? name : name.upper(); QString tagName = name.lower(); //add the new xml tags to the userTagList if ( !QuantaCommon::isKnownTag(dtd->name, tagName) && name[0] != '/' ) { QTag *newTag = m_write->userTagList.find(tagName); bool insertNew = !newTag; if (insertNew) { newTag = new QTag(); newTag->setName(name); newTag->parentDTD = dtd; } for (int i = 0; i >attrCount(); i++) { Attribute *attr = new Attribute; attr->name = attribute(i); attr->values.append(attributeValue(i)); newTag->addAttribute(attr); delete attr; } if (insertNew) { m_write->userTagList.insert(tagName, newTag); } } } }
Info API::DeleteFrom(SqlCommandDeleteFrom* command){ CatalogManager catalog_manager; IndexManager index_manager; RecordManager record_manager; bool delete_all_records = command->delete_all_records(); std::string table_name = command->table_name(); std::vector<WhereClause> where_clause = command->where_clause(); if (!catalog_manager.HasTable(table_name)){ std::string error_info; error_info = "Table \"" + table_name + "\" not exists."; return Info(error_info); } auto table = catalog_manager.GetTableInfo(table_name); for (auto it: where_clause){ if(!table.HasAttribute(it.kColumnName)){ std::string error_info; error_info = "attribute \"" + it.kColumnName + "\"in where clause \""+ it.kColumnName + it.kOperator + it.kCondition +"\" not exists."; return Info(error_info); } } if (delete_all_records){ if(record_manager.DeleteAllRecords(table)){ //update index for (auto it : table.index_names()){ IndexInfo index_info = catalog_manager.GetIndexInfo(it); index_manager.EmptyIndex(index_info); } return Info(); } else{ return Info("Delete records failed"); } } else{ std::vector<WhereClause> where_clause_with_index; std::vector<WhereClause> where_clause_without_index; for (auto it : where_clause){ if (!table.attribute(it.kColumnName).index_names().empty() && it.kOperator != "!="){ where_clause_with_index.push_back(it); } else{ where_clause_without_index.push_back(it); } } std::vector<std::pair<int,int>> results; if (!where_clause_with_index.empty()) //条件里有属性有 index { for (auto it : where_clause_with_index){ std::string index_name = table.attribute(it.kColumnName).index_names().at(0); IndexInfo index = catalog_manager.GetIndexInfo(index_name); std::vector<int> offsets_of_a_clause = index_manager.FindRecords(table,index, it); if(offsets_of_a_clause.empty()){ std::string error_info; error_info = "record not found with index, deletion failed"; return Info(error_info); } std::sort(offsets_of_a_clause.begin(), offsets_of_a_clause.end()); offsets_of_a_clause.erase(std::unique(offsets_of_a_clause.begin(), offsets_of_a_clause.end()), offsets_of_a_clause.end()); std::vector<std::pair<int,int>> results_of_a_clause = record_manager.FindRecordsWithIndex(offsets_of_a_clause, table, it); if (results.empty()){ results = results_of_a_clause; } else{ std::vector<std::pair<int,int> > results_temp; std::set_intersection(results.begin(),results.end(), results_of_a_clause.begin(),results_of_a_clause.end(), std::back_inserter(results_temp)); results = results_temp; } } for(auto it : where_clause_without_index){ if(results.empty()){ std::string error_info; error_info = "record not found with index, deletion failed"; return Info(error_info); } results = record_manager.RecordsFilter(results, table, it); } } else{ //条件里属性都没有 index for (auto it: where_clause_without_index){ if (results.empty()){ results = record_manager.FindRecordsWithNoIndex(table, it); } else{ results = record_manager.RecordsFilter(results,table, it); } } if(results.empty()){ std::string error_info; error_info = "record not found with no index, deletion failed"; return Info(error_info); } } if(results.empty()){ std::string error_info; error_info = "record not found, deletion failed"; return Info(error_info); } auto records = record_manager.SelectRecords(results, table); int ret = record_manager.DeleteRecords(results, table); if(!ret){ return Info("Delete records failed."); } else{ auto index_names = table.index_names(); int pair_index = 0; for (auto it : records){ for (auto i : index_names){ IndexInfo index_info = catalog_manager.GetIndexInfo(i); auto index = table.attribute_index(index_info.attribute_name()); std::string value = it.at(index); int offset_i = results.at(pair_index).first; bool ret = index_manager.DeleteRecord(table, index_info, value, offset_i); if(!ret){ return Info("Delete record in index \"" + index_info.name() + "on attribute \"" + index_info.attribute_name() +"\" of table \"" + index_info.table_name() + "\"failed."); } } pair_index++; } return Info(); } } }
void KopeteImportThread::ParseFile (const QString& filename) { QFile file (filename); if (!file.open (QIODevice::ReadOnly)) { qWarning () << Q_FUNC_INFO << "unable to open file" << file.fileName () << file.errorString (); return; } QDomDocument doc; if (!doc.setContent (&file)) { qWarning () << Q_FUNC_INFO << "error parsing file" << file.fileName (); return; } int month = 0, year = 0; QString contact; QString ourContact; ParseHead (doc.documentElement (), month, year, contact, ourContact); if (contact.isEmpty ()) { qWarning () << Q_FUNC_INFO << "got empty contact for" << file.fileName (); return; } QVariantList list; auto msg = doc.documentElement ().firstChildElement ("msg"); while (!msg.isNull ()) { const auto& rawTime = msg.attribute ("time").split (' ', QString::SkipEmptyParts); QVariantMap result; result ["EntryID"] = contact; result ["DateTime"] = QDateTime (QDate (year, month, rawTime.value (0).toInt ()), QTime::fromString (rawTime.value (1), "h:m:s")); result ["Direction"] = msg.attribute ("in") == "0" ? "in" : "out"; result ["Body"] = msg.text (); result ["MessageType"] = "chat"; list << result; msg = msg.nextSiblingElement ("msg"); } if (list.isEmpty ()) return; Entity e; e.Additional_ ["History"] = list; e.Mime_ = "x-leechcraft/im-history-import"; e.Additional_ ["AccountName"] = ourContact; e.Additional_ ["AccountID"] = ourContact; e.Parameters_ = OnlyHandle | FromUserInitiated; Proxy_->GetEntityManager ()->HandleEntity (e); }
bool HbXmlLoaderBaseSyntax::readAnchorLayoutStartItem(bool idBased) { bool result = true; HbXmlLengthValue minVal, prefVal, maxVal; QSizePolicy::Policy sizepolicyVal; QSizePolicy::Policy *sizepolicyValP = 0; HbAnchor::Direction directionVal; HbAnchor::Direction *directionValP = 0; QString anchorId; const QString src = attribute( AL_SRC_NAME ); QString srcId = attribute( AL_SRC_ID ); if ( src.isNull() && srcId.isNull() ) { HB_DOCUMENTLOADER_PRINT( QString( "ANCHORLAYOUT: NO SRC NOR SRCID SPECIFIED" ) ); result = false; } else if ( !src.isNull() && !srcId.isNull() ) { HB_DOCUMENTLOADER_PRINT( QString( "ANCHORLAYOUT: BOTH SRC AND SRCID SPECIFIED" ) ); result = false; } else if ( idBased && srcId.isNull() ) { srcId = src; } const QString dst = attribute( AL_DST_NAME ); QString dstId = attribute( AL_DST_ID ); if ( dst.isNull() && dstId.isNull() ) { HB_DOCUMENTLOADER_PRINT( QString( "ANCHORLAYOUT: NO DST NOR DSTID SPECIFIED" ) ); result = false; } else if ( !dst.isNull() && !dstId.isNull() ) { HB_DOCUMENTLOADER_PRINT( QString( "ANCHORLAYOUT: BOTH DST AND DSTID SPECIFIED" ) ); result = false; } else if ( idBased && dstId.isNull() ) { dstId = dst; } const QString srcEdgeStr = attribute( AL_SRC_EDGE ); const QString dstEdgeStr = attribute( AL_DST_EDGE ); Hb::Edge srcEdge, dstEdge; result &= toAnchorEdge( srcEdgeStr, srcEdge ); result &= toAnchorEdge( dstEdgeStr, dstEdge ); // Check the convenience notation first. QString spacing = attribute( AL_SPACING ); if ( result && !spacing.isEmpty() ) { directionVal = HbAnchor::Positive; directionValP = &directionVal; if (spacing.at(0) == '-') { directionVal = HbAnchor::Negative; spacing = spacing.mid(1); } sizepolicyVal = QSizePolicy::Fixed; sizepolicyValP = &sizepolicyVal; result = toLengthValue( spacing, prefVal ); } const QString direction = attribute( AL_DIRECTION ); if ( result && !direction.isNull() ) { // intentionally overriding possible previously set value directionValP = &directionVal; result = toAnchorDir( direction, directionVal ); } const QString spacer = attribute( AL_SPACER ); if ( result && !spacer.isEmpty() ) { // intentionally overriding possible previously set value sizepolicyVal = QSizePolicy::Preferred; sizepolicyValP = &sizepolicyVal; anchorId = spacer; if (prefVal.mType != HbXmlLengthValue::None) { // previously set by "spacing" minVal = prefVal; } else { prefVal.mType = HbXmlLengthValue::PlainNumber; prefVal.mValue = 0; } if ( !directionValP ) { // direction not yet set, use heuristics bool srcIsLayout = src.isEmpty() && srcId.isEmpty(); bool negativeEdge = srcEdge == Hb::LeftEdge || srcEdge == Hb::TopEdge; directionVal = ( (!srcIsLayout && negativeEdge) || (srcIsLayout && !negativeEdge) ) ? HbAnchor::Negative : HbAnchor::Positive; directionValP = &directionVal; HB_DOCUMENTLOADER_PRINT( QString( "ANCHORLAYOUT: ANCHOR DIRECTION SET BY HEURISTICS" ) ); } } const QString minLength = attribute( AL_MIN_LENGTH ); const QString prefLength = attribute( AL_PREF_LENGTH ); const QString maxLength = attribute( AL_MAX_LENGTH ); const QString sizepolicy = attribute( AL_SIZEPOLICY ); const QString anchorIdTemp = attribute( AL_ANCHOR_ID ); if ( !anchorIdTemp.isNull() ) { // intentionally overriding possible previously set value anchorId = anchorIdTemp; } if ( result && !minLength.isNull() ) { // intentionally overriding possible previously set value result = toLengthValue( minLength, minVal ); } if ( result && !prefLength.isNull() ) { // intentionally overriding possible previously set value result = toLengthValue( prefLength, prefVal ); } if ( result && !maxLength.isNull() ) { result = toLengthValue( maxLength, maxVal ); } if ( result && !sizepolicy.isNull() ) { // intentionally overriding possible previously set value sizepolicyValP = &sizepolicyVal; result = toSizePolicy( sizepolicy, sizepolicyVal ); } if ( result ) { result = mActions->addAnchorLayoutItem( src, srcId, srcEdge, dst, dstId, dstEdge, minVal, prefVal, maxVal, sizepolicyValP, directionValP, anchorId ); } return result; }
QList<QTextLayout::FormatRange> KateRenderer::decorationsForLine( const Kate::TextLine& textLine, int line, bool selectionsOnly, KateRenderRange* completionHighlight, bool completionSelected ) const { QList<QTextLayout::FormatRange> newHighlight; // Don't compute the highlighting if there isn't going to be any highlighting QList<Kate::TextRange *> rangesWithAttributes = m_doc->buffer().rangesForLine (line, m_printerFriendly ? 0 : m_view, true); if (selectionsOnly || textLine->attributesList().count() || rangesWithAttributes.count()) { RenderRangeList renderRanges; // Add the inbuilt highlighting to the list NormalRenderRange* inbuiltHighlight = new NormalRenderRange(); const QVector<Kate::TextLineData::Attribute> &al = textLine->attributesList(); for (int i = 0; i < al.count(); ++i) if (al[i].length > 0 && al[i].attributeValue > 0) inbuiltHighlight->addRange(new KTextEditor::Range(KTextEditor::Cursor(line, al[i].offset), al[i].length), specificAttribute(al[i].attributeValue)); renderRanges.append(inbuiltHighlight); if (!completionHighlight) { // check for dynamic hl stuff const QSet<Kate::TextRange *> *rangesMouseIn = m_view ? m_view->rangesMouseIn () : 0; const QSet<Kate::TextRange *> *rangesCaretIn = m_view ? m_view->rangesCaretIn () : 0; bool anyDynamicHlsActive = m_view && (!rangesMouseIn->empty() || !rangesCaretIn->empty()); // sort all ranges, we want that the most specific ranges win during rendering, multiple equal ranges are kind of random, still better than old smart rangs behavior ;) qSort (rangesWithAttributes.begin(), rangesWithAttributes.end(), rangeLessThanForRenderer); // loop over all ranges for (int i = 0; i < rangesWithAttributes.size(); ++i) { // real range Kate::TextRange *kateRange = rangesWithAttributes[i]; // calculate attribute, default: normal attribute KTextEditor::Attribute::Ptr attribute = kateRange->attribute(); if (anyDynamicHlsActive) { // check mouse in if (KTextEditor::Attribute::Ptr attributeMouseIn = attribute->dynamicAttribute (KTextEditor::Attribute::ActivateMouseIn)) { if (rangesMouseIn->contains (kateRange)) attribute = attributeMouseIn; } // check caret in if (KTextEditor::Attribute::Ptr attributeCaretIn = attribute->dynamicAttribute (KTextEditor::Attribute::ActivateCaretIn)) { if (rangesCaretIn->contains (kateRange)) attribute = attributeCaretIn; } } // span range NormalRenderRange *additionaHl = new NormalRenderRange(); additionaHl->addRange(new KTextEditor::Range (*kateRange), attribute); renderRanges.append(additionaHl); } } else { // Add the code completion arbitrary highlight to the list renderRanges.append(completionHighlight); } // Add selection highlighting if we're creating the selection decorations if ((selectionsOnly && showSelections() && m_view->selection()) || (completionHighlight && completionSelected) || m_view->blockSelection()) { NormalRenderRange* selectionHighlight = new NormalRenderRange(); // Set up the selection background attribute TODO: move this elsewhere, eg. into the config? static KTextEditor::Attribute::Ptr backgroundAttribute; if (!backgroundAttribute) backgroundAttribute = KTextEditor::Attribute::Ptr(new KTextEditor::Attribute()); backgroundAttribute->setBackground(config()->selectionColor()); backgroundAttribute->setForeground(attribute(KTextEditor::HighlightInterface::dsNormal)->selectedForeground().color()); // Create a range for the current selection if (completionHighlight && completionSelected) selectionHighlight->addRange(new KTextEditor::Range(line, 0, line + 1, 0), backgroundAttribute); else if(m_view->blockSelection() && m_view->selectionRange().overlapsLine(line)) selectionHighlight->addRange(new KTextEditor::Range(m_doc->rangeOnLine(m_view->selectionRange(), line)), backgroundAttribute); else { selectionHighlight->addRange(new KTextEditor::Range(m_view->selectionRange()), backgroundAttribute); } renderRanges.append(selectionHighlight); // highlighting for the vi visual modes } KTextEditor::Cursor currentPosition, endPosition; // Calculate the range which we need to iterate in order to get the highlighting for just this line if (selectionsOnly) { if(m_view->blockSelection()) { KTextEditor::Range subRange = m_doc->rangeOnLine(m_view->selectionRange(), line); currentPosition = subRange.start(); endPosition = subRange.end(); } else { KTextEditor::Range rangeNeeded = m_view->selectionRange() & KTextEditor::Range(line, 0, line + 1, 0); currentPosition = qMax(KTextEditor::Cursor(line, 0), rangeNeeded.start()); endPosition = qMin(KTextEditor::Cursor(line + 1, 0), rangeNeeded.end()); } } else { currentPosition = KTextEditor::Cursor(line, 0); endPosition = KTextEditor::Cursor(line + 1, 0); } // Main iterative loop. This walks through each set of highlighting ranges, and stops each // time the highlighting changes. It then creates the corresponding QTextLayout::FormatRanges. while (currentPosition < endPosition) { renderRanges.advanceTo(currentPosition); if (!renderRanges.hasAttribute()) { // No attribute, don't need to create a FormatRange for this text range currentPosition = renderRanges.nextBoundary(); continue; } KTextEditor::Cursor nextPosition = renderRanges.nextBoundary(); // Create the format range and populate with the correct start, length and format info QTextLayout::FormatRange fr; fr.start = currentPosition.column(); if (nextPosition < endPosition || endPosition.line() <= line) { fr.length = nextPosition.column() - currentPosition.column(); } else { // +1 to force background drawing at the end of the line when it's warranted fr.length = textLine->length() - currentPosition.column() + 1; } KTextEditor::Attribute::Ptr a = renderRanges.generateAttribute(); if (a) { fr.format = *a; if(selectionsOnly) { assignSelectionBrushesFromAttribute(fr, *a); } } newHighlight.append(fr); currentPosition = nextPosition; } if (completionHighlight) // Don't delete external completion render range renderRanges.removeAll(completionHighlight); qDeleteAll(renderRanges); } return newHighlight; }
bool HbXmlLoaderBaseSyntax::scanForSections( QIODevice *device, QList<QString> §ionsList ) { const QChar separator(' '); bool exit = false; bool result = true; mReader.setDevice( device ); mCurrentSection.clear(); mTopState = TS_READ_DOCUMENT; while( !exit ) { switch( mTopState ) { case TS_READ_DOCUMENT: { mCurrentTokenType = mReader.readNext(); HB_DOCUMENTLOADER_PRINT( "TOP_STATE READ_ELEMENT " + mReader.name().toString() ); switch( mCurrentTokenType ) { case QXmlStreamReader::EndElement: case QXmlStreamReader::StartElement: { mCurrentElementType = elementType( mReader.name() ); if( ( mCurrentElementType == HbXml::METADATA ) && ( mCurrentTokenType == QXmlStreamReader::StartElement ) ) { mTopState = TS_READ_METADATA; break; } if( mCurrentElementType == HbXml::SECTION ) { if( mCurrentTokenType == QXmlStreamReader::StartElement ) { QString name = attribute( ATTR_NAME ); if( name.isEmpty() ) { qWarning() << "Section without a name, line " << mReader.lineNumber(); mTopState = TS_ERROR; break; } mCurrentSection << name; sectionsList.append( mCurrentSection.join( separator ) ); } else if( mCurrentTokenType == QXmlStreamReader::EndElement ) { mCurrentSection.removeLast(); } } break; } case QXmlStreamReader::EndDocument: { mTopState = TS_EXIT; break; } case QXmlStreamReader::Characters: { if( mReader.isWhitespace() ) { break; } HB_DOCUMENTLOADER_PRINT( "Characters" ); } case QXmlStreamReader::NoToken: HB_DOCUMENTLOADER_PRINT( "NoToken" ); case QXmlStreamReader::Invalid: HB_DOCUMENTLOADER_PRINT( "Invalid" ); case QXmlStreamReader::EntityReference: { qWarning() << "Parse error, line " << mReader.lineNumber(); mTopState = TS_ERROR; break; } case QXmlStreamReader::StartDocument: case QXmlStreamReader::Comment: case QXmlStreamReader::DTD: case QXmlStreamReader::ProcessingInstruction: default: { break; } } break; } case TS_READ_METADATA: { HB_DOCUMENTLOADER_PRINT( "TOP_STATE READ_METADATA" ); mCurrentTokenType = mReader.readNext(); switch( mCurrentTokenType ) { case QXmlStreamReader::EndElement: { mCurrentElementType = elementType( mReader.name() ); if( mCurrentElementType == HbXml::METADATA ) { mTopState = TS_READ_DOCUMENT; } break; } case QXmlStreamReader::NoToken: case QXmlStreamReader::Invalid: { qWarning() << "Parse error, line " << mReader.lineNumber(); mTopState = TS_ERROR; break; } case QXmlStreamReader::EndDocument: { qWarning() << "Unexpected end of document, line " << mReader.lineNumber(); mTopState = TS_ERROR; break; } default: { break; } } break; } case TS_ERROR: { HB_DOCUMENTLOADER_PRINT( "TOP_STATE ERROR" ); result = false; mTopState = TS_EXIT; break; } case TS_EXIT: { HB_DOCUMENTLOADER_PRINT( "TOP_STATE EXIT" ); exit = true; break; } default: { HB_DOCUMENTLOADER_PRINT( "INTERNAL ERROR" ); mTopState = TS_ERROR; break; } } } mReader.clear(); return result; }
std::shared_ptr<QNetworkReply> OsmAnd::Network::Downloader::download( const QUrl& url_, const DownloadSettings& settings_ /*= DownloadSettings()*/ ) { QWaitCondition resultWaitCondition; QMutex resultMutex; std::shared_ptr<QNetworkReply> result; const auto url = url_; const auto settings = settings_; resultMutex.lock(); Concurrent::pools->network->start(new Concurrent::Task([url, settings, &result, &resultMutex, &resultWaitCondition](Concurrent::Task* task, QEventLoop& eventLoop) { QNetworkAccessManager networkAccessManager; // Create request QNetworkRequest request; request.setUrl(url); request.setRawHeader("User-Agent", settings.userAgent.toLocal8Bit()); // Process until final reply is ready auto reply = networkAccessManager.get(request); for(;;) { // Wait for reply to be ready QObject::connect(reply, SIGNAL(finished()), &eventLoop, SLOT(quit())); eventLoop.exec(); // If settings specify that redirects must be followed, do that if(settings.autoFollowRedirects) { auto redirectUrl = reply->attribute(QNetworkRequest::RedirectionTargetAttribute).toUrl(); if(!redirectUrl.isEmpty()) { // Delete current reply reply->deleteLater(); // Create new request, and wait for reply to arrive QNetworkRequest newRequest; newRequest.setUrl(redirectUrl); request.setRawHeader("User-Agent", settings.userAgent.toLocal8Bit()); reply = networkAccessManager.get(newRequest); continue; } } // Since reply is ready, exit loop break; } // Propagate final reply reply->setParent(nullptr); { QMutexLocker scopedLocker(&resultMutex); result.reset(reply); resultWaitCondition.wakeAll(); } return; })); // Wait for condition resultWaitCondition.wait(&resultMutex); resultMutex.unlock(); return result; }
SimulatorResourceServerImplSP SimulatorResourceCreator::createResource( const std::string &configPath) { RAML::RamlPtr raml; try { std::shared_ptr<RAML::RamlParser> ramlParser = std::make_shared<RAML::RamlParser>(configPath); raml = ramlParser->getRamlPtr(); } catch (RAML::RamlException &e) { OC_LOG_V(ERROR, TAG, "RAML Exception occured! [%s]", e.what()); throw; } std::map<std::string, RAML::RamlResourcePtr> ramlResources = raml->getResources(); RAML::RamlResourcePtr ramlResource; if (0 == ramlResources.size() || (ramlResource = ramlResources.begin()->second) == nullptr) { OC_LOG(ERROR, TAG, "Zero resources detected from RAML!"); return nullptr; } if (ramlResource) { SimulatorResourceServerImplSP simResource(new SimulatorResourceServerImpl()); simResource->setName(ramlResource->getDisplayName()); simResource->setURI(ramlResource->getResourceUri()); // Get the resource representation schema from GET response body RAML::ActionPtr action = ramlResource->getAction(RAML::ActionType::GET); if (!action) { OC_LOG(ERROR, TAG, "Failed to create resource representation schema as it does not" "posess the GET request!"); return nullptr; } RAML::ResponsePtr getResponse = action->getResponse("200"); if (!getResponse) { OC_LOG(ERROR, TAG, "Resource does not provide valid GET response!"); return nullptr; } RAML::RequestResponseBodyPtr responseBody = getResponse->getResponseBody("application/json"); if (responseBody) { RAML::JsonSchemaPtr resourceProperties = responseBody->getSchema()->getProperties(); for ( auto & propertyElement : resourceProperties->getProperties()) { if (!propertyElement.second) continue; std::string propName = propertyElement.second->getName(); if ("rt" == propName || "resourceType" == propName) { simResource->setResourceType(propertyElement.second->getValueString()); continue; } else if ("if" == propName) { simResource->setInterfaceType(propertyElement.second->getValueString()); continue; } else if ("p" == propName || "n" == propName || "id" == propName) { continue; } // Build representation attribute SimulatorResourceModel::Attribute attribute(propName); switch (propertyElement.second->getValueType()) { case 0: // Integer attribute.setValue(propertyElement.second->getValue<int>()); break; case 1: // Double attribute.setValue(propertyElement.second->getValue<double>()); break; case 2: // Boolean attribute.setValue(propertyElement.second->getValue<bool>()); break; case 3: // String attribute.setValue(propertyElement.second->getValue<std::string>()); break; } // Set range/supported values set int min = 0, max = 0, multipleof = 0; propertyElement.second->getRange(min, max, multipleof); attribute.setRange(min, max); if (propertyElement.second->getAllowedValuesSize() > 0) attribute.setAllowedValues(propertyElement.second->getAllowedValues()); simResource->addAttribute(attribute); } } simResource->setURI(constructURI(simResource->getURI())); return simResource; } return nullptr; }
void OSRunner::registerValue(const std::string& name, int value, const std::string& units) { Attribute attribute(name,value,units); registerAttribute(attribute); }
pwr_tStatus wb_session::getMenu(ldh_sMenuCall* ip) { pwr_tStatus sts = 0; ldh_sMenuItem* Item = (ldh_sMenuItem*)&ldh_lMenuItem; pwr_tUInt32 i; pwr_tObjName MenuFolder; pwr_tString80 Menu; pwr_tBoolean isSame = FALSE; pwr_tClassId Class; pwr_tObjid Object; int nItems = 0; wb_name cn; for (i = 0; i < ip->SelectCount; i++) { if (cdh_ObjidIsEqual(ip->Pointed.Objid, ip->Selected[i].Objid) && ip->Pointed.Offset == ip->Selected[i].Offset && ip->Pointed.Flags.m == ip->Selected[i].Flags.m) { isSame = TRUE; break; } } sprintf(MenuFolder, "%sP%cs%c%c", ldh_lUtility[((wb_session*)ip->PointedSession)->utility()].Name, ldh_lMenuSet[ip->PointedSet].Char, ldh_lMenuSet[ip->SelectedSet].Char, (isSame ? 's' : 'n')); /* Find generic menues of pointed object */ switch (ip->PointedSet) { case ldh_eMenuSet_Object: { sprintf(Menu, "pwrs:Class-$Object-%s-Pointed", MenuFolder); wb_cdrep* cdrep = m_vrep->merep()->cdrep(&sts, pwr_eClass_Object); if (EVEN(sts)) return sts; wb_orep* o = m_vrep->erep()->object(&sts, Menu); if (EVEN(sts)) break; o->ref(); Object = o->oid(); void* o_menu_body; wb_orep* o_menu = cdrep->menuFirst(&sts, o, &o_menu_body); while (ODD(sts)) { o_menu->ref(); getAllMenuItems(ip, &Item, cdrep, o_menu, o_menu_body, 0, &nItems, 0); wb_orep* prev = o_menu; o_menu = cdrep->menuAfter(&sts, o_menu, &o_menu_body); prev->unref(); } delete cdrep; o->unref(); break; } case ldh_eMenuSet_ObjectAttr: { pwr_tObjName OMenuFolder; sprintf(OMenuFolder, "%sP%cs%c%c", ldh_lUtility[((wb_session*)ip->PointedSession)->utility()].Name, 'x', 'x', 'x'); sprintf(Menu, "pwrs:Class-$Object-%s-Pointed", OMenuFolder); wb_cdrep* cdrep = m_vrep->merep()->cdrep(&sts, pwr_eClass_Object); if (EVEN(sts)) return sts; wb_orep* o = m_vrep->erep()->object(&sts, Menu); if (EVEN(sts)) return sts; o->ref(); Object = o->oid(); void* o_menu_body; wb_orep* o_menu = cdrep->menuFirst(&sts, o, &o_menu_body); while (ODD(sts)) { o_menu->ref(); getAllMenuItems(ip, &Item, cdrep, o_menu, o_menu_body, 0, &nItems, 0); wb_orep* prev = o_menu; o_menu = cdrep->menuAfter(&sts, o_menu, &o_menu_body); prev->unref(); } delete cdrep; o->unref(); break; } case ldh_eMenuSet_Attribute: case ldh_eMenuSet_Array: { sprintf(Menu, "pwrs:Class-$Attribute-%s-Pointed", MenuFolder); wb_cdrep* cdrep = m_vrep->merep()->cdrep(&sts, pwr_eClass_Param); if (EVEN(sts)) return sts; wb_orep* o = m_vrep->erep()->object(&sts, Menu); if (EVEN(sts)) return sts; o->ref(); Object = o->oid(); void* o_menu_body; wb_orep* o_menu = cdrep->menuFirst(&sts, o, &o_menu_body); while (ODD(sts)) { o_menu->ref(); getAllMenuItems(ip, &Item, cdrep, o_menu, o_menu_body, 0, &nItems, 0); wb_orep* prev = o_menu; o_menu = cdrep->menuAfter(&sts, o_menu, &o_menu_body); prev->unref(); } delete cdrep; o->unref(); break; } case ldh_eMenuSet_Class: { sprintf(Menu, "pwrs:Class-$Object-%s-Pointed", MenuFolder); wb_cdrep* cdrep = m_vrep->merep()->cdrep(&sts, pwr_eClass_Object); if (EVEN(sts)) return sts; wb_orep* o = m_vrep->erep()->object(&sts, Menu); if (EVEN(sts)) return sts; o->ref(); Object = o->oid(); void* o_menu_body; wb_orep* o_menu = cdrep->menuFirst(&sts, o, &o_menu_body); while (ODD(sts)) { o_menu->ref(); getAllMenuItems(ip, &Item, cdrep, o_menu, o_menu_body, 0, &nItems, 0); wb_orep* prev = o_menu; o_menu = cdrep->menuAfter(&sts, o_menu, &o_menu_body); prev->unref(); } delete cdrep; o->unref(); break; } default:; } /* Find specific menues of pointed object */ switch (ip->PointedSet) { case ldh_eMenuSet_Object: case ldh_eMenuSet_ObjectAttr: { if (ip->PointedSet == ldh_eMenuSet_Class) { Class = cdh_ClassObjidToId(ip->Pointed.Objid); } else { wb_attribute a = attribute(&ip->Pointed); if (!a) return sts; Class = a.tid(); } wb_cdrep* cdrep = m_vrep->merep()->cdrep(&sts, Class); while (ODD(sts)) { cn = cdrep->longName(); sprintf(Menu, "%s-%s-Pointed", cn.name(), MenuFolder); wb_orep* o = m_vrep->erep()->object(&sts, Menu); if (ODD(sts)) { o->ref(); Object = o->oid(); void* o_menu_body; wb_orep* o_menu = cdrep->menuFirst(&sts, o, &o_menu_body); while (ODD(sts)) { o_menu->ref(); getAllMenuItems(ip, &Item, cdrep, o_menu, o_menu_body, 0, &nItems, 0); wb_orep* prev = o_menu; o_menu = cdrep->menuAfter(&sts, o_menu, &o_menu_body); prev->unref(); } o->unref(); } // Get menuitems for superclass wb_cdrep* super_cdrep = cdrep->super(&sts); if (super_cdrep) { delete cdrep; cdrep = super_cdrep; } } delete cdrep; break; } default:; } switch (ip->SelectedSet) { case ldh_eMenuSet_Attribute: case ldh_eMenuSet_Array: case ldh_eMenuSet_ObjectAttr: break; case ldh_eMenuSet_Class: case ldh_eMenuSet_Many: case ldh_eMenuSet_Object: { if (ip->PointedSet != ldh_eMenuSet_Object) break; /* Find generic menues for selected object(s) */ sprintf(Menu, "pwrs:Class-$Object-%s-Selected", MenuFolder); wb_cdrep* cdrep = m_vrep->merep()->cdrep(&sts, pwr_eClass_Object); if (EVEN(sts)) return sts; wb_orep* o = m_vrep->erep()->object(&sts, Menu); if (ODD(sts)) { o->ref(); Object = o->oid(); void* o_menu_body; wb_orep* o_menu = cdrep->menuFirst(&sts, o, &o_menu_body); while (ODD(sts)) { o_menu->ref(); getAllMenuItems(ip, &Item, cdrep, o_menu, o_menu_body, 0, &nItems, 0); wb_orep* prev = o_menu; o_menu = cdrep->menuAfter(&sts, o_menu, &o_menu_body); prev->unref(); } o->unref(); } delete cdrep; /* Find specific menues for selected object(s) */ if (ip->PointedSet == ldh_eMenuSet_Class) { Class = cdh_ClassObjidToId(ip->Pointed.Objid); } else { if (m_vrep->vid() == ip->Pointed.Objid.vid) o = m_vrep->object(&sts, ip->Pointed.Objid); else // Other volume o = m_vrep->erep()->object(&sts, ip->Pointed.Objid); if (EVEN(sts)) return sts; o->ref(); Class = o->cid(); o->unref(); } cdrep = m_vrep->merep()->cdrep(&sts, Class); while (ODD(sts)) { cn = cdrep->longName(); sprintf(Menu, "%s-%s-Selected", cn.name(), MenuFolder); o = m_vrep->erep()->object(&sts, Menu); if (ODD(sts)) { o->ref(); Object = o->oid(); void* o_menu_body; wb_orep* o_menu = cdrep->menuFirst(&sts, o, &o_menu_body); while (ODD(sts)) { o_menu->ref(); getAllMenuItems(ip, &Item, cdrep, o_menu, o_menu_body, 0, &nItems, 0); wb_orep* prev = o_menu; o_menu = cdrep->menuAfter(&sts, o_menu, &o_menu_body); prev->unref(); } o->unref(); } // Get menuitems for superclass wb_cdrep* super_cdrep = cdrep->super(&sts); if (super_cdrep) { delete cdrep; cdrep = super_cdrep; } } delete cdrep; break; } default: break; } Item->Level = 0; ip->ItemList = ldh_lMenuItem; ip->ItemCount = nItems - 1; return LDH__SUCCESS; }
void Coordinate_Test_Data::Initialize( const std::string& reference_file) { // Create instance if( instance == nullptr ){ instance = new Coordinate_Test_Data(); } // Open PugiXML Document pugi::xml_document xml_doc; pugi::xml_parse_result res = xml_doc.load_file( reference_file.c_str() ); // If problems, throw error if( !res ) { throw std::runtime_error("Unable to load reference file at: " + reference_file); } // Otherwise, grab the root node pugi::xml_node root_node = xml_doc.child("Coordinate_Conversion"); std::cout << "Root Node: " << root_node.name() << std::endl; // Grab the coordinate node pugi::xml_node coordinates_node = root_node.child("Coordinates"); if( !coordinates_node ){ throw std::runtime_error("Unable to find <Coordinates> node."); } for( auto node = coordinates_node.begin(); node != coordinates_node.end(); node++ ) { // Grab the node pugi::xml_node coord_node = (*node); // Get the name std::string location_name = coord_node.attribute("name").as_string(); // Add the node instance->m_coordinate_list[location_name] = Coordinate_Tuple(location_name); //Iterate over subnodes for( auto subnode = coord_node.begin(); subnode != coord_node.end(); subnode++ ) { // Check the type if( subnode->name() == std::string("Geog")) { // Get the Datum std::string datum_str = subnode->attribute("datum").as_string(); DatumType datum = String_To_DatumType(datum_str); // Latitude and Longitude double lat_deg = subnode->attribute("latitude_deg").as_double(); double lon_deg = subnode->attribute("longitude_deg").as_double(); // Add to coordinate list instance->m_coordinate_list[location_name].Add_Coordinate( std::make_shared<Coordinate_Geographic>( lon_deg, lat_deg, datum )); } else if( subnode->name() == std::string("UTM")) { // Get the Grid Zone int grid_zone = subnode->attribute("grid_zone").as_int(); // Get the hemisphere bool is_north = subnode->attribute("is_northern").as_bool(); // Get the Easting double easting_m = subnode->attribute("easting_meters").as_double(); double northing_m = subnode->attribute("northing_meters").as_double(); // Add to coordinate list instance->m_coordinate_list[location_name].Add_Coordinate( std::make_shared<Coordinate_UTM>( grid_zone, is_north, easting_m, northing_m )); } else if( subnode->name() == std::string("MGRS")) { } else { throw std::runtime_error("Unknown Node (" + std::string(subnode->name()) + ")"); } } } }
void main_window::on_load_mission() { auto filename = QFileDialog::getOpenFileName(this, "Load mission", "missions", "*.zip"); if (!filename.length()) return; std::string filename_str = to_str(filename); auto prov = &nya_resources::get_resources_provider(); nya_resources::file_resources_provider fprov; nya_resources::set_resources_provider(&fprov); nya_resources::zip_resources_provider zprov; bool result = zprov.open_archive(filename_str.c_str()); nya_resources::set_resources_provider(prov); if (!result) { alert("Unable to load location " + filename_str); return; } m_filename.assign(filename_str); pugi::xml_document doc; if (!load_xml(zprov.access("objects.xml"), doc)) return; auto root = doc.first_child(); std::string loc = root.attribute("location").as_string(); if (loc.empty()) return; clear_mission(); m_location = loc; m_scene_view->load_location(loc); auto p = root.child("player"); scene_view::object plr; plr.attributes["align"] = "ally"; plr.yaw = p.attribute("yaw").as_float(); plr.pos = read_vec3(p); plr.y = p.attribute("editor_y").as_float(); plr.pos.y -= plr.y; auto at = p.child("attribute"); for (auto a = at.attributes_begin(); a != at.attributes_end(); ++a) plr.attributes[a->name()] = a->value(); m_scene_view->set_player(plr); for (auto o = root.child("object"); o; o = o.next_sibling("object")) { scene_view::object obj; obj.name = o.attribute("name").as_string(); obj.id = o.attribute("id").as_string(); obj.active = o.attribute("active").as_bool(); obj.yaw = o.attribute("yaw").as_float(); obj.pos = read_vec3(o); obj.y = o.attribute("editor_y").as_float(); obj.pos.y -= obj.y; auto at = o.child("attribute"); for (auto a = at.attributes_begin(); a != at.attributes_end(); ++a) obj.attributes[a->name()] = a->value(); m_scene_view->add_object(obj); } for (auto z = root.child("zone"); z; z = z.next_sibling("zone")) { scene_view::zone zn; zn.name = z.attribute("name").as_string(); zn.active = z.attribute("active").as_bool(); zn.radius = z.attribute("radius").as_float(); zn.pos = read_vec3(z); auto at = z.child("attribute"); for (auto a = at.attributes_begin(); a != at.attributes_end(); ++a) zn.attributes[a->name()] = a->value(); m_scene_view->add_zone(zn); } for (auto p = root.child("path"); p; p = p.next_sibling("path")) { scene_view::path pth; pth.name = p.attribute("name").as_string(); for (auto p0 = p.child("point"); p0; p0 = p0.next_sibling("point")) { nya_math::vec4 p; p.xyz() = read_vec3(p0); p.w = p0.attribute("editor_y").as_float(); p.y -= p.w; pth.points.push_back(p); } m_scene_view->get_paths().push_back(pth); } auto script_res = zprov.access("script.lua"); if (script_res) { std::string script; script.resize(script_res->get_size()); if (!script.empty()) script_res->read_all(&script[0]); m_script_edit->setText(script.c_str()); script_res->release(); } if (load_xml(zprov.access("info.xml"), doc)) { auto root = doc.first_child(); m_mission_title->setText(root.attribute("name").as_string()); m_mission_description->setText(root.child("description").first_child().value()); auto author = root.child("author"); m_mission_author->setText(author.attribute("name").as_string()); m_mission_email->setText(author.attribute("email").as_string()); } update_objects_tree(); m_navigator->setCurrentIndex(mode_info); m_scene_view->set_focus("player spawn", 0); }
void Doom3EntityClass::parseFromTokens(parser::DefTokeniser& tokeniser) { // Clear this structure first, we might be "refreshing" ourselves from tokens clear(); // Required open brace (the name has already been parsed by the EClassManager) tokeniser.assertNextToken("{"); // Loop over all of the keys in this entitydef std::string key; while ((key = tokeniser.nextToken()) != "}") { const std::string value = tokeniser.nextToken(); // Handle some keys specially if (key == "model") { setModelPath(os::standardPath(value)); } else if (key == "editor_color") { setColour(string::convert<Vector3>(value)); } else if (key == "editor_light") { setIsLight(value == "1"); } else if (key == "spawnclass") { setIsLight(value == "idLight"); } else if (boost::algorithm::istarts_with(key, "editor_")) { parseEditorSpawnarg(key, value); } // Try parsing this key/value with the Attachments manager _attachments->parseDefAttachKeys(key, value); // Add the EntityClassAttribute for this key/val if (getAttribute(key).getType().empty()) { // Following key-specific processing, add the keyvalue to the eclass EntityClassAttribute attribute("text", key, value, ""); // Type is empty, attribute does not exist, add it. addAttribute(attribute); } else if (getAttribute(key).getValue().empty()) { // Attribute type is set, but value is empty, set the value. getAttribute(key).setValue(value); } else { // Both type and value are not empty, emit a warning rWarning() << "[eclassmgr] attribute " << key << " already set on entityclass " << _name << std::endl; } } // while true _attachments->validateAttachments(); // Notify the observers _changedSignal.emit(); }
static const attribute attribute_at( std::size_t index ) { assert( !"should not happen" ); return attribute(); }
QString Source::url() const { return attribute(QStringLiteral("url")); }
AIXMLLindenGenepool::AIXMLLindenGenepool(LLFILE* fp) : AIXMLRootElement(fp, "linden_genepool") { attribute("version", "1.0"); attribute("metaversion", "1.0"); child(MetaData(gHippoGridManager->getConnectedGrid()->getGridNick(), LLDate::now())); }