Example #1
0
void CastingPlatform<TSubClass, issueError>::issueCastError(const Item &validationError,
                                                            const Item &sourceValue,
                                                            const ReportContext::Ptr &context) const
{
    Q_ASSERT(validationError);
    Q_ASSERT(context);
    Q_ASSERT(validationError.isAtomicValue());
    Q_ASSERT(validationError.template as<AtomicValue>()->hasError());

    const ValidationError::Ptr err(validationError.template as<ValidationError>());
    QString msg(err->message());

    if(msg.isNull())
    {
        msg = QtXmlPatterns::tr("It's not possible to cast the value %1 of type %2 to %3")
                 .arg(formatData(sourceValue.stringValue()))
                 .arg(formatType(context->namePool(), sourceValue.type()))
                 .arg(formatType(context->namePool(), targetType()));
    }
    else
    {
        Q_ASSERT(!msg.isEmpty());
        msg = QtXmlPatterns::tr("Failure when casting from %1 to %2: %3")
                 .arg(formatType(context->namePool(), sourceValue.type()))
                 .arg(formatType(context->namePool(), targetType()))
                 .arg(msg);
    }

    /* If m_errorCode is FORG0001, we assume our sub-classer doesn't have a
     * special wish about error code, so then we use the error object's code.
     */
    context->error(msg, m_errorCode == ReportContext::FORG0001 ? err->errorCode() : m_errorCode,
                   static_cast<const TSubClass*>(this));
}
Example #2
0
bool Item::operator<(const Item & other) const {
    if (m_type != other.type())
        return m_type < other.type();

    const QString first(data(Qt::DisplayRole).toString().toLower());
    const QString second(other.data(Qt::DisplayRole).toString().toLower());
    return first.localeAwareCompare(second) < 0;
}
bool CategoryItem::operator<(const Item &other) const {
    if (other.type() != ITEM_CATEGORY) {
        return ITEM_CATEGORY < other.type();
    }
    const CategoryItem &o(static_cast<const CategoryItem &>(other));
    if (m_category   == CSwordModuleInfo::UnknownCategory) return false;
    if (o.m_category == CSwordModuleInfo::UnknownCategory) return true;
    return m_category < o.m_category;
}
Example #4
0
void Panel::expanded(const QModelIndex &index)
{
  if (!index.isValid()) return;
  // Save state (expanded/collapsed) of External Links root node and
  // of Interwiki root node.
  QSettings settings;
  Item *item = static_cast<Item*>(index.internalPointer());
  if (item->type() == Item::ExternalLinksRoot)
    settings.setValue("externalLinksExpanded", true);
  else if  (item->type() == Item::InterwikiRoot)
    settings.setValue("interwikiExpanded", true);
}
Example #5
0
PoopSeq::PoopSeq( VMachine* vm, const Item &iobj ):
   m_mark( vm->generation() ),
   m_vm( vm )
{
   switch( iobj.type() )
   {
   case FLC_ITEM_OBJECT:
      if( ! iobj.asObjectSafe()->getMethod( "append", m_appendMth ) )
      {
         throw new CodeError( ErrorParam( e_miss_iface, __LINE__ )
              .origin( e_orig_runtime )
              .extra( "append") );
      }
      break;

   case FLC_ITEM_DICT:
      if( ! iobj.asDict()->getMethod( "append", m_appendMth ) )
      {
         throw new CodeError( ErrorParam( e_miss_iface, __LINE__ )
              .origin( e_orig_runtime )
              .extra( "append") );
      }
      break;

   default:
      throw new ParamError( ErrorParam( e_inv_params, __LINE__ )
           .origin( e_orig_runtime )
           .extra( "O|D" ) );
   }
}
Example #6
0
void MainWindow::on_buttonMusic_clicked()
{
    if (soundEngine.isPlayingMusic())
    {
        if (soundEngine.isMusicPaused())
        {
            timer->start();
            soundEngine.resumeMusic();
            buttonMusic->setText(QApplication::translate("mainWindow","&Pause",0));
        }
        else
        {
            timer->stop();
            soundEngine.pauseMusic();
            buttonMusic->setText(QApplication::translate("mainWindow","&Resume",0));
        }
    }
    else
    {
        // we play the selected song (if it is a sound item)
        QTreeWidgetItem *qItem = treeMusic->currentItem();
        if (qItem != NULL)
        {
            Item *item = dynamic_cast<QCustomTreeWidgetItem*>(qItem)->branch()->item();
            if (item->type()==Item::tSound)
            {
                SoundItem *sItem = dynamic_cast<SoundItem*>(item);
                playMusic(sItem->fileName(),sItem->duration());
            }
        }
        timer->start();
    }
}
Example #7
0
bool Item::methodize( const Item &self )
{
   Item *data = dereference();

   switch( data->type() )
   {
      case FLC_ITEM_FUNC:
      {
         data->setMethod( self, data->asFunction() );
      }
      return true;

      case FLC_ITEM_ARRAY:
      {
         CoreArray& arr = *asArray();
         // even if arr[0] is not an array, the check is harmless, as we check by ptr value.
         if ( arr.canBeMethod() && arr.length() > 0 && arr[0].asArray() != &arr && arr[0].isCallable() )
         {
            data->setMethod( self, &arr );
            return true;
         }
      }
      return false;
   }

   return false;
}
Example #8
0
Item GenericPredicate::mapToItem(const Item &item,
                                 const DynamicContext::Ptr &context) const
{
    const Item::Iterator::Ptr it(m_operand2->evaluateSequence(context));
    const Item pcateItem(it->next());

    if(!pcateItem)
        return Item(); /* The predicate evaluated to the empty sequence */
    else if(pcateItem.isNode())
        return item;
    /* Ok, now it must be an AtomicValue */
    else if(BuiltinTypes::numeric->xdtTypeMatches(pcateItem.type()))
    { /* It's a positional predicate. */
        if(it->next())
        {
            context->error(QtXmlPatterns::tr("A positional predicate must "
                                             "evaluate to a single numeric "
                                             "value."),
                              ReportContext::FORG0006, this);
            return Item();
        }

        if(Double::isEqual(static_cast<xsDouble>(context->contextPosition()),
                           pcateItem.as<Numeric>()->toDouble()))
        {
            return item;
        }
        else
            return Item();
    }
    else if(Boolean::evaluateEBV(pcateItem, it, context)) /* It's a truth predicate. */
        return item;
    else
        return Item();
}
Example #9
0
	bool ActorInventory::equip(int id, int count) {
		DASSERT(isValidId(id) && count > 0);

		Item item = m_entries[id].item;
		ItemType::Type type = item.type();
		if((type != ItemType::weapon && type != ItemType::armour && type != ItemType::ammo) || !count)
			return false;
		if(type == ItemType::ammo && m_weapon.proto().ammo_class_id != Ammo(item).classId())
			return false;

		Entry old_ammo = m_ammo;
		unequip(type);

		if(type == ItemType::ammo) {
			if(old_ammo.item == item)
				count += old_ammo.count;
			count = min(count, m_weapon.maxAmmo());
		}
		else
			count = min(count, 1);
		count = min(count, m_entries[id].count);

		remove(id, count);

		if(type == ItemType::weapon)
			m_weapon = item;
		else if(type == ItemType::armour)
			m_armour = item;
		else if(type == ItemType::ammo) {
			m_ammo.item = item;
			m_ammo.count = count;
		}

		return true;
	}
Example #10
0
Item CastingPlatform<TSubClass, issueError>::cast(const Item &sourceValue,
                                                  const ReportContext::Ptr &context) const
{
    Q_ASSERT(sourceValue);
    Q_ASSERT(context);
    Q_ASSERT(targetType());

    if(m_caster)
        return castWithCaster(sourceValue, m_caster, context);
    else
    {
        bool castImpossible = false;
        const AtomicCaster::Ptr caster(locateCaster(sourceValue.type(), context, castImpossible, static_cast<const TSubClass *>(this), targetType()));

        if(!issueError && castImpossible)
        {
            /* If we're supposed to issue an error(issueError) then this
             * line will never be reached, because locateCaster() will in
             * that case throw. */
            return ValidationError::createError();
        }
        else
            return castWithCaster(sourceValue, caster, context);
    }
}
Example #11
0
bool DisplayList::shouldDumpForFlags(AsTextFlags flags, const Item& item)
{
    switch (item.type()) {
    case ItemType::SetState:
        if (!(flags & AsTextFlag::IncludesPlatformOperations)) {
            const auto& stateItem = downcast<SetState>(item);
            // FIXME: for now, only drop the item if the only state-change flags are platform-specific.
            if (stateItem.state().m_changeFlags == GraphicsContextState::ShouldSubpixelQuantizeFontsChange)
                return false;

            if (stateItem.state().m_changeFlags == GraphicsContextState::ShouldSubpixelQuantizeFontsChange)
                return false;
        }
        break;
#if USE(CG)
    case ItemType::ApplyFillPattern:
    case ItemType::ApplyStrokePattern:
        if (!(flags & AsTextFlag::IncludesPlatformOperations))
            return false;
        break;
#endif
    default:
        break;
    }
    return true;
}
Example #12
0
/*#
   @class Semaphore
   @brief Simple coroutine synchronization device.
   @ingroup coroutine_support
   @optparam initValue Initial value for the semaphore; if not given, 0 will be assumed.

   The semaphore is a simple synchronization object that is used by coroutines to
   communicate each others about relevant changes in the status of the application.

   Decrements the value of the semaphore, and eventually waits for the value to be > 0.
   When a @a Semaphore.wait method is called on a semaphore, two things may happen:
   if the value of the semaphore is greater than zero, the value is decremented and the
   coroutine can proceed. If it's zero, the coroutine is swapped out until the
   semaphore gets greater than zero again. When this happens, the coroutine
   decrements the value of the semaphore and proceeds. If a timeout parameter is given,
   in case the semaphore wasn't posted before the given timeout the function will return
   false.

   The order by which coroutines are resumed is the same by which they asked
   to wait on a semaphore. In this sense, @a Semaphore.wait method is implemented as a fair
   wait routine.

   The @a Semaphore.post method will raise the count of the semaphore by the given parameter
   (1 is the default if the parameter is not given). However, the calling coroutine
   won't necessarily be swapped out until a @a yield is called.

   By default, the semaphore is initialized to zero; this means that the
   first wait will block the waiting coroutine, unless a @a Semaphore.post
   is issued first.
*/
FALCON_FUNC  Semaphore_init ( ::Falcon::VMachine *vm )
{
   Item *qty = vm->param(0);
   int32 value = 0;
   if ( qty != 0 ) {
      if ( qty->type() == FLC_ITEM_INT )
         value = (int32) qty->asInteger();
      else if ( qty->type() == FLC_ITEM_NUM )
         value = (int32) qty->asNumeric();
      else {
         throw new ParamError( ErrorParam( e_param_range ).extra( "( N )" ) );
      }
   }

   VMSemaphore *sem = new VMSemaphore( value );
   vm->self().asObject()->setUserData( sem );
}
Example #13
0
void Panel::activated(const QModelIndex &index)
{
  if (!index.isValid()) return;
  Item *item = static_cast<Item*>(index.internalPointer());
  if (item->type() == Item::ExternalLink && _urlOpeningAllowed)
  {
    static_cast<ExternalLinkItem*>(item)->openUrl();

    // Protection from double-click activation.
    // We do not want a link to be opened twice when user
    // double-clicks.
    _urlOpeningAllowed = false;
    QTimer::singleShot(3000, this, SLOT(allowOpeningUrl()));
  }
  else if  (item->type() == Item::InternalLink)
    emit localLinkClicked(static_cast<InternalLinkItem*>(item)->link());
}
Example #14
0
bool ComparisonPlatform<TSubClass, issueError, comparisonType, errorCode>::
flexibleCompare(const Item &it1,
                const Item &it2,
                const DynamicContext::Ptr &context) const
{
    if(m_comparator)
        /* The comparator was located at compile time. */
        return compare(it1, it2, m_comparator, operatorID());
    else
    {
        const AtomicComparator::Ptr cp(fetchComparator(it1.type(),
                                                       it2.type(),
                                                       context));

        return cp ? compare(it1, it2, cp, operatorID()) : false;
    }
}
bool ItemReaderASTVisitor::visit(AST::UiObjectDefinition *ast)
{
    const QString typeName = ast->qualifiedTypeNameId->name.toString();
    Item *item = Item::create(m_itemPool);
    item->setFile(m_file);
    item->setTypeName(typeName);
    item->setLocation(toCodeLocation(ast->qualifiedTypeNameId->identifierToken));

    if (m_item)
        Item::addChild(m_item, item); // Add this item to the children of the parent item.
    else
        m_item = item; // This is the root item.

    const Item *inheritorItem = nullptr;

    // Inheritance resolving, part 1: Find out our actual type name (needed for setting
    // up children and alternatives).
    const QStringList fullTypeName = toStringList(ast->qualifiedTypeNameId);
    const QString baseTypeFileName = m_typeNameToFile.value(fullTypeName);
    if (!baseTypeFileName.isEmpty()) {
        inheritorItem = m_visitorState.readFile(baseTypeFileName, m_file->searchPaths(),
                                                m_itemPool);
        QBS_CHECK(inheritorItem->type() <= ItemType::LastActualItem);
        item->setType(inheritorItem->type());
    } else {
        item->setType(BuiltinDeclarations::instance().typeForName(typeName));
        if (item->type() == ItemType::Properties && item->parent()
                && item->parent()->type() == ItemType::SubProject) {
            item->setType(ItemType::PropertiesInSubProject);
        }
    }

    if (ast->initializer) {
        qSwap(m_item, item);
        ast->initializer->accept(this);
        qSwap(m_item, item);
    }

    ASTPropertiesItemHandler(item).handlePropertiesItems();

    // Inheritance resolving, part 2 (depends on alternatives having been set up).
    if (inheritorItem) {
        inheritItem(item, inheritorItem);
        if (inheritorItem->file()->idScope()) {
            // Make ids from the derived file visible in the base file.
            // ### Do we want to turn off this feature? It's QMLish but kind of strange.
            item->file()->ensureIdScope(m_itemPool);
            inheritorItem->file()->idScope()->setPrototype(item->file()->idScope());
        }
    } else {
        // Only the item at the top of the inheritance chain is a built-in item.
        // We cannot do this in "part 1", because then the visitor would complain about duplicate
        // bindings.
        item->setupForBuiltinType(m_logger);
    }

    return false;
}
void QCustomTreeWidgetItem::updateDisplay()
{
    Item *item = pBranch->item();
    setText(0,item->content().c_str());
    setIcon(1,QCustomTreeWidget::icon(item->state()));
    if (item->type()==Item::tSound)
    {
        setIcon(0,QIcon(":/data/images/speaker.svg"));
        setToolTip(0,dynamic_cast<SoundItem*>(item)->fileName().c_str()); 
        setStatusTip(0,QApplication::translate("customTree","Double click to play the file",0));
    }
    else if (item->type()==Item::tImage)
    {
        setIcon(0,QIcon(":/data/images/image.svg"));
        setToolTip(0,dynamic_cast<ImageItem*>(item)->fileName().c_str()); 
        setStatusTip(0,QApplication::translate("customTree","Double click to show the file",0));
    }
}
bool BtBookshelfTreeModel::setData(const QModelIndex & itemIndex,
                                   const QVariant & value,
                                   int role) {
    Q_ASSERT(itemIndex.isValid());
    typedef QPair<Item *, QModelIndex> IP;

    if (UNLIKELY(role != Qt::CheckStateRole))
        return false;

    bool ok;
    Qt::CheckState newState = static_cast<Qt::CheckState>(value.toInt(&ok));
    if (UNLIKELY(!ok))
        return false;

    // Handle partially checked as checked here in setData():
    if (newState == Qt::PartiallyChecked)
        newState = Qt::Checked;

    Item * item = static_cast<Item *>(itemIndex.internalPointer());
    Q_ASSERT(item != 0);
    if (item->checkState() == newState) return false;

    // Recursively (un)check all children:
    QList<IP> q;
    IP p(item, itemIndex);
    for (;;) {
        if (item->checkState() != newState) {
            item->setCheckState(newState);
            emit dataChanged(p.second, p.second);
            if (item->type() == Item::ITEM_MODULE) {
                ModuleItem & mItem = *static_cast<ModuleItem *>(item);
                CSwordModuleInfo & mInfo = mItem.moduleInfo();
                if (newState == Qt::Checked) {
                    m_checkedModulesCache.insert(&mInfo);
                    emit moduleChecked(&mInfo, true);
                } else {
                    m_checkedModulesCache.remove(&mInfo);
                    emit moduleChecked(&mInfo, false);
                }
            } else {
                const QList<Item *> & children = item->children();
                for (int i = 0; i < children.size(); i++)
                    q.append(IP(children.at(i), index(i, 0, p.second)));
            }
        }
        if (q.empty())
            break;
        p = q.takeFirst();
        item = p.first;
    }

    // Recursively change parent check states.
    resetParentCheckStates(itemIndex.parent());

    return true;
}
Example #18
0
/*#
   @method post Semaphore
   @brief Increments the count of the semaphore.
   @optparam count The amount by which the semaphore will be incremented (1 by default).

   This method will increment the count of the semaphore by 1 or by a specified amount,
   allowing the same number of waiting coroutines to proceed.

   However, the calling coroutine won't necessarily be swapped out until a @a yield is called.
*/
FALCON_FUNC  Semaphore_post ( ::Falcon::VMachine *vm )
{
   VMSemaphore *semaphore = dyncast< VMSemaphore *>(vm->self().asObject()->getFalconData());
   Item *qty = vm->param(0);
   int32 value = 1;
   if ( qty != 0 ) {
      if ( qty->type() == FLC_ITEM_INT )
         value = (int32)qty->asInteger();
      else if ( qty->type() == FLC_ITEM_NUM )
         value = (int32) qty->asNumeric();
      else {
         throw new ParamError( ErrorParam( e_inv_params ).extra( "( N )" ) );
      }
      if (value <= 0)
         value = 1;
   }

   semaphore->post( vm, value );
}
Example #19
0
bool AtomicType::itemMatches(const Item &item) const
{
    Q_ASSERT(item);
    if(item.isNode())
        return false;
    else
    {
        const SchemaType::Ptr t(static_cast<AtomicType *>(item.type().data()));
        return wxsTypeMatches(t);
    }
}
Example #20
0
bool Item::exactlyEqual( const Item& other ) const
{
   if ( type() != other.type() )
   {
      return false;
   }

   switch( type() )
   {
      case FLC_ITEM_NIL: case FLC_ITEM_UNB:
         return true;
      
      case FLC_ITEM_INT:
         return asInteger() == other.asInteger();
      
      case FLC_ITEM_NUM:
         return asNumeric() == other.asNumeric();
         
      case FLC_ITEM_RANGE:
         if( asRangeIsOpen() != other.asRangeIsOpen() )
            return false;
         if ( asRangeStart() != other.asRangeStart() )
            return false;
         if ( asRangeStep() != other.asRangeStep() )
            return false;
         if ( ! asRangeIsOpen() &&
            (asRangeEnd() != other.asRangeEnd() ) )
            return false;
         return true;
      
      case FLC_ITEM_STRING:
         return *asString() == *other.asString();
      
      case FLC_ITEM_METHOD:
         if ( asMethodFunc() == other.asMethodFunc() )
         {
            return asMethodItem().exactlyEqual(other.asMethodItem() );
         } 
         return false;
      
      case FLC_ITEM_CLSMETHOD:
         if ( asObjectSafe()  != other.asObjectSafe() )
            return false;
         // fallthrough
         
      case FLC_ITEM_FUNC:
      case FLC_ITEM_CLASS:
         return asClass() == other.asClass();
   }
   
   // the default is to check for the voidp element in data
   return asObjectSafe() == other.asObjectSafe(); 
}
Example #21
0
AtomicComparator::ComparisonResult
ComparisonPlatform<TSubClass, issueError, comparisonType, errorCode>::
detailedFlexibleCompare(const Item &it1,
                        const Item &it2,
                        const DynamicContext::Ptr &context) const
{
    AtomicComparator::Ptr comp;

    if(m_comparator)
        comp = m_comparator;
    else
    {
        comp = fetchComparator(it1.type(),
                               it2.type(),
                               context);
    }

    Q_ASSERT_X(operatorID() == AtomicComparator::OperatorLessThanNaNLeast || operatorID() == AtomicComparator::OperatorLessThanNaNGreatest,
               Q_FUNC_INFO, "Only OperatorLessThan is currently supported for this function.");
    return comp->compare(it1, operatorID(), it2);
}
Item::Iterator::Ptr ArgumentConverter::mapToSequence(const Item &item,
                                                     const DynamicContext::Ptr &context) const
{
    if(item.isAtomicValue() && !BuiltinTypes::xsUntypedAtomic->xdtTypeMatches(item.type()))
        return makeSingletonIterator(item);
    else
    {
        /* We're using UntypedAtomicConverter::mapToItem(). */
        return makeItemMappingIterator<Item>(ConstPtr(this),
                                             item.sequencedTypedValue(),
                                             context);
    }
}
Example #23
0
inline Item
ComparingAggregator<oper, result>::applyNumericPromotion(const Item &old,
                                                         const Item &nev,
                                                         const Item &newVal) const
{
    Q_ASSERT(old);
    Q_ASSERT(nev);
    Q_ASSERT(newVal);
    const ItemType::Ptr to(old.type());
    const ItemType::Ptr tn(nev.type());

    if(!(BuiltinTypes::numeric->xdtTypeMatches(to) && BuiltinTypes::numeric->xdtTypeMatches(tn)))
        return newVal; /* At least one of them isn't numeric. */
    else if(BuiltinTypes::xsDouble->xdtTypeMatches(to) || BuiltinTypes::xsDouble->xdtTypeMatches(tn))
        return toItem(Double::fromValue(newVal.as<Numeric>()->toDouble()));
    else if(BuiltinTypes::xsFloat->xdtTypeMatches(to) || BuiltinTypes::xsFloat->xdtTypeMatches(tn))
        return toItem(Float::fromValue(newVal.as<Numeric>()->toDouble()));
    else if(BuiltinTypes::xsInteger->xdtTypeMatches(to) &&
            BuiltinTypes::xsInteger->xdtTypeMatches(tn))
        return newVal; /* Both must be xs:integer. */
    else
        return toItem(Decimal::fromValue(newVal.as<Numeric>()->toDecimal()));
}
Example #24
0
void QCustomTreeWidget::launchItem(QTreeWidgetItem *qItem)
{
    Item *item = dynamic_cast<QCustomTreeWidgetItem*>(qItem)->branch()->item();
    switch (item->type())
    {
        case Item::tSound:  {
                                SoundItem *soundItem = dynamic_cast<SoundItem*>(item);
                                // we send a signal to play the music (and do some other things)
                                emit fileToPlay(soundItem->fileName(),soundItem->duration());
                                break;
                            }
        case Item::tImage: {
                                ImageItem *imageItem = dynamic_cast<ImageItem*>(item);
                                new ImageWindow(imageItem->fileName(),this);
                                break;
                             }
        default:            break;
    }
}
Example #25
0
size_t Item::sizeInBytes(const Item& item)
{
    switch (item.type()) {
    case ItemType::Save:
        return sizeof(downcast<Save>(item));
    case ItemType::Restore:
        return sizeof(downcast<Restore>(item));
    case ItemType::Translate:
        return sizeof(downcast<Translate>(item));
    case ItemType::Rotate:
        return sizeof(downcast<Rotate>(item));
    case ItemType::Scale:
        return sizeof(downcast<Scale>(item));
    case ItemType::ConcatenateCTM:
        return sizeof(downcast<ConcatenateCTM>(item));
    case ItemType::SetState:
        return sizeof(downcast<SetState>(item));
    case ItemType::SetLineCap:
        return sizeof(downcast<SetLineCap>(item));
    case ItemType::SetLineDash:
        return sizeof(downcast<SetLineDash>(item));
    case ItemType::SetLineJoin:
        return sizeof(downcast<SetLineJoin>(item));
    case ItemType::SetMiterLimit:
        return sizeof(downcast<SetMiterLimit>(item));
    case ItemType::ClearShadow:
        return sizeof(downcast<ClearShadow>(item));
    case ItemType::Clip:
        return sizeof(downcast<Clip>(item));
    case ItemType::ClipOut:
        return sizeof(downcast<ClipOut>(item));
    case ItemType::ClipOutToPath:
        return sizeof(downcast<ClipOutToPath>(item));
    case ItemType::ClipPath:
        return sizeof(downcast<ClipPath>(item));
    case ItemType::DrawGlyphs:
        return sizeof(downcast<DrawGlyphs>(item));
    case ItemType::DrawImage:
        return sizeof(downcast<DrawImage>(item));
    case ItemType::DrawTiledImage:
        return sizeof(downcast<DrawTiledImage>(item));
    case ItemType::DrawTiledScaledImage:
        return sizeof(downcast<DrawTiledScaledImage>(item));
#if USE(CG) || USE(CAIRO)
    case ItemType::DrawNativeImage:
        return sizeof(downcast<DrawNativeImage>(item));
#endif
    case ItemType::DrawPattern:
        return sizeof(downcast<DrawPattern>(item));
    case ItemType::DrawRect:
        return sizeof(downcast<DrawRect>(item));
    case ItemType::DrawLine:
        return sizeof(downcast<DrawLine>(item));
    case ItemType::DrawLinesForText:
        return sizeof(downcast<DrawLinesForText>(item));
    case ItemType::DrawLineForDocumentMarker:
        return sizeof(downcast<DrawLineForDocumentMarker>(item));
    case ItemType::DrawEllipse:
        return sizeof(downcast<DrawEllipse>(item));
    case ItemType::DrawPath:
        return sizeof(downcast<DrawPath>(item));
    case ItemType::DrawFocusRingPath:
        return sizeof(downcast<DrawFocusRingPath>(item));
    case ItemType::DrawFocusRingRects:
        return sizeof(downcast<DrawFocusRingRects>(item));
    case ItemType::FillRect:
        return sizeof(downcast<FillRect>(item));
    case ItemType::FillRectWithColor:
        return sizeof(downcast<FillRectWithColor>(item));
    case ItemType::FillRectWithGradient:
        return sizeof(downcast<FillRectWithGradient>(item));
    case ItemType::FillCompositedRect:
        return sizeof(downcast<FillCompositedRect>(item));
    case ItemType::FillRoundedRect:
        return sizeof(downcast<FillRoundedRect>(item));
    case ItemType::FillRectWithRoundedHole:
        return sizeof(downcast<FillRectWithRoundedHole>(item));
    case ItemType::FillPath:
        return sizeof(downcast<FillPath>(item));
    case ItemType::FillEllipse:
        return sizeof(downcast<FillEllipse>(item));
    case ItemType::StrokeRect:
        return sizeof(downcast<StrokeRect>(item));
    case ItemType::StrokePath:
        return sizeof(downcast<StrokePath>(item));
    case ItemType::StrokeEllipse:
        return sizeof(downcast<StrokeEllipse>(item));
    case ItemType::ClearRect:
        return sizeof(downcast<ClearRect>(item));
    case ItemType::BeginTransparencyLayer:
        return sizeof(downcast<BeginTransparencyLayer>(item));
    case ItemType::EndTransparencyLayer:
        return sizeof(downcast<EndTransparencyLayer>(item));
#if USE(CG)
    case ItemType::ApplyStrokePattern:
        return sizeof(downcast<ApplyStrokePattern>(item));
    case ItemType::ApplyFillPattern:
        return sizeof(downcast<ApplyFillPattern>(item));
#endif
    case ItemType::ApplyDeviceScaleFactor:
        return sizeof(downcast<ApplyDeviceScaleFactor>(item));
    }
    return 0;
}
Example #26
0
void ResultSender::SendRecord(TempTable::RecordIterator& iter)		// send to MySQL
{
#ifdef PURE_LIBRARY
	BHERROR("NOT IMPLEMENTED! Depends on MySQL code.");
#else
	Item* item;
	Field* f;
	Item_field* ifield;
	Item_ref* iref;
	Item_sum* is;
	Item_sum_int_rcbase* isum_int_rcbase;
	Item_sum_sum_rcbase* isum_sum_rcbase;
	Item_sum_hybrid_rcbase*	isum_hybrid_rcbase;
	Item_sum::Sumfunctype sum_type;

	uint col_id = 0;
	int is_null;
	_int64 value;

	List_iterator_fast<Item> li(fields);
	li.rewind();
	while((item = li++)) {
		is_null = 0;
		RCDataType& rcdt((*iter)[col_id]);
		switch(item->type()) {
			case Item::DEFAULT_VALUE_ITEM:
			case Item::FIELD_ITEM:  // regular select
				ifield = (Item_field*)item;
				f = ifield->result_field;
				// if buf_lens[col_id] is 0 means that f->ptr was not assigned
				// because it was assigned for this instance of object
				if(buf_lens[col_id] != 0) {
					RCEngine::Convert(is_null, f, f->ptr, rcdt, NULL);
					SetFieldState(f, is_null);
				}
				break;
			case Item::REF_ITEM:	// select from view
				iref = (Item_ref*)item;
				ifield = (Item_field*)(*iref->ref);
				f = ifield->result_field;
				if(buf_lens[col_id] != 0) {
					RCEngine::Convert(is_null, f, f->ptr, rcdt, NULL);
					SetFieldState(f, is_null);
				}
				break;
			case Item::SUM_FUNC_ITEM:
				is = (Item_sum*)item;
				sum_type = is->sum_func();

				//used only MIN_FUNC
				if(sum_type == Item_sum::MIN_FUNC || sum_type == Item_sum::MAX_FUNC) {
					isum_hybrid_rcbase = (Item_sum_hybrid_rcbase*)is;
					enum_field_types is_field_type = isum_hybrid_rcbase->hybrid_field_type;
					if(isum_hybrid_rcbase->result_type() == DECIMAL_RESULT)	{
						RCEngine::Convert(is_null, isum_hybrid_rcbase->dec_value(), rcdt, item->decimals);
						//RCEngine::Convert(is_null, isum_hybrid_rcbase->dec_value(), &obj_item, item->decimals);
						isum_hybrid_rcbase->null_value = is_null;
					} else if(isum_hybrid_rcbase->result_type() == INT_RESULT) {
						RCEngine::Convert(is_null, isum_hybrid_rcbase->int64_value(), rcdt, is_field_type);
						isum_hybrid_rcbase->null_value = is_null;
					} else if(isum_hybrid_rcbase->result_type() == REAL_RESULT)	{
						RCEngine::Convert(is_null, isum_hybrid_rcbase->real_value(), rcdt);
						isum_hybrid_rcbase->null_value = is_null;
					} else if(isum_hybrid_rcbase->result_type() == STRING_RESULT) {
						RCEngine::Convert(is_null, isum_hybrid_rcbase->string_value(), rcdt, isum_hybrid_rcbase->hybrid_field_type);
						isum_hybrid_rcbase->null_value = is_null;
					}
					break;
				}
				//do not check COUNT_DISTINCT_FUNC, we use only this for both types
				if(sum_type == Item_sum::COUNT_FUNC || sum_type == Item_sum::SUM_BIT_FUNC) {
					isum_int_rcbase = (Item_sum_int_rcbase*)is;
					RCEngine::Convert(is_null, value, rcdt, is->field_type());
					if(is_null)
						value = 0;
					isum_int_rcbase->int64_value(value);
					break;
				}
				if(sum_type == Item_sum::SUM_FUNC || sum_type == Item_sum::STD_FUNC || sum_type == Item_sum::VARIANCE_FUNC) {
					isum_sum_rcbase = (Item_sum_sum_rcbase*)is;
					if(isum_sum_rcbase->result_type() == DECIMAL_RESULT) {
						RCEngine::Convert(is_null, isum_sum_rcbase->dec_value(), rcdt);
						isum_sum_rcbase->null_value = is_null;
					} else if(isum_sum_rcbase->result_type() == REAL_RESULT) {
						RCEngine::Convert(is_null, isum_sum_rcbase->real_value(), rcdt);
						isum_sum_rcbase->null_value = is_null;
					}
					break;
				}
				break;
			default:
				// Const items like item_int etc. do not need any conversion
				break;
		} // end switch
		col_id++;
	} // end while
	res->send_data(fields);
#endif
}
Example #27
0
Item
ComparingAggregator<oper, result>::evaluateSingleton(const DynamicContext::Ptr &context) const
{
    const Item::Iterator::Ptr it(m_operands.first()->evaluateSequence(context));
    Item largest;

    while(true)
    {
        Item next(it->next());

        if(!next)
        {
            return largest;
        }

        AtomicComparator::Ptr comp(comparator());

        if(!comp)
        {
            ItemType::Ptr t1(next.type());
            Q_ASSERT(t1);

            if(BuiltinTypes::xsUntypedAtomic->xdtTypeMatches(t1))
            {
                next = cast(next, context);
                t1 = BuiltinTypes::xsDouble;
            }

            if(!largest)
            {
                largest = next;
                continue;
            }

            Q_ASSERT(largest);
            comp = fetchComparator(largest.type(), t1, context);
            Q_ASSERT(comp);
        }
        else if(!largest)
        {
            largest = next;
            continue;
        }

        if(comp->compare(next, operatorID(), largest) == result)
        {
            largest = applyNumericPromotion(largest, next, next);
            continue;
        }

        const ItemType::Ptr t(next.type());

        if(BuiltinTypes::xsDouble->xdtTypeMatches(t) &&
           next.as<Numeric>()->isNaN())
        {
            return CommonValues::DoubleNaN;
        }
        else if(BuiltinTypes::xsFloat->xdtTypeMatches(t) &&
                next.as<Numeric>()->isNaN())
        {
            if(BuiltinTypes::xsDouble->xdtTypeMatches(largest.type()))
                return CommonValues::DoubleNaN;

            /* If we have a xs:double somewhere, we must promote the NaN value to xs:double,
             * and we really should raise error on invalid value. */
            largest = it->next();

            while(largest)
            {
                const ItemType::Ptr tf(largest.type());
                if(BuiltinTypes::xsDouble->xdtTypeMatches(tf))
                    return CommonValues::DoubleNaN;
                else if(BuiltinTypes::xsUntypedAtomic->xdtTypeMatches(tf))
                {
                    /* Attempt a convert, which will raise an error if it doesn't work out. */
                    cast(largest, context);
                    return CommonValues::DoubleNaN;
                }
                else if(!BuiltinTypes::numeric->xdtTypeMatches(tf))
                {
                    fetchComparator(BuiltinTypes::xsFloat, tf, context);
                }
                else
                    largest = it->next();
            };

            return CommonValues::FloatNaN;
        }
        else
            largest = applyNumericPromotion(largest, next, largest);
    }
}
Example #28
0
 static inline bool isNaN(const Item &i)
 {
     return BuiltinTypes::xsDouble->xdtTypeMatches(i.type()) &&
            i.as<Numeric>()->isNaN();
 }
Example #29
0
	void Container::setKey(const Item &key) {
		DASSERT(key.type() == ItemType::other);
		m_key = key;
	}
Example #30
0
bool Format::format( VMachine *vm, const Item &source, String &target )
{
   String sBuffer;

   switch( source.type() )
   {
      case FLC_ITEM_NIL:
         switch( m_nilFormat )
         {
            case e_nilEmpty: break;
            case e_nilNil: sBuffer = "Nil"; break;
            case e_nilN: sBuffer = "N"; break;
            case e_nilnil: sBuffer = "nil"; break;
            case e_nilNA: sBuffer = "N/A"; break;
            case e_nilNone: sBuffer = "None"; break;
            case e_nilNULL: sBuffer = "NULL"; break;
            case e_nilNull: sBuffer = "Null"; break;
            case e_nilPad: sBuffer.append( m_paddingChr );
         }
         applyPad( sBuffer );

      break;

      case FLC_ITEM_UNB:
         sBuffer = "_";
         applyPad( sBuffer );
         break;


      //==================================================
      // Parse an integer
      //
      case FLC_ITEM_INT:
      {
         int64 num = source.asInteger();

         // number formats are compatible with string formats
         if ( m_convType != e_tNum && m_convType != e_tStr )
         {
            return processMismatch( vm, source, target );
         }

         formatInt( num, sBuffer, true );

         // minus sign must be added AFTER padding with parentesis/fixed size or with *End signs,
         // else it must be added before.
         if ( negBeforePad() )
         {
            applyNeg( sBuffer, num );
            applyPad( sBuffer );
         }
         else {
            applyPad( sBuffer, negPadSize( num ) );
            applyNeg( sBuffer, num );
         }
      }
      break;

      //==================================================
      // Parse double format
      //
      case FLC_ITEM_NUM:
      {
         numeric num = source.asNumeric();

         // number formats are compatible with string formats
         if ( m_convType != e_tNum && m_convType != e_tStr )
         {
            return processMismatch( vm, source, target );
         }

         if( m_numFormat == e_scientific )
         {
           formatScientific( num, sBuffer );
         }
         else {
            double intPart, fractPart;
            bool bNeg, bIntIsZero;
            fractPart = modf( num, &intPart );
            if ( intPart < 0.0 ) {
               intPart = -intPart;
               fractPart = -fractPart;
               bNeg = true;
               bIntIsZero = false;
            }
            else
            {
               bIntIsZero = intPart > 0.0 ? false : true;

               if ( fractPart < 0.0 )
               {
                  fractPart = -fractPart;
                  // draw neg sign only if < 0 but int
                  bNeg = true;
               }
               else
                  bNeg = false;
            }



            String precPart;
            int base = 10;
            switch( m_numFormat )
            {
               case e_binary: case e_binaryB: base = 2; break;
               case e_octalZero: case e_octal: base = 8; break;
               case e_cHexUpper: case e_hexUpper: case e_cHexLower: case e_hexLower: base = 16; break;
               default:
                  break;
            }

            while( intPart > 9e14 )
            {
               intPart /= base;
               precPart.append( '0' );
            }

            // manual round
            if( (pow((double)10.0,-(m_decimals+1)) *5)+fractPart >=1.0)
            {
               intPart++;
               bIntIsZero = false;
            }

            uint8 decs = m_decimals;
            m_decimals = 0;


            formatInt( (int64) intPart, sBuffer, false );
            sBuffer.append( precPart );

            // now we can add the grouping
            if ( m_grouping > 0 )
            {
               String token;
               token.append( m_thousandSep );
               uint32 pos = sBuffer.size();

               while( pos > m_grouping )
               {
                  pos -= m_grouping;
                  sBuffer.insert( pos, 0, token );
               }
            }

            // finally add decimals
            m_decimals = decs;
            if( base == 10 && m_decimals > 0 )
            {

               char bufFmt[32];
               char buffer[255];
               sprintf( bufFmt, "%%.%df", m_decimals );
               sprintf( buffer, bufFmt, fractPart );
               sBuffer.append( m_decimalSep );
               sBuffer.append( buffer + 2 );
            }
            else if ( bIntIsZero )
            {
               // do not print -0!
               bNeg = false;
            }

            // we must fix the number.
            num = bNeg ? -1.0 : 1.0;
         }

         // minus sign must be added AFTER padding with parentesis/fixed size or with *End signs,
         // else it must be added before.
         if ( negBeforePad() )
         {
            applyNeg( sBuffer, (int64) num );
            applyPad( sBuffer );
         }
         else {
            applyPad( sBuffer, negPadSize( (int64) num ) );
            applyNeg( sBuffer, (int64) num );
         }
      }
      break;

      case FLC_ITEM_RANGE:
      {
         // number formats are compatible with string formats
         if ( m_convType != e_tNum && m_convType != e_tStr )
         {
            return processMismatch( vm, source, target );
         }

         int64 begin = source.asRangeStart();
         String sBuf1, sBuf2, sBuf3;

         formatInt( begin, sBuf1, true );

         //apply negative format now.
         applyNeg( sBuf1, (int64) begin );
         if ( ! source.asRangeIsOpen() )
         {
            int64 end = source.asRangeEnd();
            formatInt( end, sBuf2, true );
            applyNeg( sBuf2, (int64) end );
            
            int64 step = source.asRangeStep();
            if ( (begin <= end && step != 1) ||
                 (begin > end && step != -1 ) )
            {
               formatInt( step, sBuf3, true );
               applyNeg( sBuf3, (int64) step );
               sBuffer = "[" + sBuf1 + ":" + sBuf2 + ":" + sBuf3 + "]";
            }
            else
               sBuffer = "[" + sBuf1 + ":" + sBuf2 + "]";
         }
         else
            sBuffer = "[" + sBuf1 + ":" + sBuf2 + "]";

         applyPad( sBuffer );
      }
      break;

      case FLC_ITEM_STRING:
      {
         // number formats are compatible with string formats
         if ( m_convType != e_tStr )
         {
            return processMismatch( vm, source, target );
         }

         sBuffer = *source.asString();
         applyPad( sBuffer );
      }
      break;


      case FLC_ITEM_OBJECT:
      {
         // try to format the object
         if( vm != 0 )
         {
            if( m_posOfObjectFmt != String::npos )
            {
               vm->itemToString( sBuffer, &source, m_originalFormat.subString( m_posOfObjectFmt + 1 ) );
            }
            else {
               vm->itemToString( sBuffer, &source );
            }
         }
         else {
            return processMismatch( vm, source, target );
         }

         applyPad( sBuffer );
      }
      break;

      default:
         return processMismatch( vm, source, target );
   }

   // out of bounds?
   if ( m_size > 0 && m_fixedSize && sBuffer.length() > m_size ) {
      return false;
   }

   target += sBuffer;
   return true;
}