示例#1
0
/////////////////
// name:	response
// purpose:	tries to get a response from an npc standing around
// history:	heavily revamped/rewritten by Duke, Oct 2001
// remark:	The new logic tries to minimize the # of strstr() calls by *first* checking
//			what kind of npcs are standing around and then checking only those keywords
//			that they might be interested in.
//			This is especially usefull in crowded places.
bool Speech::response( cUOSocket* socket, P_PLAYER pPlayer, const QString& comm, QValueVector<Q_UINT16>& keywords )
{
	if ( !pPlayer->socket() || pPlayer->isDead() )
	{
		return false;
	}

	QString speechUpr = comm.upper();

	MapCharsIterator ri = MapObjects::instance()->listCharsInCircle( pPlayer->pos(), 18 );
	for ( P_CHAR pChar = ri.first(); pChar; pChar = ri.next() )
	{
		P_NPC pNpc = dynamic_cast<P_NPC>( pChar );

		// We will only process NPCs here
		if ( !pNpc )
			continue;

		// at least they should be on the screen
		if ( pPlayer->dist( pNpc ) > 16 )
			continue;

		if ( pNpc->canHandleEvent( EVENT_SPEECH ) )
		{
			PyObject* pkeywords = PyTuple_New( keywords.size() );

			// Set Items
			for ( unsigned int i = 0; i < keywords.size(); ++i )
				PyTuple_SetItem( pkeywords, i, PyInt_FromLong( keywords[i] ) );

			PyObject* args = Py_BuildValue( "(NNNO)", pNpc->getPyObject(), pPlayer->getPyObject(), QString2Python( comm ), pkeywords );

			bool result = pNpc->callEventHandler( EVENT_SPEECH, args );

			Py_DECREF( args );
			Py_DECREF( pkeywords );

			if ( result )
				return true;
		}

		if ( pNpc->ai() )
		{
			pNpc->ai()->onSpeechInput( pPlayer, speechUpr );
		}

		if ( QuestionSpeech( socket, pPlayer, pNpc, speechUpr ) )
			return true;
	}

	return false;
}
示例#2
0
void DocCHMPlugin::createTOC(DocumentationCatalogItem* item)
{
    QStringList lines = QStringList::split("\n", getSpecialData("catalog", item->url()) );
    if(lines.count() % 4 != 0) { kdDebug(9002) << "DocCHMPlugin::createTOC: wrong count of strings"; return;}
    
    QValueVector<DocumentationItem*> items;
    items.push_back(item);
    for(QStringList::Iterator it = lines.begin(); it != lines.end();) {
        bool ok1 = true, ok2 = true;
        int parent = (*it).toInt(&ok1);
        ++it;
        int current = (*it).toInt(&ok2);
        ++it;
        if(int(items.size()) != current || !ok1 || !ok2 || parent < 0 || parent >= int(items.size()) || current < 0 || current != int(items.size())) {
            kdDebug(9002) << "DocCHMPlugin::createTOC error while parsing output of ioslave" << endl;
            break;
        }
        
        QString& name(*it);
        ++it;
        KURL url(*it);
        ++it;
        
        items.push_back(new DocumentationItem(
                DocumentationItem::Document, items[parent], chainEnd(items[parent]), decodeHTML(name)));
        items[current]->setURL(url);
        if(parent != 0) items[parent]->setType(DocumentationItem::Book);
    }
    

    return;
}
示例#3
0
void KImportDialog::setData(uint row, uint col, const QString &value)
{
    QString val = value;
    val.replace("\\n", "\n");

    if(row >= mData.count())
    {
        mData.resize(row + 1);
    }

    QValueVector<QString> *rowVector = mData[ row ];
    if(!rowVector)
    {
        rowVector = new QValueVector<QString>;
        mData.insert(row, rowVector);
    }
    if(col >= rowVector->size())
    {
        rowVector->resize(col + 1);
    }

    KImportColumn *c = mColumnDict.find(col);
    if(c)
        rowVector->at(col) = c->preview(val, findFormat(col));
    else
        rowVector->at(col) = val;
}
示例#4
0
/**
 * Does spike-reduction on the given point-array's stack-top.
 *
 * Spikes are path segments of which one goes forward, and the sucessor
 * goes backward on the predecessor's segment:
 *
 * 2      0      1
 * x------x<-----x
 * (0 is stack-top in point-array)
 *
 * This will be reduced to
 * 1      0
 * x------x
 *
 * Preconditions:
 * - No other spikes exist in the whole point-array except at most
 *   one at the end
 * - No two succeeding points are ever equal
 * - For each two succeeding points either p1.x == p2.x or p1.y == p2.y holds
 *   true
 * - No such spike exists where 2 is situated between 0 and 1.
 *
 * Postcondition:
 * - No spikes exist in the whole point-array
 *
 * If no spike is found, the point-array is left unchanged.
 * @return \c true if an actual reduction was done
 */
inline static bool reduceSpike(QValueVector< QPoint > &pointArray)
{
    if(pointArray.size() < 3)
        return false;
    QValueVector< QPoint >::Iterator it = pointArray.end();
    QPoint p0 = *--it;
    QPoint p1 = *--it;
    QPoint p2 = *--it;

    bool elide = false;

    if((p0.x() == p1.x() && p1.x() == p2.x() && ((p1.y() < p0.y() && p0.y() < p2.y()) || (p2.y() < p0.y() && p0.y() < p1.y())
                                                || (p1.y() < p2.y() && p2.y() < p0.y()) || (p0.y() < p2.y() && p2.y() < p1.y())
                                                || (elide = p2.y() == p0.y() && p0.y() < p1.y()) || (elide = p1.y() < p0.y() && p0.y() == p2.y())))
       || (p0.y() == p1.y() && p1.y() == p2.y() && ((p1.x() < p0.x() && p0.x() < p2.x()) || (p2.x() < p0.x() && p0.x() < p1.x())
                                                   || (p1.x() < p2.x() && p2.x() < p0.x()) || (p0.x() < p2.x() && p2.x() < p1.x())
                                                   || (elide = p2.x() == p0.x() && p0.x() < p1.x()) || (elide = p1.x() < p0.x() && p0.x() == p2.x()))))
    {
        //     kdDebug(6040) << "spikered p2" << (elide ? " (elide)" : "") << ": " << p2 << " p1: " << p1 << " p0: " << p0 << endl;
        pointArray.pop_back();
        pointArray.pop_back();
        if(!elide)
            pointArray.push_back(p0);
        return true;
    }
    return false;
}
示例#5
0
void RenderInline::paintOutlines(QPainter *p, int _tx, int _ty)
{
    if(style()->outlineWidth() == 0 || style()->outlineStyle() <= BHIDDEN)
        return;
    int offset = style()->outlineOffset();

    // We may have to draw more than one outline path as they may be
    // disjoint.
    for(InlineRunBox *curr = firstLineBox(); curr; curr = curr->nextLineBox())
    {
        QValueVector< QPoint > path;

        // collect topmost outline
        collectHorizontalBoxCoordinates(curr, path, false, offset);
        // collect right outline
        collectVerticalBoxCoordinates(curr, path, false, offset, &curr);
        // collect bottommost outline
        collectHorizontalBoxCoordinates(curr, path, true, offset);
        // collect left outline
        collectVerticalBoxCoordinates(curr, path, true, offset);

        if(path.size() < 3)
            continue;

        const QPoint *begin = linkEndToBegin(path);

        // paint the outline
        paintOutlinePath(p, _tx, _ty, begin, path.end(), BSLeft, -1, BSTop);
    }
}
示例#6
0
Q_UINT16 DynTile( const Coord_cl& pos )
{
	RegionIterator4Items ri( pos );
	for ( ri.Begin(); !ri.atEnd(); ri++ )
	{
		P_ITEM mapitem = ri.GetData();
		if ( mapitem )
		{
			if ( mapitem->isMulti() )
			{
				MultiDefinition* def = MultiCache::instance()->getMulti( mapitem->id() - 0x4000 );
				if ( !def )
					return 0;
				QValueVector<multiItem_st> multi = def->getEntries();
				for ( Q_UINT32 j = 0; j < multi.size(); ++j )
				{
					if ( ( multi[j].visible && ( mapitem->pos().x + multi[j].x == pos.x ) && ( mapitem->pos().y + multi[j].y == pos.y ) && ( abs( mapitem->pos().z + multi[j].z - pos.z ) <= 1 ) ) )
					{
						return multi[j].tile;
					}
				}
			}
			else if ( mapitem->pos() == pos )
				return mapitem->id();
		}
	}
	return ( Q_UINT16 ) - 1;
}
示例#7
0
Q_UINT16 DynTile( const Coord& pos )
{
	MapItemsIterator ri = MapObjects::instance()->listItemsInCircle( pos, 18 );
	for ( P_ITEM mapitem = ri.first(); mapitem; mapitem = ri.next() )
	{
		if ( mapitem->isMulti() )
		{
			MultiDefinition* def = MultiCache::instance()->getMulti( mapitem->id() - 0x4000 );
			if ( !def )
				return 0;

			QValueVector<multiItem_st> multi = def->getEntries();
			for ( Q_UINT32 j = 0; j < multi.size(); ++j )
			{
				if ( ( multi[j].visible && ( mapitem->pos().x + multi[j].x == pos.x ) && ( mapitem->pos().y + multi[j].y == pos.y ) && ( abs( mapitem->pos().z + multi[j].z - pos.z ) <= 1 ) ) )
				{
					return multi[j].tile;
				}
			}
		}
		else if ( mapitem->pos() == pos )
		{
			return mapitem->id();
		}
	}
	return ( Q_UINT16 ) - 1;
}
示例#8
0
// The main method for dropping
KIO::CopyJob *KIO::pasteMimeSource(QMimeSource *data, const KURL &dest_url, const QString &dialogText, QWidget *widget, bool clipboard)
{
    QByteArray ba;

    // Now check for plain text
    // We don't want to display a mimetype choice for a QTextDrag, those mimetypes look ugly.
    QString text;
    if(QTextDrag::canDecode(data) && QTextDrag::decode(data, text))
    {
        QTextStream txtStream(ba, IO_WriteOnly);
        txtStream << text;
    }
    else
    {
        QValueVector< QCString > formats;
        const char *fmt;
        for(int i = 0; (fmt = data->format(i)); ++i)
        {
            if(qstrcmp(fmt, "application/x-qiconlist") == 0) // see QIconDrag
                continue;
            if(qstrcmp(fmt, "application/x-kde-cutselection") == 0) // see KonqDrag
                continue;
            if(strchr(fmt, '/') == 0) // e.g. TARGETS, MULTIPLE, TIMESTAMP
                continue;
            formats.append(fmt);
        }

        if(formats.size() == 0)
            return 0;

        if(formats.size() > 1)
        {
            return chooseAndPaste(dest_url, data, formats, dialogText, widget, clipboard);
        }
        ba = data->encodedData(formats.first());
    }
    if(ba.size() == 0)
    {
        KMessageBox::sorry(0, i18n("The clipboard is empty"));
        return 0;
    }

    return pasteDataAsync(dest_url, ba, dialogText);
}
void MultiDefinition::setItems( const QValueVector<multiItem_st>& items )
{
	// try to sort
	if ( items.empty() )
		return;
	unsigned int i = 0;
	for ( ; i < items.size(); ++i )
	{
		if ( items[i].x < left )
			left = items[i].x;
		else if ( items[i].x > right )
			right = items[i].x;

		if ( items[i].y < top )
			top = items[i].y;
		else if ( items[i].y > bottom )
			bottom = items[i].y;
	}

	// by now we have the dimensions.
	this->width = abs( right - left ) + 1;
	this->height = abs( bottom - top ) + 1;

	// copy into grid
	grid.resize( width * height );
	for ( i = 0; i < items.size(); ++i )
	{
		unsigned int index = ( items[i].y - top ) * width + ( items[i].x - left );
		if ( index < grid.size() )
		{
			grid[index].append( items[i] );
		}
	}

	entries = items;
}
示例#10
0
/*
	\method account.delete
	\description Removes this account and all characters attached to it.
*/
static PyObject* wpAccount_delete( wpAccount* self, PyObject* args )
{
	Q_UNUSED( args );
	if ( self->account == 0 )
		Py_RETURN_FALSE;

	QValueVector<P_PLAYER> chars = self->account->caracterList();
	for ( uint i = 0; i < chars.size(); ++i )
		chars[i]->remove();

	self->account->remove();
	self->account = 0;

	Py_RETURN_TRUE;
}
示例#11
0
void KImportDialog::fillTable()
{
    //  kdDebug(5300) << "KImportDialog::fillTable()" << endl;

    int row, column;

    for(row = 0; row < mTable->numRows(); ++row)
        for(column = 0; column < mTable->numCols(); ++column)
            mTable->clearCell(row, column);

    for(row = 0; row < int(mData.count()); ++row)
    {
        QValueVector<QString> *rowVector = mData[ row ];
        for(column = 0; column < int(rowVector->size()); ++column)
        {
            setCellText(row, column, rowVector->at(column));
        }
    }
}
示例#12
0
/**
 * Reduces segment separators.
 *
 * A segment separator separates a segment into two segments, thus causing
 * two adjacent segment with the same orientation.
 *
 * 2       1     0
 * x-------x---->x
 * (0 means stack-top)
 *
 * Here, 1 is a segment separator. As segment separators not only make
 * the line drawing algorithm inefficient, but also make the spike-reduction
 * fail, they must be eliminated:
 *
 * 1             0
 * x------------>x
 *
 * Preconditions:
 * - No other segment separators exist in the whole point-array except
 *   at most one at the end
 * - No two succeeding points are ever equal
 * - For each two succeeding points either p1.x == p2.x or p1.y == p2.y holds
 *   true
 * - No such spike exists where 2 is situated between 0 and 1.
 *
 * Postcondition:
 * - No segment separators exist in the whole point-array
 *
 * If no segment separator is found at the end of the point-array, it is
 * left unchanged.
 * @return \c true if a segment separator was actually reduced.
 */
inline static bool reduceSegmentSeparator(QValueVector< QPoint > &pointArray)
{
    if(pointArray.size() < 3)
        return false;
    QValueVector< QPoint >::Iterator it = pointArray.end();
    QPoint p0 = *--it;
    QPoint p1 = *--it;
    QPoint p2 = *--it;
    //     kdDebug(6040) << "checking p2: " << p2 << " p1: " << p1 << " p0: " << p0 << endl;

    if((p0.x() == p1.x() && p1.x() == p2.x() && ((p2.y() < p1.y() && p1.y() < p0.y()) || (p0.y() < p1.y() && p1.y() < p2.y())))
       || (p0.y() == p1.y() && p1.y() == p2.y() && ((p2.x() < p1.x() && p1.x() < p0.x()) || (p0.x() < p1.x() && p1.x() < p2.x()))))
    {
        //     kdDebug(6040) << "segred p2: " << p2 << " p1: " << p1 << " p0: " << p0 << endl;
        pointArray.pop_back();
        pointArray.pop_back();
        pointArray.push_back(p0);
        return true;
    }
    return false;
}
void MultiDefinition::setItems( QValueVector<multiItem_st> items )
{
	// try to sort
	if ( items.empty() )
		return;
	unsigned int i = 0;
	int max_X = 0, max_Y = 0, min_X = 0, min_Y = 0;
	for (; i < items.size(); ++i)
	{
		if ( items[max_X].x < items[i].x )
			max_X = i;
		if ( items[max_Y].y < items[i].y )
			max_Y = i;
		if ( items[min_X].x > items[i].x )
			min_X = i;
		if ( items[min_Y].y > items[i].y )
			min_Y = i;
	}

	// by now we have the dimensions.
	this->width  = items[max_X].x + abs(items[min_X].x);
	this->height = items[max_Y].y + abs(items[min_Y].y);
	entries = items;
}
示例#14
0
// The highest items will be @ the beginning
// While walking we always will try the highest first.
vector< stBlockItem > getBlockingItems( P_CHAR pChar, const Coord& pos )
{
	vector<stBlockItem> blockList;
	make_heap( blockList.begin(), blockList.end(), compareTiles() );

	// Process the map at that position
	stBlockItem mapBlock;
	mapBlock.maptile = true;
	mapBlock.z = Maps::instance()->mapAverageElevation( pos );
	mapBlock.height = 0;

	// TODO: Calculate the REAL average Z Value of that Map Tile here! Otherwise clients will have minor walking problems.
	map_st mapCell = Maps::instance()->seekMap( pos );
	//mapBlock.z = mapCell.z;
	land_st mapTile = TileCache::instance()->getLand( mapCell.id );

	// If it's not impassable it's automatically walkable
	if ( !( mapTile.flag1 & 0x40 ) )
		mapBlock.walkable = true;
	else
		mapBlock.walkable = checkWalkable( pChar, mapCell.id );

	if ( mapCell.id != 0x02 )
	{
		blockList.push_back( mapBlock );
		push_heap( blockList.begin(), blockList.end(), compareTiles() );
	}

	// Now for the static-items
	StaticsIterator staIter = Maps::instance()->staticsIterator( pos, true );
	for ( ; !staIter.atEnd(); ++staIter )
	{
		tile_st tTile = TileCache::instance()->getTile( staIter->itemid );

		// Here is decided if the tile is needed
		// It's uninteresting if it's NOT blocking
		// And NOT a bridge/surface
		if ( !( ( tTile.flag2 & 0x02 ) || ( tTile.flag1 & 0x40 ) || ( tTile.flag2 & 0x04 ) ) )
			continue;

		stBlockItem staticBlock;
		staticBlock.z = staIter->zoff;

		// If we are a surface we can always walk here, otherwise check if
		// we are special
		if ( ( tTile.flag2 & 0x02 ) && !( tTile.flag1 & 0x40 ) )
			staticBlock.walkable = true;
		else
			staticBlock.walkable = checkWalkable( pChar, staIter->itemid );

		// If we are a stair only the half height counts (round up)
		if ( tTile.flag2 & 0x04 )
			staticBlock.height = ( Q_UINT8 ) ( ( tTile.height ) / 2 );
		else
			staticBlock.height = tTile.height;

		blockList.push_back( staticBlock );
		push_heap( blockList.begin(), blockList.end(), compareTiles() );
	}

	// We are only interested in items at pos
	// todo: we could impliment blocking for items on the adjacent sides
	// during a diagonal move here, but this has yet to be decided.

	MapItemsIterator iIter = MapObjects::instance()->listItemsAtCoord( pos );
	for ( P_ITEM pItem = iIter.first(); pItem; pItem = iIter.next() )
	{
		if ( pChar && pChar->isDead() )
		{
			// Doors can be passed by ghosts
			if ( pItem->hasScript( "door" ) )
			{
				continue;
			}
		}

		tile_st tTile = TileCache::instance()->getTile( pItem->id() );

		// See above for what the flags mean
		if ( !( ( tTile.flag2 & 0x02 ) || ( tTile.flag1 & 0x40 ) || ( tTile.flag2 & 0x04 ) ) )
			continue;

		stBlockItem blockItem;
		blockItem.height = ( tTile.flag2 & 0x04 ) ? ( tTile.height / 2 ) : tTile.height;
		blockItem.z = pItem->pos().z;

		// Once again: see above for a description of this part
		if ( ( tTile.flag2 & 0x02 ) && !( tTile.flag1 & 0x40 ) )
			blockItem.walkable = true;
		else
			blockItem.walkable = checkWalkable( pChar, pItem->id() );

		blockList.push_back( blockItem );
		push_heap( blockList.begin(), blockList.end(), compareTiles() );
	}


	// deal with the multis now, or not.
	// 18 has been tested with castle sides and corners...
	MapMultisIterator iter = MapObjects::instance()->listMultisInCircle( pos, 18 );
	for ( cMulti*pMulti = iter.first(); pMulti; pMulti = iter.next() )
	{
		MultiDefinition* def = MultiCache::instance()->getMulti( pMulti->id() - 0x4000 );
		if ( !def )
			continue;

		QValueVector<multiItem_st> multi = def->getEntries();

		for ( unsigned int j = 0; j < multi.size(); ++j )
		{
			if ( multi[j].visible && ( pMulti->pos().x + multi[j].x == pos.x ) && ( pMulti->pos().y + multi[j].y == pos.y ) )
			{
				tile_st tTile = TileCache::instance()->getTile( multi[j].tile );
				if ( !( ( tTile.flag2 & 0x02 ) || ( tTile.flag1 & 0x40 ) || ( tTile.flag2 & 0x04 ) ) )
					continue;

				stBlockItem blockItem;
				blockItem.height = ( tTile.flag2 & 0x04 ) ? ( tTile.height / 2 ) : tTile.height;
				blockItem.z = pMulti->pos().z + multi[j].z;

				if ( ( tTile.flag2 & 0x02 ) && !( tTile.flag1 & 0x40 ) )
					blockItem.walkable = true;
				else
					blockItem.walkable = checkWalkable( pChar, pMulti->id() );

				blockList.push_back( blockItem );
				push_heap( blockList.begin(), blockList.end(), compareTiles() );
			}
		}
		continue;
	}

	// Now we need to evaluate dynamic items [...] (later)  ??
	sort_heap( blockList.begin(), blockList.end(), compareTiles() );

	return blockList;
};
示例#15
0
文件: SpawnSSH.cpp 项目: nixz/covise
SpawnSSH::SpawnSSH(RemoteRebootMaster *master,
                   const QString &localhostname, int localport,
                   const QString &hostname, const QString &user)

    : Spawn(master, localhostname, localport)
{

    QStringList inputList;

    QValueVector<QString> argv = master->getArgv();

    if (hostname == "")
    {
        if (argv.size() > 0)
        {
            this->hostname = argv[0];
        }
        else
        {
            inputList.append("Hostname");
            inputList.append("string");
            inputList.append("");
        }
    }
    else
    {
        this->hostname = hostname;
    }

    if (user == "")
    {
        if (argv.size() > 1)
        {
            this->user = argv[1];
        }
        else
        {
            inputList.append("User");
            inputList.append("string");
            inputList.append("");
        }
    }
    else
    {
        this->user = user;
    }

    if (!inputList.empty())
    {

        const QMap<QString, QString> result = master->getUI()->getUserInputs(inputList);

        if (result["Hostname"] != "")
        {
            this->hostname = result["Hostname"];
        }

        if (result["User"] != "")
        {
            this->user = result["User"];
        }
    }
}
示例#16
0
QValueVector<QColor> amaroK::readMood(const QString path)
{
	debug() << "MakeMood: Reading mood file " << path << endl;
	QString filebase = path;
	QValueVector<QColor> theArray;
	filebase.truncate(filebase.findRev('.'));
	filebase += ".mood";
	QString dotfilebase = filebase, homefilebase = filebase;
	dotfilebase.insert(filebase.findRev('/') + 1, '.');
	homefilebase.replace('/', ',');
	homefilebase = ::locateLocal("data", "amarok/moods/" + homefilebase);
	QFile mood;
	if(QFile::exists(filebase)) mood.setName(filebase);
	if(QFile::exists(dotfilebase)) mood.setName(dotfilebase);
	if(QFile::exists(homefilebase)) mood.setName(homefilebase);
	if(mood.name() != "" && mood.open(IO_ReadOnly))
	{
		int r, g, b, s = mood.size() / 3;
		debug() << "ReadMood: File opened. Proceeding to read contents... s=" << s << endl;
		QMemArray<int> huedist(360);
		int total = 0, mx = 0;
		for(int i = 0; i < 360; i++) huedist[i] = 0;
		theArray.resize(s);
		for(int i = 0; i < s; i++)
		{
			r = mood.getch();
			g = mood.getch();
			b = mood.getch();
			theArray[i] = QColor(CLAMP(0, r, 255), CLAMP(0, g, 255), CLAMP(0, b, 255), QColor::Rgb);
			int h, s, v;
			theArray[i].getHsv(&h, &s, &v);
			if(h < 0) h = 0; else h = h % 360;
			huedist[h]++;
			if(mx < huedist[h]) mx = huedist[h];
		}
		debug() << "ReadMood: File read. Maximum hue bin size = " <<  mx << endl;
		if(AmarokConfig::makeMoodier())
		{
			debug() << "ReadMood: Making moodier!" << endl;
			int threshold, rangeStart = 0, rangeDelta = 359, sat = 100, val = 100;
			switch(AmarokConfig::alterMood())
			{
				// Angry
				case 1: threshold = s / 360 * 9; rangeStart = 45; rangeDelta = -45; sat = 200; val = 100; break;
				// Frozen
				case 2: threshold = s / 360 * 1; rangeStart = 140; rangeDelta = 160; sat = 50; val = 100; break;
				// Happy
				default: threshold = s / 360 * 2; rangeStart = 0; rangeDelta = 359; sat = 150; val = 250;
			}
			debug() << "ReadMood: Appling filter t=" << threshold << ", rS=" << rangeStart << ", rD=" << rangeDelta << ", s=" << sat << "%, v=" << val << "%" << endl;
			for(int i = 0; i < 360; i++) if(huedist[i] > threshold) total++;
			debug() << "ReadMood: Total=" << total << endl;
			if(total < 360 && total > 0)
			{
				for(int i = 0, n = 0; i < 360; i++)
					huedist[i] = ((huedist[i] > threshold ? n++ : n) * rangeDelta / total + rangeStart) % 360;
				for(uint i = 0; i < theArray.size(); i++)
				{	int h, s, v;
					theArray[i].getHsv(&h, &s, &v);
					if(h < 0) h = 0; else h = h % 360;
					if(h > 359) debug() << "ReadMood: Bad hue in array[" << i << "]: " << h << endl;
					theArray[i].setHsv(CLAMP(0, huedist[h], 359), CLAMP(0, s * sat / 100, 255), CLAMP(0, v * val / 100, 255));
				}
			}
		}
	}
	debug() << "ReadMood: All done." << endl;
	return theArray;
}
示例#17
0
static PyObject* wpRegion_getAttr( wpRegion* self, char* name )
{
	/*
		\rproperty region.parent This property represents the parent region of this region. If there is no parent region this
		property contains None, otherwise another region object for the parent region.
	*/
	if ( !strcmp( name, "parent" ) )
	{
		// Check if valid region
		cTerritory* pRegion = dynamic_cast<cTerritory*>( self->pRegion->parent() );
		return PyGetRegionObject( pRegion );
	}
	/*
		\rproperty region.children This property contains a tuple of region objects for the subregions within this region.
	*/
	else if ( !strcmp( name, "children" ) )
	{
		QValueVector<cBaseRegion*> children = self->pRegion->children();
		PyObject* tuple = PyTuple_New( children.size() );
		for ( uint i = 0; i < children.size(); ++i )
		{
			cTerritory* pRegion = dynamic_cast<cTerritory*>( children[i] );
			PyTuple_SetItem( tuple, i, PyGetRegionObject( pRegion ) );
		}
		return tuple;
	}
	/*
		\rproperty region.rectangles This property is a tuple of tuples containing x1, y1, x2 and y2 for the rectangles that define
		the area of this region.
	*/
	else if ( !strcmp( name, "rectangles" ) )
	{
		QValueVector<cBaseRegion::rect_st> rectangles = self->pRegion->rectangles();
		PyObject* tuple = PyTuple_New( rectangles.size() );
		for ( uint i = 0; i < rectangles.size(); ++i )
		{
			PyObject* subtuple = PyTuple_New( 4 );
			PyTuple_SetItem( subtuple, 0, PyInt_FromLong( rectangles[i].x1 ) );
			PyTuple_SetItem( subtuple, 1, PyInt_FromLong( rectangles[i].y1 ) );
			PyTuple_SetItem( subtuple, 2, PyInt_FromLong( rectangles[i].x2 ) );
			PyTuple_SetItem( subtuple, 3, PyInt_FromLong( rectangles[i].y2 ) );

			PyTuple_SetItem( tuple, i, subtuple );
		}
		return tuple;
	}
	/*
		\rproperty region.name The name of this region.
	*/
	else if ( !strcmp( name, "name" ) )
		return QString2Python( self->pRegion->name() );
	/*
		\rproperty region.midilist A list of midi sounds to be played for this region.
	*/
	else if ( !strcmp( name, "midilist" ) )
		return QString2Python( self->pRegion->midilist() );
	/*
		\rproperty region.guardowner The name of the guardowner for this region.
	*/
	else if ( !strcmp( name, "guardowner" ) )
		return QString2Python( self->pRegion->guardOwner() );

	// Flags
	/*
		\rproperty region.guarded This boolean flag indicates whether the region is guarded or not.
	*/
	else if ( !strcmp( name, "guarded" ) )
		return PyInt_FromLong( self->pRegion->isGuarded() ? 1 : 0 );
	/*
		\rproperty region.nomark This boolean flag indicates whether runes aren't markable in this region or not.
	*/
	else if ( !strcmp( name, "nomark" ) )
		return PyInt_FromLong( self->pRegion->isNoMark() ? 1 : 0 );
	/*
		\rproperty region.nogate This boolean flag indicates whether gates in or out of this region are allowed.
	*/
	else if ( !strcmp( name, "nogate" ) )
		return PyInt_FromLong( self->pRegion->isNoGate() ? 1 : 0 );
	/*
		\rproperty region.norecallout This boolean flag indicates whether recalling out of this region is allowed.
	*/
	else if ( !strcmp( name, "norecallout" ) )
		return PyInt_FromLong( self->pRegion->isNoRecallOut() ? 1 : 0 );
	/*
		\rproperty region.norecallin This boolean flag indicates whether recalling into this region is allowed.
	*/
	else if ( !strcmp( name, "norecallin" ) )
		return PyInt_FromLong( self->pRegion->isNoRecallIn() ? 1 : 0 );
	/*
		\rproperty region.noagressivemagic This boolean flag indicates whether agressive magic is forbidden in this region or not.
	*/
	else if ( !strcmp( name, "noagressivemagic" ) )
		return PyInt_FromLong( self->pRegion->isNoAgressiveMagic() ? 1 : 0 );
	/*
		\rproperty region.noagressivemagic This boolean flag indicates whether magic is forbidden in this region or not.
	*/
	else if ( !strcmp( name, "antimagic" ) )
		return PyInt_FromLong( self->pRegion->isAntiMagic() ? 1 : 0 );
	/*
		\rproperty region.cave This boolean flag indicates that this region is underground.
	*/
	else if ( !strcmp( name, "cave" ) )
		return PyInt_FromLong( self->pRegion->isCave() ? 1 : 0 );
	/*
		\rproperty region.nomusic This boolean flag indicates that no music should be played in this region.
	*/
	else if ( !strcmp( name, "nomusic" ) )
		return PyInt_FromLong( self->pRegion->isNoMusic() ? 1 : 0 );
	/*
		\rproperty region.noguardmessage This boolean flag indicates that no guard message should show when entering this region..
	*/
	else if ( !strcmp( name, "noguardmessage" ) )
		return PyInt_FromLong( self->pRegion->isNoGuardMessage() ? 1 : 0 );
	/*
		\rproperty region.noentermessage This boolean flag indicates that no entrance message should show when entering this region.
	*/
	else if ( !strcmp( name, "noentermessage" ) )
		return PyInt_FromLong( self->pRegion->isNoEnterMessage() ? 1 : 0 );

	return Py_FindMethod( wpRegionMethods, ( PyObject * ) self, name );
}
示例#18
0
static PyObject *wpRegion_getAttr( wpRegion *self, char *name )
{
	if( !strcmp( name, "parent" ) )
	{
		// Check if valid region
		cTerritory *pRegion = dynamic_cast< cTerritory* >( self->pRegion->parent() );
		return PyGetRegionObject( pRegion );
	}
	else if( !strcmp( name, "children" ) )
	{
		QValueVector< cBaseRegion* > children = self->pRegion->children();
		PyObject *tuple = PyTuple_New( children.size() );
		for( uint i = 0; i < children.size(); ++i )
		{
			cTerritory *pRegion = dynamic_cast< cTerritory* >( children[i] );
			PyTuple_SetItem( tuple, i, PyGetRegionObject( pRegion ) );
		}
		return tuple;
	}
	// Return a Tuple of Tuples
	else if( !strcmp( name, "rectangles" ) )
	{
		QValueVector< cBaseRegion::rect_st > rectangles = self->pRegion->rectangles();
		PyObject *tuple = PyTuple_New( rectangles.size() );
		for( uint i = 0; i < rectangles.size(); ++i )
		{
			PyObject *subtuple = PyTuple_New( 4 );
			PyTuple_SetItem( subtuple, 0, PyInt_FromLong( rectangles[i].x1 ) );
			PyTuple_SetItem( subtuple, 1, PyInt_FromLong( rectangles[i].y1 ) );
			PyTuple_SetItem( subtuple, 2, PyInt_FromLong( rectangles[i].x2 ) );
			PyTuple_SetItem( subtuple, 3, PyInt_FromLong( rectangles[i].y2 ) );

			PyTuple_SetItem( tuple, i, subtuple );
		}
		return tuple;
	}
	else if( !strcmp( name, "name" ) )
		return QString2Python(self->pRegion->name());
	else if( !strcmp( name, "midilist" ) )
		return QString2Python(self->pRegion->midilist());
	else if( !strcmp( name, "guardowner" ) )
		return QString2Python(self->pRegion->guardOwner());
	else if( !strcmp( name, "rainchance" ) )
		return PyInt_FromLong( self->pRegion->rainChance() );
	else if( !strcmp( name, "snowchance" ) )
		return PyInt_FromLong( self->pRegion->snowChance() );

	// Flags
	else if( !strcmp( name, "guarded" ) )
		return PyInt_FromLong( self->pRegion->isGuarded() ? 1 : 0 );
	else if( !strcmp( name, "nomark" ) )
		return PyInt_FromLong( self->pRegion->isNoMark() ? 1 : 0 );
	else if( !strcmp( name, "nogate" ) )
		return PyInt_FromLong( self->pRegion->isNoGate() ? 1 : 0 );
	else if( !strcmp( name, "norecallout" ) )
		return PyInt_FromLong( self->pRegion->isNoRecallOut() ? 1 : 0 );
	else if( !strcmp( name, "norecallin" ) )
		return PyInt_FromLong( self->pRegion->isNoRecallIn() ? 1 : 0 );
	else if( !strcmp( name, "recallshield" ) )
		return PyInt_FromLong( self->pRegion->isRecallShield() ? 1 : 0 );
	else if( !strcmp( name, "noagressivemagic" ) )
		return PyInt_FromLong( self->pRegion->isNoAgressiveMagic() ? 1 : 0 );
	else if( !strcmp( name, "antimagic" ) )
		return PyInt_FromLong( self->pRegion->isAntiMagic() ? 1 : 0 );
	else if( !strcmp( name, "validescortregion" ) )
		return PyInt_FromLong( self->pRegion->isValidEscortRegion() ? 1 : 0 );
	else if( !strcmp( name, "cave" ) )
		return PyInt_FromLong( self->pRegion->isCave() ? 1 : 0 );
	else if( !strcmp( name, "nomusic" ) )
		return PyInt_FromLong( self->pRegion->isNoMusic() ? 1 : 0 );

	return Py_FindMethod( wpRegionMethods, (PyObject*)self, name );
}
示例#19
0
// The highest items will be @ the beginning
// While walking we always will try the highest first.
vector< stBlockItem > getBlockingItems( P_CHAR pChar, const Coord_cl& pos )
{
	vector<stBlockItem> blockList;
	make_heap( blockList.begin(), blockList.end(), compareTiles() );

	// Process the map at that position
	stBlockItem mapBlock;
	mapBlock.maptile = true;
	mapBlock.z = Maps::instance()->mapAverageElevation( pos );
	mapBlock.height = 0;

	// TODO: Calculate the REAL average Z Value of that Map Tile here! Otherwise clients will have minor walking problems.
	map_st mapCell = Maps::instance()->seekMap( pos );
	//mapBlock.z = mapCell.z;*/
	land_st mapTile = TileCache::instance()->getLand( mapCell.id );

	// If it's not impassable it's automatically walkable
	if ( !( mapTile.flag1 & 0x40 ) )
		mapBlock.walkable = true;
	else
		mapBlock.walkable = checkWalkable( pChar, mapCell.id );

	if ( mapCell.id != 0x02 )
	{
		blockList.push_back( mapBlock );
		push_heap( blockList.begin(), blockList.end(), compareTiles() );
	}

	// Now for the static-items
	StaticsIterator staIter = Maps::instance()->staticsIterator( pos, true );
	for ( ; !staIter.atEnd(); ++staIter )
	{
		tile_st tTile = TileCache::instance()->getTile( staIter->itemid );

		// Here is decided if the tile is needed
		// It's uninteresting if it's NOT blocking
		// And NOT a bridge/surface
		if ( !( ( tTile.flag2 & 0x02 ) || ( tTile.flag1 & 0x40 ) || ( tTile.flag2 & 0x04 ) ) )
			continue;

		stBlockItem staticBlock;
		staticBlock.z = staIter->zoff;

		// If we are a surface we can always walk here, otherwise check if
		// we are special
		if ( ( tTile.flag2 & 0x02 ) && !( tTile.flag1 & 0x40 ) )
			staticBlock.walkable = true;
		else
			staticBlock.walkable = checkWalkable( pChar, staIter->itemid );

		// If we are a stair only the half height counts (round up)
		if ( tTile.flag2 & 0x04 )
			staticBlock.height = ( Q_UINT8 ) ( ( tTile.height + 1 ) / 2 );
		else
			staticBlock.height = tTile.height;

		blockList.push_back( staticBlock );
		push_heap( blockList.begin(), blockList.end(), compareTiles() );
	}

	RegionIterator4Items iIter( pos );
	for ( iIter.Begin(); !iIter.atEnd(); iIter++ )
	{
		P_ITEM pItem = iIter.GetData();

		if ( !pItem )
			continue;

		if ( pItem->id() >= 0x4000 )
		{
			MultiDefinition* def = MultiCache::instance()->getMulti( pItem->id() - 0x4000 );
			if ( !def )
				continue;
			QValueVector<multiItem_st> multi = def->getEntries();
			unsigned int j;
			for ( j = 0; j < multi.size(); ++j )
			{
				if ( multi[j].visible && ( pItem->pos().x + multi[j].x == pos.x ) && ( pItem->pos().y + multi[j].y == pos.y ) )
				{
					tile_st tTile = TileCache::instance()->getTile( multi[j].tile );
					if ( !( ( tTile.flag2 & 0x02 ) || ( tTile.flag1 & 0x40 ) || ( tTile.flag2 & 0x04 ) ) )
						continue;

					stBlockItem blockItem;
					blockItem.height = tTile.height;
					blockItem.z = pItem->pos().z + multi[j].z;

					if ( ( tTile.flag2 & 0x02 ) && !( tTile.flag1 & 0x40 ) )
						blockItem.walkable = true;
					else
						blockItem.walkable = checkWalkable( pChar, pItem->id() );

					blockList.push_back( blockItem );
					push_heap( blockList.begin(), blockList.end(), compareTiles() );
				}
			}
			continue;
		}
		else if ( pChar->isDead() )
		{
			// Doors can be passed by ghosts
			if ( pItem->hasScript( "door" ) )
			{
				continue;
			}
		}

		// They need to be at the same x,y,plane coords
		if ( ( pItem->pos().x != pos.x ) || ( pItem->pos().y != pos.y ) || ( pItem->pos().map != pos.map ) )
			continue;

		tile_st tTile = TileCache::instance()->getTile( pItem->id() );

		// Se above for what the flags mean
		if ( !( ( tTile.flag2 & 0x02 ) || ( tTile.flag1 & 0x40 ) || ( tTile.flag2 & 0x04 ) ) )
			continue;

		stBlockItem blockItem;
		blockItem.height = tTile.height;
		blockItem.z = pItem->pos().z;

		// Once again: see above for a description of this part
		if ( ( tTile.flag2 & 0x02 ) && !( tTile.flag1 & 0x40 ) )
			blockItem.walkable = true;
		else
			blockItem.walkable = checkWalkable( pChar, pItem->id() );

		blockList.push_back( blockItem );
		push_heap( blockList.begin(), blockList.end(), compareTiles() );
	}

	// Now we need to evaluate dynamic items [...] (later)
	// TODO: Multis here
	sort_heap( blockList.begin(), blockList.end(), compareTiles() );

	return blockList;
};
示例#20
0
QString EQStr::formatMessage(uint32_t formatid, 
			     const char* arguments, size_t argsLen) const
{
  QString* formatStringRes = m_messageStrings.find(formatid);

  QString tempStr;

    if (formatStringRes == NULL)
    {
	uint32_t arg_len;
	unsigned char *cp;
	tempStr.sprintf( "Unknown: %04x:", formatid);
	cp = (unsigned char *) arguments;
	while (cp < ((unsigned char *) &arguments[argsLen])) {
	    arg_len = (cp[0] << 0) | (cp[1] << 8) | (cp[2] << 16) | (cp[3] << 24);
	    cp += 4;
	    if (arg_len == 0)
		break;
	    tempStr += " ";
	    tempStr += QString::fromUtf8((const char *) cp, arg_len);
	    cp += arg_len;
	}
	return tempStr;
    }
    else
    {
	QValueVector<QString> argList;
	argList.reserve(5); // reserve space for 5 elements to handle most common sizes

	// 
	size_t totalArgsLen = 0;
	const char* curArg;
	while (totalArgsLen < argsLen)
	{
	    curArg = arguments + totalArgsLen;
	    // insert argument into the argument list
	    argList.push_back(QString::fromUtf8(curArg));
	    totalArgsLen += strlen(curArg) + 1;
	}

	bool ok;
	int curPos;
	size_t substArg;
	int substArgValue;
	QString* substFormatStringRes;
	QString substFormatString;

	////////////////////////////
	// replace template (%T) arguments in formatted string
	QString formatString = *formatStringRes;
	QRegExp rxt("%T(\\d{1,3})", true, false);

	// find first template substitution
	curPos = rxt.search(formatString, 0);

	while (curPos != -1)
	{
	    substFormatStringRes = NULL;
	    substArg = rxt.cap(1).toInt(&ok);
	    if (ok && (substArg <= argList.size()))
	    {
		substArgValue = argList[substArg-1].toInt(&ok);

		if (ok)
		    substFormatStringRes = m_messageStrings.find(substArgValue);
	    }

	    // replace template argument with subst string
	    if (substFormatStringRes != NULL)
		formatString.replace(curPos, rxt.matchedLength(), *substFormatStringRes);
	    else
		curPos += rxt.matchedLength(); // if no replacement string, skip over

	    // find next substitution
	    curPos = rxt.search(formatString, curPos);
	}

	////////////////////////////
	// now replace substitution arguments in formatted string
	// NOTE: not using QString::arg() because not all arguments are always used
	//       and it will do screwy stuff in this situation
	QRegExp rx("%(\\d{1,3})", true, false);

	// find first template substitution
	curPos = rx.search(formatString, 0);

	while (curPos != -1)
	{
	    substArg = rx.cap(1).toInt(&ok);

	    // replace substitution argument with argument from list
	    if (ok && (substArg <= argList.size()))
		formatString.replace(curPos, rx.matchedLength(), argList[substArg-1]);
	    else
		curPos += rx.matchedLength(); // if no such argument, skip over

	    // find next substitution
	    curPos = rx.search(formatString, curPos);
	}

	return formatString;
    }

}
// public
void kpMainWindow::pasteText (const QString &text,
                              bool forceNewTextSelection,
                              const QPoint &newTextSelectionTopLeft)
{
#if DEBUG_KP_MAIN_WINDOW && 1
    kdDebug () << "kpMainWindow::pasteText(" << text
               << ",forceNewTextSelection=" << forceNewTextSelection
               << ",newTextSelectionTopLeft=" << newTextSelectionTopLeft
               << ")" << endl;
#endif

    if (text.isEmpty ())
        return;


    // sync: restoreOverrideCursor() in all exit paths
    QApplication::setOverrideCursor (Qt::waitCursor);

    if (toolHasBegunShape ())
        tool ()->endShapeInternal ();


    QValueVector <QString> textLines (1, QString::null);

    for (int i = 0; i < (int) text.length (); i++)
    {
        if (text [i] == '\n')
            textLines.push_back (QString::null);
        else
            textLines [textLines.size () - 1].append (text [i]);
    }


    if (!forceNewTextSelection &&
        m_document && m_document->selection () &&
        m_document->selection ()->isText () &&
        m_commandHistory && m_viewManager)
    {
    #if DEBUG_KP_MAIN_WINDOW && 1
        kdDebug () << "\treusing existing Text Selection" << endl;
    #endif

        kpMacroCommand *macroCmd = new kpMacroCommand (i18n ("Text: Paste"),
            this);

        for (int i = 0; i < (int) textLines.size (); i++)
        {
            if (i > 0)
            {
                macroCmd->addCommand (
                    new kpToolTextEnterCommand (
                        QString::null/*uninteresting child of macroCmd*/,
                        m_viewManager->textCursorRow (),
                        m_viewManager->textCursorCol (),
                        this));
            }

            macroCmd->addCommand (
                new kpToolTextInsertCommand (
                    QString::null/*uninteresting child of macroCmd*/,
                    m_viewManager->textCursorRow (),
                    m_viewManager->textCursorCol (),
                    textLines [i],
                    this));
        }

        m_commandHistory->addCommand (macroCmd, false/*no exec*/);
    }
    else
    {
    #if DEBUG_KP_MAIN_WINDOW && 1
        kdDebug () << "\tcreating Text Selection" << endl;
    #endif

        const kpTextStyle ts = textStyle ();
        const QFontMetrics fontMetrics = ts.fontMetrics ();

        int height = textLines.size () * fontMetrics.height ();
        if (textLines.size () >= 1)
            height += (textLines.size () - 1) * fontMetrics.leading ();

        int width = 0;
        for (QValueVector <QString>::const_iterator it = textLines.begin ();
             it != textLines.end ();
             it++)
        {
            const int w = fontMetrics.width (*it);
            if (w > width)
                width = w;
        }


        const int selWidth = QMAX (kpSelection::minimumWidthForTextStyle (ts),
                                   width + kpSelection::textBorderSize () * 2);
        const int selHeight = QMAX (kpSelection::minimumHeightForTextStyle (ts),
                                    height + kpSelection::textBorderSize () * 2);
        kpSelection sel (QRect (0, 0, selWidth, selHeight),
                         textLines,
                         ts);

        if (newTextSelectionTopLeft != KP_INVALID_POINT)
        {
            sel.moveTo (newTextSelectionTopLeft);
            paste (sel, true/*force topLeft*/);
        }
        else
        {
            paste (sel);
        }
    }


    QApplication::restoreOverrideCursor ();
}
示例#22
0
void
Container::createGridLayout(bool testOnly)
{
	//Those lists sort widgets by y and x
	VerWidgetList *vlist = new VerWidgetList(m_form->toplevelContainer()->widget());
	HorWidgetList *hlist = new HorWidgetList(m_form->toplevelContainer()->widget());
	// The vector are used to store the x (or y) beginning of each column (or row)
	QValueVector<int> cols;
	QValueVector<int> rows;
	int end=-1000;
	bool same = false;

	for(ObjectTreeItem *tree = m_tree->children()->first(); tree; tree = m_tree->children()->next())
		vlist->append( tree->widget());
	vlist->sort();

	for(ObjectTreeItem *tree = m_tree->children()->first(); tree; tree = m_tree->children()->next())
		hlist->append( tree->widget());
	hlist->sort();

	// First we need to make sure that two widgets won't be in the same row,
	// ie that no widget overlap another one
	if(!testOnly) {
		for(WidgetListIterator it(*vlist); it.current() != 0; ++it)
		{
			QWidget *w = it.current();
			WidgetListIterator it2 = it;

			for(; it2.current() != 0; ++it2) {
				QWidget *nextw = it2.current();
				if((w->y() >= nextw->y()) || (nextw->y() >= w->geometry().bottom()))
					break;

				if(!w->geometry().intersects(nextw->geometry()))
					break;
				// If the geometries of the two widgets intersect each other,
				// we move one of the widget to the rght or bottom of the other
				if((nextw->y() - w->y()) > abs(nextw->x() - w->x()))
					nextw->move(nextw->x(), w->geometry().bottom()+1);
				else if(nextw->x() >= w->x())
					nextw->move(w->geometry().right()+1, nextw->y());
				else
					w->move(nextw->geometry().right()+1, nextw->y());
			}
		}
	}

	// Then we count the number of rows in the layout, and set their beginnings
	for(WidgetListIterator it(*vlist); it.current() != 0; ++it)
	{
		QWidget *w = it.current();
		WidgetListIterator it2 = it;
		if(!same) { // this widget will make a new row
			end = w->geometry().bottom();
			rows.append(w->y());
		}

		// If same == true, it means we are in the same row as prev widget
		// (so no need to create a new column)
		++it2;
		if(!it2.current())
			break;

		QWidget *nextw = it2.current();
		if(nextw->y() >= end)
			same = false;
		else {
			same = !(same && (nextw->y() >= w->geometry().bottom()));
			if(!same)
				end = w->geometry().bottom();
		}
	}
	kdDebug() << "the new grid will have n rows: n == " << rows.size() << endl;

	end = -10000;
	same = false;
	// We do the same thing for the columns
	for(WidgetListIterator it(*hlist); it.current() != 0; ++it)
	{
		QWidget *w = it.current();
		WidgetListIterator it2 = it;
		if(!same) {
			end = w->geometry().right();
			cols.append(w->x());
		}

		++it2;
		if(!it2.current())
			break;

		QWidget *nextw = it2.current();
		if(nextw->x() >= end)
			same = false;
		else {
			same = !(same && (nextw->x() >= w->geometry().right()));
			if(!same)
				end = w->geometry().right();
		}
	}
	kdDebug() << "the new grid will have n columns: n == " << cols.size() << endl;

	// We create the layout ..
	QGridLayout *layout=0;
	if(!testOnly) {
		layout = new QGridLayout(m_container, rows.size(), cols.size(), m_margin, m_spacing, "grid");
		m_layout = (QLayout*)layout;
	}

	// .. and we fill it with widgets
	for(WidgetListIterator it(*vlist); it.current() != 0; ++it)
	{
		QWidget *w = it.current();
		QRect r = w->geometry();
		uint wcol=0, wrow=0, endrow=0, endcol=0;
		uint i = 0;

		// We look for widget row(s) ..
		while(r.y() >= rows[i])
		{
			if(rows.size() <= i+1) // we are the last row
			{
				wrow = i;
				break;
			}
			if(r.y() < rows[i+1])
			{
				wrow = i; // the widget will be in this row
				uint j = i + 1;
				// Then we check if the widget needs to span multiple rows
				while(rows.size() >= j+1 && r.bottom() > rows[j])
				{
					endrow = j;
					j++;
				}

				break;
			}
			i++;
		}
		//kdDebug() << "the widget " << w->name() << " wil be in the row " << wrow <<
		   //" and will go to the row " << endrow << endl;

		// .. and column(s)
		i = 0;
		while(r.x() >= cols[i])
		{
			if(cols.size() <= i+1) // last column
			{
				wcol = i;
				break;
			}
			if(r.x() < cols[i+1])
			{
				wcol = i;
				uint j = i + 1;
				// Then we check if the widget needs to span multiple columns
				while(cols.size() >= j+1 && r.right() > cols[j])
				{
					endcol = j;
					j++;
				}

				break;
			}
			i++;
		}
		//kdDebug() << "the widget " << w->name() << " wil be in the col " << wcol <<
		 // " and will go to the col " << endcol << endl;

		ObjectTreeItem *item = m_form->objectTree()->lookup(w->name());
		if(!endrow && !endcol) {
			if(!testOnly)
				layout->addWidget(w, wrow, wcol);
			item->setGridPos(wrow, wcol, 0, 0);
		}
		else {
			if(!endcol)  endcol = wcol;
			if(!endrow)  endrow = wrow;
			if(!testOnly)
				layout->addMultiCellWidget(w, wrow, endrow, wcol, endcol);
			item->setGridPos(wrow, wcol, endrow-wrow+1, endcol-wcol+1);
		}
	}
}
示例#23
0
/*
	\command account
	\usage - <code>account create username password</code>
	- <code>account remove username</code>
	- <code>account set username key value</code>
	- <code>account show username key</code>
	Use the create subcommand to create a new account with the given username and password.
	To remove an account along with all player characters on that account, use the remove 
	subcommand and pass the username to it.
	To change properties of a given account, use the set subcommand and pass the username, 
	the property key and the new property value to it. See the notes for a list of valid property keys.
	To view properties of an account, use the show subcommand and pass the property key to it.

	\notes The following properties can be set for accounts:
    <i>password</i>
	The account password.

	<i>acl</i>
	The name of the access control list.

	<i>block</i>
	Block status of the account.

	In addition to the writeable properties, the following properties can be shown:

	<i>loginattempts</i>
	How many failed login attempts have been made since the last successful login.

	<i>lastlogin</i>
	When was the last successful login made.
	
	<i>chars</i>
	Prints a list of player characters on this account.

	Valid values for the block property are either on, off or for how long the account should be blocked.
	
	If you have enabled MD5 passwords, you can only view the hashed password when showing the password property.
*/
void commandAccount( cUOSocket *socket, const QString &command, const QStringList &args ) throw()
{
	Q_UNUSED(command);
	// Account Create User Pass
	// Account Remove User
	// Account Set User Pass
	// Account Show User Pass
	if( args.count() == 0 )
	{
		socket->sysMessage( tr( "Usage: account <create|remove|set|show>" ) );
		return;
	}

	QString subCommand = args[0].lower();

	// Create Accounts
	if( subCommand == "create" )
	{
		// Create a new account
		if( args.count() < 3 )
		{
			socket->sysMessage( tr( "Usage: account create <username> <password>" ) );
		}
		else if( Accounts::instance()->getRecord( args[1].left( 30 ) ) )
		{
			socket->sysMessage( tr( "Account '%1' already exists" ).arg( args[1].left( 30 ) ) );
		}
		else
		{
			Accounts::instance()->createAccount( args[1].left( 30 ), args[2].left( 30 ) );
			socket->sysMessage( tr( "Account '%1' with password '%2' has been created" ).arg( args[1].left( 30 ) ).arg( args[2].left( 30 ) ) );
		}
	}

	// Remove an Account and all associated characters
	else if( subCommand == "remove" )
	{
		if( args.count() < 2 )
		{
			socket->sysMessage( tr( "Usage: account remove <username>" ) );
		}
		else if( !Accounts::instance()->getRecord( args[1].left( 30 ) ) )
		{
			socket->sysMessage( tr( "Account '%1' does not exist" ).arg( args[1].left( 30 ) ) );
		}
		else
		{
			cAccount *account = Accounts::instance()->getRecord( args[1].left( 30 ) );
			QValueVector<P_PLAYER> characters = account->caracterList();
			Accounts::instance()->remove( account );
			UINT32 i = 0;
			for(; i < characters.size(); ++i )
				if( characters[i] )
					cCharStuff::DeleteChar( characters[i] );

			socket->sysMessage( tr( "Account '%1' and %2 characters have been removed" ).arg( args[1].left( 30 ) ).arg( i+1 ) );
		}
	}

	// Set properties of accounts
	else if( subCommand == "set" )
	{
		if( args.count() < 4 )
		{
			socket->sysMessage( tr( "Usage: account set <username> <key> <value>" ) );
		}
		else if( !Accounts::instance()->getRecord( args[1].left( 30 ) ) )
		{
				socket->sysMessage( tr( "Account '%1' does not exist" ).arg( args[1].left( 30 ) ) );
		}
		else
		{
			cAccount *account = Accounts::instance()->getRecord( args[1].left( 30 ) );
			QString key = args[2];
			QString value = args[3];

			if( key == "password" )
			{
				account->setPassword( value.left( 30 ) ); // Maximum of 30 Chars allowed
				socket->sysMessage( tr( "The password of account '%1' has been set to '%2'" ).arg( account->login() ).arg( value.left( 30 ) ) );
			}
			else if( key == "block" )
			{
				if( value.lower() == "on" )
				{
					account->setBlocked( true );
					socket->sysMessage( tr( "Account '%1' has been blocked" ).arg( account->login() ) );
				}
				else if( value.lower() == "off" )
				{
					account->setBlocked( false );
					socket->sysMessage( tr( "Account '%1' has been unblocked" ).arg( account->login() ) );
				}
				else
				{
					bool ok = false;
					UINT32 blockTime = hex2dec( value ).toUInt( &ok );

					if( ok )
					{
						account->block( blockTime );
						socket->sysMessage( tr( "Account '%1' will be blocked for %2 seconds" ).arg( account->login() ).arg( blockTime ) );
					}
					else
					{
						socket->sysMessage( tr( "Usage: account set <username> block <on|off>" ) );
					}
				}
			}
			else if( key == "acl" )
			{
				if( !Commands::instance()->getACL( value.latin1() ) )
				{
					socket->sysMessage( tr( "You tried to specify an unknown acl '%1'" ).arg( value ) );
				}
				else
				{
					account->setAcl( value );
					account->refreshAcl();
				}
			}
			else
			{
				socket->sysMessage( tr( "Unknown field '%1' for account '%2'" ).arg( args[2] ).arg( account->login() ) );
			}
		}
	}
	// Show properties of accounts
	else if( subCommand == "show" )
	{
		if( args.count() < 3 )
		{
			socket->sysMessage( tr( "Usage: account show <username> <key>" ) );
		}
		else if( !Accounts::instance()->getRecord( args[1].left( 30 ) ) )
		{
			socket->sysMessage( tr( "Account '%1' does not exist" ).arg( args[1].left( 30 ) ) );
		}
		else
		{
			cAccount *account = Accounts::instance()->getRecord( args[1].left( 30 ) );
			QString key = args[2];

			if( key == "password" )
			{
				socket->sysMessage( tr( "The password of account '%1' is '%2'" ).arg( account->login() ).arg( account->password() ) );
			}
			else if( key == "block" )
			{
				if( account->isBlocked() )
					socket->sysMessage( tr( "Account '%1' is currently blocked" ).arg( account->login() ) );
				else if( account->secsToUnblock() )
					socket->sysMessage( tr( "Account '%1' will be unblocked in %2 seconds" ).arg( account->login() ).arg( account->secsToUnblock() ) );
				else
					socket->sysMessage( tr( "Account '%1' is currently not blocked" ).arg( account->login() ) );
			}
			else if( key == "loginattempts" )
			{
				socket->sysMessage( tr( "There were %1 unsuccesul login attempts for account '%2'" ).arg( account->loginAttempts() ).arg( account->login() ) );
			}
			else if( key == "lastlogin" )
			{
				socket->sysMessage( tr( "The last login of account '%1' was on %2" ).arg( account->login() ).arg( account->lastLogin().toString( Qt::ISODate ) ) );
			}
			else if( key == "acl" )
			{
				socket->sysMessage( tr( "The acl of account '%1' is %2" ).arg( account->login() ).arg( account->acl() ) );
			}
			else if( key == "chars" )
			{
				QStringList sCharList;
				QValueVector< P_PLAYER > pCharList = account->caracterList();

				for( UINT32 i = 0; i < pCharList.size(); ++i )
					if( pCharList[i] )
						sCharList.push_back( QString( "0x%1" ).arg( pCharList[i]->serial(), 8, 16 ) );

				socket->sysMessage( tr( "Account '%1' has the following characters: %2" ).arg( account->login() ).arg( sCharList.join( ", " ) ) );
			}
			else
			{
				socket->sysMessage( tr( "Unknown field '%1' for account '%2'" ).arg( args[2] ).arg( account->login() ) );
			}
		}
	}
}
示例#24
0
bool Coord_cl::lineOfSight( const Coord_cl &target, UI16 targetheight, bool touch )
{
	//Console::instance()->send( QString( "LOScheck: Source:%1,Target:%2,Targetheight:%3\n" ).arg( z ).arg( target.z ).arg( targetheight ) );
	if( target.map != map )
		return false;

	if( (x == target.x) && (y == target.y) && (z == target.z) )
		return true;		// if source and target are on the same position

	SI32 n = ( target.x - x ), m = ( target.y - y ), i = 0;
	SI08 sgn_x = ( x <= target.x ) ? 1 : (-1); // signum for x
	SI08 sgn_y = ( y <= target.y ) ? 1 : (-1); // signum for y
	SI08 sgn_z = ( z <= target.z ) ? 1 : (-1); // signum for z
	if( x == target.x )
		sgn_x = 0;
	if( y == target.y )
		sgn_y = 0;
	if( z == target.z )
		sgn_z = 0;

	QValueList< Coord_cl > collisions;

	//first we get our x-y-coordinates
	if( sgn_x == 0 && sgn_y == 0 && !sgn_z == 0 ) // should fix shooting through floor issues
		{
			collisions.push_back( Coord_cl( x, y, 0, map ) );
		}
	else if( sgn_x == 0 ) // if we are on the same x-level, just push every x/y coordinate in y-direction from src to trg into the array
		for( i = 0; i <= (sgn_y * m); ++i )
		{
			collisions.push_back( Coord_cl( x, y + (sgn_y * i), 0, map ) );
		}
	else if ( sgn_y == 0 ) // if we are on the same y-level, just push every x/y coordinate in x-direction from src to trg into the array
		for( i = 0; i <= (sgn_x * n); ++i )
		{
			collisions.push_back( Coord_cl( x + (sgn_x * i), y, 0, map ) );
		}
	else
	{
		SI32 oldpos = y;
		bool exaktpos = false;
		for( i = 0; (sgn_x * n >= sgn_y * m) && (i <= (sgn_x * n)); i++ )
		{
			//Console::instance()->send( QString( "x:%1\n" ).arg( i ) );
			SI32 gridx = x + (sgn_x * i);
			if( ( ( n == 0 ) && ( gridx == 0 ) ) ||
				( ( n + ( gridx * m ) == 0 ) ) )
				continue;
			else
			{
				if( exaktpos )
				{
					collisions.push_back( Coord_cl( gridx, oldpos-sgn_y, 0, map ) );
					//Console::instance()->send( QString( "add exaktpos coordinate %1,%2\n" ).arg( gridx ).arg( oldpos-sgn_y ) );
					exaktpos = false;
				}
					
				// linear evaluation of extended 2x2 matrix, abbreviated
				double t = (double)sgn_x * ((double)i+0.5) * (double)m / (double)n + (double)y;
				//Console::instance()->send( QString( "t:%1\n" ).arg( t ) );

				if( ((sgn_y>0) && (specialFloor(t)==oldpos+0.5)) || ((sgn_y<0) && (specialFloor(t)==oldpos-0.5)) )
				{
					exaktpos = true;
				}
				
				if( ((sgn_y>0) && (t<oldpos+0.5)) || ((sgn_y<0) && (t>oldpos-0.5)) || (oldpos==target.y) )
				{
					collisions.push_back( Coord_cl( gridx, oldpos, 0, map ) );
					//Console::instance()->send( QString( "add coordinate %1,%2\n" ).arg( gridx ).arg( oldpos ) );
				}
				// but if not, we have to take BOTH coordinates, which the calculated collision is between!
				else
				{ 
					collisions.push_back( Coord_cl( gridx, oldpos, 0, map ) );
					//Console::instance()->send( QString( "add coordinate %1,%2\n" ).arg( gridx ).arg( oldpos ) );
					oldpos += sgn_y;
					collisions.push_back( Coord_cl( gridx, oldpos, 0, map ) );
					//Console::instance()->send( QString( "add coordinate %1,%2\n" ).arg( gridx ).arg( oldpos ) );
				}
			}
		}
		
		oldpos = x;
		exaktpos = false;
		for( i = 0; (sgn_y * m >= sgn_x * n) && (i <= (sgn_y * m)); ++i )
		{
			//Console::instance()->send( QString( "y:%1\n" ).arg( i ) );
			SI32 gridy = y + (sgn_y * i);
			if( ( ( m == 0 ) && ( gridy == 0 ) ) ||
				( ( m + ( gridy * n ) == 0 ) ) )
				continue;
			else
			{
				if( exaktpos )
				{
					collisions.push_back( Coord_cl( oldpos-sgn_x, gridy, 0, map ) );
					//Console::instance()->send( QString( "add exaktpos coordinate %1,%2\n" ).arg( oldpos-sgn_x ).arg( gridy ) );
					exaktpos = false;
				}

				double t = (double)x + (double)n / (double)m * (double)sgn_y * ((double)i+0.5);
				//Console::instance()->send( QString( "t:%1\n" ).arg( t ) );

				if( ((sgn_x>0) && (specialFloor(t)==oldpos+0.5)) || ((sgn_x<0) && (specialFloor(t)==oldpos-0.5)) )
				{
					exaktpos = true;
				}

				if( ((sgn_x>0) && (t<oldpos+0.5)) || ((sgn_x<0) && (t>oldpos-0.5)) || (oldpos==target.x) )
				{
					collisions.push_back( Coord_cl( oldpos, gridy, 0, map ) );
					//Console::instance()->send( QString( "add coordinate %1,%2\n" ).arg( oldpos ).arg( gridy ) );

				}
				// but if not, we have to take BOTH coordinates, which the calculated collision is between!
				else
				{ 
					collisions.push_back( Coord_cl( oldpos, gridy, 0, map ) );
					//Console::instance()->send( QString( "add coordinate %1,%2\n" ).arg( oldpos ).arg( gridy ) );
					oldpos += sgn_x;;
					collisions.push_back( Coord_cl( oldpos, gridy, 0, map ) );
					//Console::instance()->send( QString( "add coordinate %1,%2\n" ).arg( oldpos ).arg( gridy ) );
				}
			}
		}
	}

	// the next will search for multis
	QPtrList< cItem > multis;
	RegionIterator4Items ri( *this );
	for( ri.Begin(); !ri.atEnd(); ri++ )
	{
		P_ITEM pi = ri.GetData();
		if( pi && pi->id() >= 0x4000 )
		{
			multis.append( pi );
		}
	}

	//touch wird von notouch getrennt, da der notouch algorithmus wesentlich aufwändiger
	//ist (touch benötigt die erste for-schleife nicht), macht den code zwar bisserl
	//unübersichtlicher, aber ist wesentlich effizienter

	//touch is separated from notouch, because the notouch calculation is much more to do
	//( one additional for-loop )

	if( targetheight > 0 )
	{
		--targetheight;
	}

	if( !touch )
	{
		for( i = target.z+targetheight; i >= target.z; --i )
		{
			bool blocked = false;
			//Console::instance()->send( QString( "i:%1\n" ).arg( i ) );
			double dz;
			double gradient;
			double offset;
			if( (sgn_x == 0) && (sgn_y == 0) )
			{
				dz = (double)i - (double)z;
				gradient = 1; //only to avoid problems, isnt used
				offset = 1;
			}
			else
			{
				dz = ( (double)i -(double)z ) / sqrt( ((double)target.x - (double)x)*((double)target.x - (double)x) + ((double)target.y - (double)y)*((double)target.y - (double)y) );
				gradient = (double)m / (double)n;
				offset = 0.5*( (double)y + (double)target.y - gradient*( x + target.x ) );
			}
	
			map_st map1, map2;
			SI32 j;
	
			bool posHigherThanMap;
			map1 = Map->seekMap( (*this) );
			if( map1.z > z )
			{
				posHigherThanMap = false;
			}
			else
			{
				posHigherThanMap = true;
			}
			
			//Console::instance()->send( QString( "after first things\n" ) );
			QValueList< Coord_cl >::iterator pit = collisions.begin();
			while( pit != collisions.end() )
			{
				//Console::instance()->send( QString( "coordinate:%1,%2 dz:%3\n" ).arg( (*pit).x ).arg( (*pit).y ).arg( dz ) );
				//lets see what z-coordinates we have to test
				//we do our calculations exakt, because its the only way to solve all problems
				//of floor
				//"minimum" ist am anfang der platte, "maximum" am ende
				//our line is y = gradient * x + offset
				//or x = ( y - offset ) / gradient
				//we now have to test, where the line cuts one position
				//start and endposition has to be done alone
				
				double z1 = -300;
				double z2 = -300;
				SI08 zmin, zmax;

				if( (sgn_x == 0) && (sgn_y == 0) )
				{
					if( dz > 0 )
					{
						zmin = z+1;
						zmax = i;
					}
					else
					{
						zmin = i+1;
						zmax = z;
					}
				}
				else if( sgn_x == 0 )
				{
					//gradient only in y-direction
					z1 = (double)i - dz*( fabs( (double)target.y - (double)((*pit).y) ) -0.5 ); 
					z2 = (double)i - dz*( fabs( (double)target.y - (double)((*pit).y) ) +0.5 );
					//Console::instance()->send( QString( "i:%1,ty:%2,cy:%3\n" ).arg( i ).arg( target.y ).arg( (*pit).y ) );
					//Console::instance()->send( QString( "z1:%1,z2:%2\n" ).arg( z1 ).arg( z2 ) );

					if( z1 > z2 )
					{
						zmin = (SI08)floor( z2 );
						zmax = (SI08)ceilf( z1 );
					}
					else
					{
						zmin = (SI08)floor( z1 );
						zmax = (SI08)ceilf( z2 );
					}

					/*another try, but i think its needed for all positions, not only start and end...
					//target 
					if( (*pit).y == target.y )
					{
						if( dz > 0 )
						{
							zmax = QMIN( zmax, i );
							//Console::instance()->send( QString( "TargetY, zmax:%1, i:%2\n" ).arg( zmax ).arg( i ) );
						}
						else
						{
							zmin = QMAX( zmin, i+1 );
							//Console::instance()->send( QString( "TargetY, zmin:%1, i:%2\n" ).arg( zmin ).arg( i ) );
						}
					}

					//source
					if( (*pit).y == y )
					{
						if( dz > 0 )
						{
							zmin = QMAX( zmin, z );
							//Console::instance()->send( QString( "SourceY, zmin:%1, i:%2\n" ).arg( zmax ).arg( i ) );
						}
						else
						{
							zmax = QMIN( zmax, z );
							//Console::instance()->send( QString( "SourceY, zmax:%1, i:%2\n" ).arg( zmax ).arg( i ) );
						}
					}*/
					if( dz > 0 )
					{
						zmax = QMIN( zmax, i );
						zmin = QMAX( zmin, z );
					}
					else
					{
						zmin = QMAX( zmin, i+1 );
						zmax = QMIN( zmax, z );
					}

				}
				else if( sgn_y == 0 )
				{
					//gradient only in y-direction
					z1 = (double)i - dz*( fabs( (double)target.x - (double)((*pit).x) ) -0.5 ); 
					z2 = (double)i - dz*( fabs( (double)target.x - (double)((*pit).x) ) +0.5 );
					//Console::instance()->send( QString( "i:%1,tx:%2,cx:%3\n" ).arg( i ).arg( target.x ).arg( (*pit).x ) );
					//Console::instance()->send( QString( "z1:%1,z2:%2\n" ).arg( z1 ).arg( z2 ) );

					if( z1 > z2 )
					{
						zmin = (SI08)floor( z2 );
						zmax = (SI08)ceilf( z1 );
					}
					else
					{
						zmin = (SI08)floor( z1 );
						zmax = (SI08)ceilf( z2 );
					}
					
					if( dz > 0 )
					{
						zmax = QMIN( zmax, i );
						zmin = QMAX( zmin, z );
					}
					else
					{
						zmin = QMAX( zmin, i+1 );
						zmax = QMIN( zmax, z );
					}

				}
				else
				{
					//4 lines to test
					double gradx = ( (double)target.y*(double)z - (double)y*(double)i ) / ( (double)target.y*(double)x - (double)y*(double)target.x );
					double grady = ( (double)target.x*(double)z - (double)x*(double)i ) / ( (double)y*(double)target.x - (double)target.y*(double)x );

					//Console::instance()->send( QString( "gradx:%1,grady:%2\n" ).arg( gradx ).arg( grady ) );
					//Console::instance()->send( QString( "Gradient:%1,Offset:%2\n" ).arg( gradient ).arg( offset ) );
					double temp;
					temp = specialFloor( gradient*( (double)((*pit).x) - 0.5 ) + offset );
					//Console::instance()->send( QString( "temp1:%1\n" ).arg( temp ) );
					if( ( temp >= ((double)((*pit).y)-0.5) ) && ( temp <= ((double)((*pit).y)+0.5) ) )
					{
						if( z1 > -300 )
						{
							z2 = gradx * ( (double)((*pit).x)-0.5 ) + grady * temp;
						}
						else
						{	
							z1 = gradx * ( (double)((*pit).x)-0.5 ) + grady * temp;
						}
						//Console::instance()->send( QString( "1:i:%1,tx:%2,ty:%3,cy:%4,cy:%5\n" ).arg( i ).arg( target.x ).arg( target.y ).arg( (*pit).x ).arg( (*pit).y ) );
						//Console::instance()->send( QString( "z1:%1,z2:%2\n" ).arg( z1 ).arg( z2 ) );
					}
					temp = specialFloor( gradient*( (double)((*pit).x) + 0.5 ) + offset );
					//Console::instance()->send( QString( "temp2:%1\n" ).arg( temp ) );
					if( ( temp >= ((double)((*pit).y)-0.5) ) && ( temp <= ((double)((*pit).y)+0.5) ) )
					{
						if( z1 > -300 )
						{
							z2 = gradx * ( (double)((*pit).x)+0.5 ) + grady * temp;
						}
						else
						{	
							z1 = gradx * ( (double)((*pit).x)+0.5 ) + grady * temp;
						}
						//Console::instance()->send( QString( "2:i:%1,tx:%2,ty:%3,cy:%4,cy:%5\n" ).arg( i ).arg( target.x ).arg( target.y ).arg( (*pit).x ).arg( (*pit).y ) );
						//Console::instance()->send( QString( "z1:%1,z2:%2\n" ).arg( z1 ).arg( z2 ) );
					}
					temp = specialFloor( (double)((*pit).y) - 0.5 - offset ) / gradient;
					//Console::instance()->send( QString( "temp3:%1\n" ).arg( temp ) );
					if( ( temp > ((double)((*pit).x)-0.5) ) && ( temp < ((double)((*pit).x)+0.5) ) )
					{
						if( z1 > -300 )
						{
							z2 = gradx * temp + grady * ((double)((*pit).y)-0.5);
						}
						else
						{
							z1 = gradx * temp + grady * ((double)((*pit).y)-0.5);
						}
						//Console::instance()->send( QString( "3:i:%1,tx:%2,ty:%3,cy:%4,cy:%5\n" ).arg( i ).arg( target.x ).arg( target.y ).arg( (*pit).x ).arg( (*pit).y ) );
						//Console::instance()->send( QString( "z1:%1,z2:%2\n" ).arg( z1 ).arg( z2 ) );
					}
					temp = specialFloor( (double)((*pit).y) + 0.5 - offset ) / gradient;
					//Console::instance()->send( QString( "temp4:%1\n" ).arg( temp ) );
					if( ( temp > ((double)((*pit).x)-0.5) ) && ( temp < ((double)((*pit).x)+0.5) ) )
					{
						if( z1 > -300 )
						{
							z2 = gradx * temp + grady * ((double)((*pit).y)+0.5);
						}
						else
						{
							z1 = gradx * temp + grady * ((double)((*pit).y)+0.5);
						}
						//Console::instance()->send( QString( "4:i:%1,tx:%2,ty:%3,cy:%4,cy:%5\n" ).arg( i ).arg( target.x ).arg( target.y ).arg( (*pit).x ).arg( (*pit).y ) );
						//Console::instance()->send( QString( "z1:%1,z2:%2\n" ).arg( z1 ).arg( z2 ) );
					}
					
					//Console::instance()->send( QString( "z1:%1,z2:%2\n" ).arg( z1 ).arg( z2 ) );
					if( z1 > z2 )
					{
						zmin = (SI08)floor( z2 );
						zmax = (SI08)ceilf( z1 );
					}
					else
					{
						zmin = (SI08)floor( z1 );
						zmax = (SI08)ceilf( z2 );
					}

					if( z2 == -300 )
					{
						zmin = (SI08)floor( z1 );
					}

					if( dz > 0 )
					{
						zmax = QMIN( zmax, i );
						zmin = QMAX( zmin, z );
					}
					else
					{
						zmin = QMAX( zmin, i+1 );
						zmax = QMIN( zmax, z );
					}
					//Console::instance()->send( QString( "zmin:%1,zmax:%2\n" ).arg( zmin ).arg( zmax ) );
				}

				/*SI08 zmin = (SI08)floor( i - dz*sqrt( ((double)target.x - (double)(*pit).x)*((double)target.x - (double)(*pit).x) + ((double)target.y - (double)(*pit).y)*((double)target.y - (double)(*pit).y) ) );
				SI08 zmax;
				//Console::instance()->send( QString( "zmin:%1,dz:%2\n" ).arg( zmin ).arg( dz ) );
				if( dz > 0 )
				{
					zmin = QMAX( (SI08)floor( zmin - dz/2 ), z+1 );
					zmax = QMIN( zmin + dz + 1, target.z+targetheight+1 );	//to prevent floor-mistakes
				}
				else
				{
					zmin = QMIN( (SI08)floor( zmin + dz/2 ), target.z+1 );
					zmax = QMAX( zmin - dz + 1, z );	//to prevent floor-mistakes
				}*/
	
				// Texture mapping  
				map1 = Map->seekMap( *pit );
				map2 = Map->seekMap( Coord_cl( (*pit).x + sgn_x, (*pit).y + sgn_y, (*pit).z, map ) );
			
				//Console::instance()->send( QString( "maphoehe:%1\n" ).arg( map1.z ) );
				StaticsIterator msi = Map->staticsIterator( *pit );
				if( (map1.id != 2) && (map2.id != 2) ) 
				{
					if( ( map1.z >= zmin ) && ( map1.z <= zmax ) )
					{
						//its just in our way
						//Console::instance()->send( QString( "Map gescheitert\n" ) );
						blocked = true;
						break;
					}
	
					//now we have to test, if this tile is under our line and the next above or
					//vice verse
					//in this case, both dont cut our line, but the mapconnection between them
					//should do
					if( ( ( map1.z < map2.z ) && ( map1.z < zmin ) && ( map2.z > zmax+dz ) ) ||						// 1) lineofsight collides with a map "wall"
						( ( map1.z > map2.z ) && ( map1.z > zmin ) && ( map2.z < zmax-dz ) ) ||
						( ( ( map1.id >= 431  && map1.id <= 432  ) ||	// 3) lineofsight cuts a mountain
						( map1.id >= 467  && map1.id <= 475  ) ||
						( map1.id >= 543  && map1.id <= 560  ) ||
						( map1.id >= 1754 && map1.id <= 1757 ) ||
						( map1.id >= 1787 && map1.id <= 1789 ) ||
						( map1.id >= 1821 && map1.id <= 1824 ) ||
						( map1.id >= 1851 && map1.id <= 1854 ) ||
						( map1.id >= 1881 && map1.id <= 1884 ) ) &&
						( posHigherThanMap ) && ( msi.atEnd() ) ) ) // mountains cut only if we are not beneath them
					{
						//Console::instance()->send( QString( "map1:%1,map2:%2\n" ).arg( map1.z ).arg( map2.z ) );
						blocked = true;
						break;
					}
				}	 
				
				//Console::instance()->send( QString( "after map\n" ) );
	
				// Statics
				tile_st tile;
				while( !msi.atEnd() )
				{
					tile = TileCache::instance()->getTile( msi->itemid );
					//if it is in our way
					//Console::instance()->send( QString( "tilepos:%1,zmax:%2" ).arg( msi->zoff ).arg( zmax ) );
					//Console::instance()->send( QString( "zmin:%3\n" ).arg( zmin ) );
					if( ( zmax >= msi->zoff ) && ( zmin <= ( msi->zoff + tile.height ) ) )
					{
						//Console::instance()->send( QString( "statictile, id: %1\n" ).arg( msi->itemid ) );
						if( tile.isNoShoot() )
						{
							blocked = true;
							break;
						}
					}
		
					++msi;
				}
				if( blocked )
				{
					break;
				}
				
				//Console::instance()->send( QString( "after statics\n" ) );
				// Items
				RegionIterator4Items rj( (*pit), 0 );
				for( rj.Begin(); !rj.atEnd(); rj++ )
				{
					P_ITEM pi = rj.GetData();
					if( pi && pi->id() < 0x4000 )
					{
						tile = TileCache::instance()->getTile( pi->id() );
						if(	( zmax >= pi->pos().z ) && ( zmin <= ( pi->pos().z + tile.height ) ) && ( pi->visible() == 0 ) )
						{
							//Console::instance()->send( QString( "item, id: %1" ).arg( pi->id() ) );
							if( tile.isNoShoot() )
							{
								blocked = true;
								break;
							}
						}	
					}
				}
				if( blocked )
				{
					break;
				}
	
				//Console::instance()->send( QString( "after items\n" ) );
				// Multis
				QPtrListIterator< cItem > mit( multis );
				P_ITEM pi;
				while( ( pi = mit.current() ) )
				{
					MultiDefinition* def = MultiCache::instance()->getMulti( pi->id() - 0x4000 );
					if ( !def )
						continue;
					QValueVector<multiItem_st> multi = def->getEntries();
					for( j = 0; j < multi.size(); ++j )
					{
						if( ( multi[j].visible ) && ( pi->pos().x + multi[j].x == (*pit).x ) &&
							( pi->pos().y + multi[j].y == (*pit).y ) )			
						{
							tile = TileCache::instance()->getTile( multi[j].tile );
							if( ( zmax >= pi->pos().z + multi[j].z ) &&
								( zmin <= pi->pos().z + multi[j].z + tile.height ) )
							{
								if( tile.isNoShoot() )
								{
									blocked = true;
									break;
								}
							}	
						}
					}
					++mit;
				}
				//Console::instance()->send( QString( "after multis\n" ) );
				++pit;
			}
	
			if( !blocked )
				return true;
		}
		//there was no line to see through
		return false;
	}
	//now touch=true
	else
	{
		//Console::instance()->send( "touch\n" );
		double dz_up, dz_down;
		double gradient;
		double offset;
		if( (sgn_x == 0) && (sgn_y == 0) )
		{
			dz_up = ( (double)targetheight + (double)target.z ) - (double)z;
			dz_down = (double)target.z - ( (double)z - (double)15 );
			gradient = 1; //only to prevent problems, isnt used
			offset = 1;
		}
		else
		{
			//Console::instance()->send( QString( "xdiff:%1,ydiff:%2\n" ).arg( (double)target.x - (double)x ).arg( (double)target.y - (double)y ) );
			dz_up = ( ( (double)targetheight + (double)target.z ) - (double)z ) / sqrt( ((double)target.x - (double)x)*((double)target.x - (double)x) + ((double)target.y - (double)y)*((double)target.y - (double)y) );
			dz_down = ( (double)target.z - ( (double)z - (double)15 ) ) / sqrt( ((double)target.x - (double)x)*((double)target.x - (double)x) + ((double)target.y - (double)y)*((double)target.y - (double)y) );
			gradient = (double)m / (double)n;
			offset = 0.5*( (double)y + (double)target.y - gradient*( x + target.x ) );
		}
	
		map_st map1, map2;
		SI32 j;
	
		bool posHigherThanMap;
		map1 = Map->seekMap( (*this) );
		if( map1.z > z )
		{
			posHigherThanMap = false;
		}
		else
		{
			posHigherThanMap = true;
		}
		
		//Console::instance()->send( QString( "after first things\n" ) );
		QValueList< Coord_cl >::iterator pit = collisions.begin();
		while( pit != collisions.end() )
		{
			//Console::instance()->send( QString( "coordinate:%1,%2\n" ).arg( (*pit).x ).arg( (*pit).y ) );				
			//lets see what z-coordinates we have to test
			//anmerkung: touch kommt nur für chars vor, grösse von chars ist 15
			//SI08 zmin = (SI08)floor(  (double)z - (double)sourceheight + dz_down*sqrt( ((double)target.x - (double)(*pit).x)*((double)target.x - (double)(*pit).x) + ((double)target.y - (double)(*pit).y)*((double)target.y - (double)(*pit).y) ) );
			//SI08 zmax = (SI08)floor(  (double)z + dz_up*sqrt( ((double)target.x - (double)(*pit).x)*((double)target.x - (double)(*pit).x) + ((double)target.y - (double)(*pit).y)*((double)target.y - (double)(*pit).y) ) );
			SI08 zmin, zmax;
			double z1_up = -300;
			double z2_up = -300;
			double z1_down = -300;
			double z2_down = -300;
			bool targetpos = false;
			//Console::instance()->send( QString( "dz_down:%3,dz_up:%4\n" ).arg( dz_down ).arg( dz_up ) );

			if( (sgn_x == 0) && (sgn_y == 0) )
			{
				if( dz_up > 0 )
				{
					zmin = z+1;
					zmax = target.z;
				}
				else
				{
					zmin = target.z+1;
					zmax = z;
				}
				targetpos = true;
				if( (dz_up >= 0) && (dz_down >= 0) )
				{
					if( zmin < target.z )
					{
						zmax = target.z -1;
					}
					else
					{
						//we ignore this coordinate
						++pit;
						continue;
					}
				}
				else if( (dz_up <= 0) && (dz_down <= 0) )
				{
					if( zmax > target.z + targetheight+1 )
					{
						zmin = target.z + targetheight + 2;
					}
					else
					{
						++pit;
						continue;
					}
				}
				else 
				{
					//we may have to split the test into two if we would do it exactly
					//but i think we can throw away the test from down in this case
					if( zmax > target.z + targetheight+1 )
					{
						zmin = target.z + targetheight + 2;
					}
					else if( zmin < target.z )
					{
						zmax = target.z -1;
					}
					else
					{
						++pit;
						continue;
					}
				}
			}
			else if( sgn_x == 0 )
			{
				z1_up = target.z + targetheight - dz_up*( fabs( (double)target.y - (double)((*pit).y) ) -0.5 ); 
				z2_up = target.z + targetheight - dz_up*( fabs( (double)target.y - (double)((*pit).y) ) +0.5 );
			
				z1_down = target.z - dz_down*( fabs( (double)target.y - (double)((*pit).y) ) -0.5 );
				z2_down = target.z - dz_down*( fabs( (double)target.y - (double)((*pit).y) ) +0.5 );

				//Console::instance()->send( QString( "ty:%2,cy:%3\n" ).arg( target.y ).arg( (*pit).y ) );
				//Console::instance()->send( QString( "z1_up:%1,z2_up:%2,z1_down:%3,z2_down:%4\n" ).arg( z1_up ).arg( z2_up ).arg( z1_down ).arg( z2_down ) );

				zmax = QMAX( ceil( z1_up ), ceil( z2_up ) );
				zmin = QMIN( floor( z1_down ), floor( z2_down ) );

				//Console::instance()->send( QString( "y:zmin:%1,zmax:%2\n" ).arg( zmin ).arg( zmax ) );

				if( dz_up > 0 )
				{
					zmax = QMIN( zmax, target.z+targetheight );
				}
				else
				{
					zmax = QMIN( zmax, z );
				}

				//Console::instance()->send( QString( "y2:zmin:%1,zmax:%2\n" ).arg( zmin ).arg( zmax ) );

				if( dz_down > 0 )
				{
					zmin = QMAX( zmin, z-14 );
				}
				else
				{
					zmin = QMAX( zmin, target.z+1 );
				}

				//Console::instance()->send( QString( "y3:zmin:%1,zmax:%2\n" ).arg( zmin ).arg( zmax ) );

				if( (*pit).y == target.y )
				{
					targetpos = true;
					if( (dz_up >= 0) && (dz_down >= 0) )
					{
						if( zmin < target.z )
						{
							zmax = target.z -1;
						}
						else
						{
							//we ignore this coordinate
							++pit;
							continue;
						}
					}
					else if( (dz_up <= 0) && (dz_down <= 0) )
					{
						if( zmax > target.z + targetheight+1 )
						{
							zmin = target.z + targetheight + 2;
						}
						else
						{
							++pit;
							continue;
						}
					}
					else 
					{
						//we may have to split the test into two if we would do it exactly
						//but i think we can throw away the test from down in this case
						if( zmax > target.z + targetheight+1 )
						{
							zmin = target.z + targetheight + 2;
						}
						else if( zmin < target.z )
						{
							zmax = target.z -1;
						}
						else
						{
							++pit;
							continue;
						}
					}
					//Console::instance()->send( QString( "y4:zmin:%1,zmax:%2\n" ).arg( zmin ).arg( zmax ) );
				}
			}
			else if( sgn_y == 0 )
			{
				z1_up = target.z + targetheight - dz_up*( fabs( (double)target.x - (double)((*pit).x) ) -0.5 ); 
				z2_up = target.z + targetheight - dz_up*( fabs( (double)target.x - (double)((*pit).x) ) +0.5 );
			
				z1_down = target.z - dz_down*( fabs( (double)target.x - (double)((*pit).x) ) -0.5 );
				z2_down = target.z - dz_down*( fabs( (double)target.x - (double)((*pit).x) ) +0.5 );

				//Console::instance()->send( QString( "tx:%2,cx:%3\n" ).arg( target.x ).arg( (*pit).x ) );
				//Console::instance()->send( QString( "z1_up:%1,z2_up:%2,z1_down:%3,z2_down:%4\n" ).arg( z1_up ).arg( z2_up ).arg( z1_down ).arg( z2_down ) );

				zmax = QMAX( ceil( z1_up ), ceil( z2_up ) );
				zmin = QMIN( floor( z1_down ), floor( z2_down ) );

				if( dz_up > 0 )
				{
					zmax = QMIN( zmax, target.z+targetheight );
				}
				else
				{
					zmax = QMIN( zmax, z );
				}

				if( dz_down > 0 )
				{
					zmin = QMAX( zmin, z-14 );
				}
				else
				{
					zmin = QMAX( zmin, target.z+1 );
				}

				if( (*pit).x == target.x )
				{
					targetpos = true;
					if( (dz_up >= 0) && (dz_down >= 0) )
					{
						if( zmin < target.z )
						{
							zmax = target.z -1;
						}
						else
						{
							//we ignore this coordinate
							++pit;
							continue;
						}
					}
					else if( (dz_up <= 0) && (dz_down <= 0) )
					{
						if( zmax > target.z + targetheight+1 )
						{
							zmin = target.z + targetheight + 2;
						}
						else
						{
							++pit;
							continue;
						}
					}
					else 
					{
						//we may have to split the test into two if we would do it exactly
						//but i think we can throw away the test from down in this case
						if( zmax > target.z + targetheight+1 )
						{
							zmin = target.z + targetheight + 2;
						}
						else if( zmin < target.z )
						{
							zmax = target.z -1;
						}
						else
						{
							++pit;
							continue;
						}
					}
				}
			}
			else
			{
				double gradx_up = ( (double)target.y*(double)z - (double)y*(double)(target.z + targetheight) ) / ( (double)target.y*(double)x - (double)y*(double)target.x );
				double grady_up = ( (double)target.x*(double)z - (double)x*(double)(target.z + targetheight) ) / ( (double)y*(double)target.x - (double)target.y*(double)x );
				double gradx_down = ( (double)target.y*(double)(z-15) - (double)y*(double)(target.z) ) / ( (double)target.y*(double)x - (double)y*(double)target.x );
				double grady_down = ( (double)target.x*(double)(z-15) - (double)x*(double)(target.z) ) / ( (double)y*(double)target.x - (double)target.y*(double)x );

				//Console::instance()->send( QString( "gradx_up:%1,grady_up:%2,gradx_down:%3,grady_down:%4\n" ).arg( gradx_up ).arg( grady_up ).arg( gradx_down ).arg( grady_down ) );
				//Console::instance()->send( QString( "Gradient:%1,Offset:%2\n" ).arg( gradient ).arg( offset ) );

				double temp = specialFloor( gradient*( (double)((*pit).x) - 0.5 ) + offset );
				//Console::instance()->send( QString( "temp1:%1\n" ).arg( temp ) );
				if( ( temp >= ((double)((*pit).y)-0.5) ) && ( temp <= ((double)((*pit).y)+0.5) ) )
				{
					if( z1_up > -300 )
					{
						z2_up = gradx_up * ( (double)((*pit).x)-0.5 ) + grady_up * temp;
						z2_down = gradx_down * ( (double)((*pit).x)-0.5 ) + grady_down * temp;
					}
					else
					{
						z1_up = gradx_up * ( (double)((*pit).x)-0.5 ) + grady_up * temp;
						z1_down = gradx_down * ( (double)((*pit).x)-0.5 ) + grady_down * temp;
					}
					//Console::instance()->send( QString( "tx:%1,ty:%2,cy:%3,cy:%4\n" ).arg( target.x ).arg( target.y ).arg( (*pit).x ).arg( (*pit).y ) );
					//Console::instance()->send( QString( "z1_up:%1,z1_down:%2,z2_up:%3,z2_down:%4\n" ).arg( z1_up ).arg( z1_down ).arg( z2_up ).arg( z2_down ) );
				}
				temp = specialFloor( gradient*( (double)((*pit).x) + 0.5 ) + offset );
				//Console::instance()->send( QString( "temp2:%1\n" ).arg( temp ) );
				if( ( temp >= ((double)((*pit).y)-0.5) ) && ( temp <= ((double)((*pit).y)+0.5) ) )
				{
					if( z1_up > -300 )
					{
						z2_up = gradx_up * ( (double)((*pit).x)+0.5 ) + grady_up * temp;
						z2_down = gradx_down * ( (double)((*pit).x)+0.5 ) + grady_down * temp;
					}
					else
					{	
						z1_up = gradx_up * ( (double)((*pit).x)+0.5 ) + grady_up * temp;
						z1_down = gradx_down * ( (double)((*pit).x)+0.5 ) + grady_down * temp;
					}
					//Console::instance()->send( QString( "tx:%1,ty:%2,cy:%3,cy:%4\n" ).arg( target.x ).arg( target.y ).arg( (*pit).x ).arg( (*pit).y ) );
					//Console::instance()->send( QString( "z1_up:%1,z1_down:%2,z2_up:%3,z2_down:%4\n" ).arg( z1_up ).arg( z1_down ).arg( z2_up ).arg( z2_down ) );
				}
				temp = specialFloor( (double)((*pit).y) - 0.5 - offset ) / gradient;
				//Console::instance()->send( QString( "temp3:%1\n" ).arg( temp ) );
				if( ( temp > ((double)((*pit).x)-0.5) ) && ( temp < ((double)((*pit).x)+0.5) ) )
				{
					if( z1_up > -300 )
					{
						z2_up = gradx_up * temp + grady_up * ((double)((*pit).y)-0.5);
						z2_down = gradx_down * temp + grady_down * ((double)((*pit).y)-0.5);
					}
					else
					{
						z1_up = gradx_up * temp + grady_up * ((double)((*pit).y)-0.5);
						z1_down = gradx_down * temp + grady_down * ((double)((*pit).y)-0.5);
					}
					//Console::instance()->send( QString( "tx:%1,ty:%2,cy:%3,cy:%4\n" ).arg( target.x ).arg( target.y ).arg( (*pit).x ).arg( (*pit).y ) );
					//Console::instance()->send( QString( "z1_up:%1,z1_down:%2,z2_up:%3,z2_down:%4\n" ).arg( z1_up ).arg( z1_down ).arg( z2_up ).arg( z2_down ) );
				}
				temp = specialFloor( (double)((*pit).y) + 0.5 - offset ) / gradient;
				//Console::instance()->send( QString( "temp4:%1\n" ).arg( temp ) );
				if( ( temp > ((double)((*pit).x)-0.5) ) && ( temp < ((double)((*pit).x)+0.5) ) )
				{
					if( z1_up > -300 )
					{
						z2_up = gradx_up * temp + grady_up * ((double)((*pit).y)+0.5);
						z2_down = gradx_down * temp + grady_down * ((double)((*pit).y)+0.5);
					}
					else
					{
						z1_up = gradx_up * temp + grady_up * ((double)((*pit).y)+0.5);
						z1_down = gradx_down * temp + grady_down * ((double)((*pit).y)+0.5);
					}
					//Console::instance()->send( QString( "tx:%1,ty:%2,cy:%3,cy:%4\n" ).arg( target.x ).arg( target.y ).arg( (*pit).x ).arg( (*pit).y ) );
					//Console::instance()->send( QString( "z1_up:%1,z1_down:%2,z2_up:%3,z2_down:%4\n" ).arg( z1_up ).arg( z1_down ).arg( z2_up ).arg( z2_down ) );
				}

				//Console::instance()->send( QString( "ergebnis: z1_up:%1,z1_down:%2,z2_up:%3,z2_down:%4\n" ).arg( z1_up ).arg( z1_down ).arg( z2_up ).arg( z2_down ) );

				if( z2_up == -300 )
				{
					zmin = floor( z1_down );
					zmax = ceil( z1_up );
				}
				else
				{
					zmin = QMIN( floor( z1_down ), floor( z2_down ) );
					zmax = QMAX( ceil( z1_up ), ceil( z2_up ) );
				}

				//Console::instance()->send( QString( "zmin:%1,zmax:%2\n" ).arg( zmin ).arg( zmax ) );

				if( dz_up > 0 )
				{
					zmax = QMIN( zmax, target.z+targetheight );
				}
				else
				{
					zmax = QMIN( zmax, z );
				}

				if( dz_down > 0 )
				{
					zmin = QMAX( zmin, z-14 );
				}
				else
				{
					zmin = QMAX( zmin, target.z+1 );
				}

				//Console::instance()->send( QString( "zmin:%1,zmax:%2\n" ).arg( zmin ).arg( zmax ) );

				if( ((*pit).x == target.x) && ((*pit).y == target.y) )
				{
					targetpos = true;
					if( (dz_up >= 0) && (dz_down >= 0) )
					{
						if( zmin < target.z )
						{
							zmax = target.z -1;
						}
						else
						{
							//we ignore this coordinate
							++pit;
							continue;
						}
					}
					else if( (dz_up <= 0) && (dz_down <= 0) )
					{
						if( zmax > target.z + targetheight+1)
						{
							zmin = target.z + targetheight + 2;
						}
						else
						{
							++pit;
							continue;
						}
					}
					else 
					{
						//we may have to split the test into two if we would do it exactly
						//but i think we can throw away the test from down in this case
						if( zmax > target.z + targetheight+1 )
						{
							zmin = target.z + targetheight + 2;
						}
						else if( zmin < target.z )
						{
							zmax = target.z -1;
						}
						else
						{
							++pit;
							continue;
						}
					}
				}				
			}
			//Console::instance()->send( QString( "zmin:%1,zmax:%2\n" ).arg( zmin ).arg( zmax ) );

			// Texture mapping  
			map1 = Map->seekMap( *pit );
			map2 = Map->seekMap( Coord_cl( (*pit).x + sgn_x, (*pit).y + sgn_y, (*pit).z, map ) );
			
			//Console::instance()->send( QString( "try2" ) );
			StaticsIterator msi = Map->staticsIterator( *pit );
			RegionIterator4Items rj( (*pit), 0 );
			if( (map1.id != 2) && (map2.id != 2) ) 
			{
				if( ( map1.z > zmin ) && ( map1.z < zmax ) )
				{
					//its just in our way
					//Console::instance()->send( QString( "map cut 1\n" ) );
					return false;
				}
				
				//now we have to test, if this tile is under our line and the next above or
				//vice verse
				//in this case, both dont cut our line, but the mapconnection between them
				//should do
				land_st tile = TileCache::instance()->getLand( map1.id );
				if( ( ( map1.z < map2.z ) && ( map1.z < zmin ) && ( map2.z > zmax+dz_down ) && !targetpos ) ||						// 1) lineofsight collides with a map "wall"
					( ( map1.z > map2.z ) && ( map1.z > zmin ) && ( map2.z < zmin+dz_down ) && !targetpos ) ||
					( tile.isBlocking() && posHigherThanMap && msi.atEnd() && rj.atEnd() ) )
				{
					//Console::instance()->send( QString( "map1:%1,map2:%2,map1id:%3\n" ).arg( map1.z ).arg( map2.z ).arg( map1.id ) );
					if( ( map1.z < map2.z ) && ( map1.z < zmin ) && ( map2.z > zmax+dz_down ) )
					{
						//Console::instance()->send( QString( "mapcut1\n" ) ); 
					}
					else if( ( map1.z > map2.z ) && ( map1.z > zmin ) && ( map2.z < zmin+dz_down ) )
					{
						//Console::instance()->send( QString( "mapcut2\n" ) );
					}
					else if( tile.isBlocking() && posHigherThanMap && msi.atEnd() && rj.atEnd() )
					{
						//Console::instance()->send( QString( "mapcut3\n" ) );
					}
					else
					{
						//Console::instance()->send( QString( "mapcut: this isnt possible\n" ) );
					}
					return false;
				}
			}	 
			
			//Console::instance()->send( QString( "after map\n" ) );
		
			// Statics
			tile_st tile;
			while( !msi.atEnd() )
			{
				tile = TileCache::instance()->getTile( msi->itemid );
				//Console::instance()->send( QString( "statictilepos:%1,zmax:%2,zmin:%3\n" ).arg( msi->zoff ).arg( zmax ).arg( zmin ) );
				//if it is in our way
				if(	( zmax >= msi->zoff ) && ( zmin <= ( msi->zoff + tile.height ) ) )
				{
					if( tile.isBlocking() || tile.isRoofOrFloorTile() )
					{
						return false;
					}
				}
			
				++msi;
			}
			
			//Console::instance()->send( QString( "after statics\n" ) );
			// Items
			//Console::instance()->send( QString( "Items at: %1,%2,%3,%4\n" ).arg( (*pit).x ).arg( (*pit).y ).arg( (*pit).z ).arg( (*pit).map ) );
			for( rj.Begin(); !rj.atEnd(); rj++ )
			{
				//Console::instance()->send( QString( "foritem\n" ) );
				P_ITEM pi = rj.GetData();
				if( pi && pi->id() < 0x4000 )
				{
					tile = TileCache::instance()->getTile( pi->id() );
					//Console::instance()->send( QString( "itemtilepos:%1,zmax:%2,zmin:%3\n" ).arg( pi->pos().z ).arg( zmax ).arg( zmin ) );
					if(	( zmax >= pi->pos().z ) && ( zmin <= ( pi->pos().z + tile.height ) ) && ( pi->visible() == 0 ) )
					{
						if( tile.isBlocking() || tile.isRoofOrFloorTile() )
						{
							//Console::instance()->send( QString( "Item:%1,Z:%2,Height:%3\n" ).arg( pi->id() ).arg( pi->pos().z ).arg( tile.height ) );
							return false;
						}
					}	
				}
			}
			
			//Console::instance()->send( QString( "after items\n" ) );
			// Multis
			QPtrListIterator< cItem > mit( multis );
			P_ITEM pi;
			while( ( pi = mit.current() ) )
			{
				MultiDefinition* def = MultiCache::instance()->getMulti( pi->id() - 0x4000 );
				if ( !def )
				{
					++mit;
					continue;
				}
				QValueVector<multiItem_st> multi = def->getEntries();
				for( j = 0; j < multi.size(); ++j )
				{
					if( ( multi[j].visible ) && ( pi->pos().x + multi[j].x == (*pit).x ) &&
						( pi->pos().y + multi[j].y == (*pit).y ) )			
					{
						tile = TileCache::instance()->getTile( multi[j].tile );
						if( ( zmax >= pi->pos().z + multi[j].z ) &&
							( zmin <= pi->pos().z + multi[j].z + tile.height ) )
						{
							if( tile.isBlocking() || tile.isRoofOrFloorTile() )
							{
								return false;							
							}
						}	
					}
				}
				++mit;
			}
			//Console::instance()->send( QString( "after multis\n" ) );
			++pit;
		}
		return true;
	}
}
示例#25
0
void
UpdateScreen::slotUpdate()
{
    QString from = _fromVersion->text();
    QString to = _toVersion->currentText();

    if (from == to) {
	qApp->beep();
	QString message = tr("Versions must be different");
	QMessageBox::critical(this, tr("Error"), message);
	return;
    }

    // Connect to company database
    Driver* driver = Driver::getDriver(_company.dbType());
    if (driver == NULL) {
	qApp->beep();
	QString message = tr("Get driver failed: %1").arg(driver->lastError());
	QMessageBox::critical(this, tr("Error"), message);
	return;
    }

    _connection = driver->allocConnection();
    if (!_connection->dbaConnect(_company.database())) {
	qApp->beep();
	QString message = tr("Open company failed: %1")
	    .arg(_connection->lastError());
	QMessageBox::critical(this, tr("Error"), message);
	return;
    }

    ServerConfig config;
    config.load();

    QString dataDir = parseDir(config.dataDir);
    QString version = to;

    QValueVector<DataModel> models;
    while (true) {
	QString filePath = dataDir + "/models/" + version + ".xml";
	DataModel model;
	if (!model.load(filePath)) {
	    qApp->beep();
	    QString message = tr("Failed loading model: %1").arg(filePath);
	    QMessageBox::critical(this, tr("Error"), message);
	    return;
	}

	if (model.fromVersion.isEmpty()) {
	    qApp->beep();
	    QString message = tr("Didn't find version: " + from);
	    QMessageBox::critical(this, tr("Error"), message);
	    return;
	}

	models.push_back(model);
	version = model.fromVersion;
	if (version == from) break;
    }

    if (models.size() == 0) {
	qApp->beep();
	QString message = tr("No models found for update use");
	QMessageBox::critical(this, tr("Error"), message);
	return;
    }

    QString dbType = _company.dbType();
    for (int i = models.size() - 1; i >= 0; --i) {
	DataModel& model = models[i];
	bool good = true;

	QValueVector<UpdateDefn> completed;
	for (unsigned int j = 0; j < model.updates.size(); ++j) {
	    UpdateDefn& update = model.updates[j];

	    // Only run update if its for All or the right type
	    if (!update.databases.contains("All"))
		if (!update.databases.contains(dbType))
		    continue;

	    // Run update commands catching errors
	    for (unsigned int k = 0; k < update.updateCmds.size(); ++k) {
		QString cmd = update.updateCmds[k];
		Stmt stmt(_connection, cmd);
		if (!stmt.execute()) {
		    qWarning(stmt.lastError());
		    good = false;
		    break;
		}
	    }

	    completed.push_back(update);
	}

	// If good then try to run cleanup commands
	if (good) {
	    for (unsigned int j = 0; j < completed.size(); ++j) {
		UpdateDefn& update = completed[j];

		for (unsigned int k = 0; k < update.cleanupCmds.size(); ++k) {
		    QString cmd = update.cleanupCmds[k];
		    Stmt stmt(_connection, cmd);
		    if (!stmt.execute()) {
			qWarning(stmt.lastError());
			good = false;
			break;
		    }
		}
	    }
	}

	// If still good then update version in database
	if (good) {
	    QString cmd = "update db_config set config_value='" +
		model.version + "' where config_key='version'";
	    Stmt stmt(_connection, cmd);
	    if (!stmt.execute()) {
		qWarning(stmt.lastError());
		good = false;
	    }
	    _connection->commit();
	}

	// If failed then run restore commands and inform user
	if (!good) {
	    for (unsigned int j = 0; j < completed.size(); ++j) {
		UpdateDefn& update = completed[j];

		for (unsigned int k = 0; k < update.restoreCmds.size(); ++k) {
		    QString cmd = update.restoreCmds[k];
		    Stmt stmt(_connection, cmd);
		    if (!stmt.execute()) {
			qWarning(stmt.lastError());
		    }
		}
	    }

	    qApp->beep();
	    QString message = tr("Update failed on version: " + model.version);
	    QMessageBox::critical(this, tr("Error"), message);
	    close();
	    return;
	}

	// Set new version in CompanyDefn
	CompanyDefn company = _company;
	company.setVersion(model.version);
	company.save(company.filePath(), true);
	_company = company;
    }

    QMessageBox::information(this, tr("Finished"), tr("Update successful"));
    close();
}
示例#26
0
int main(int argc, char** argv)
{
	if (argc < 2)
		return 0;

	QValueVector<KeramikEmbedImage> images;

	cout<<"#include <qintdict.h>\n\n";
	cout<<"#include \"keramikimage.h\"\n\n";

	QMap<QString, int> assignID;
	int nextID = 0;

	for (int c = 1; c<argc; c++)
	{

		QImage input(argv[c]);


		QFileInfo fi(argv[c]);
		QString s = fi.baseName();

		KeramikEmbedImage image;

		int pos;

		QString id = s;

		int readJustID = 0;


		if ((pos = s.findRev("-")) != -1)
		{
				int suffix = evalSuffix(s.mid(pos));
				if (suffix !=-1 )
				{
						id = s.mid(0,pos);
						readJustID = suffix;
				}
		}

		if (!assignID.contains(id))
		{
			assignID[id] = nextID;
			nextID += 256;
		}

		s.replace("-","_");


		if (s.contains("button"))
			KImageEffect::contrastHSV(input);

		int fullID = assignID[id] + readJustID;//Subwidget..

		bool highlights = true;
		bool shadows  = true;

		float gamma    = 1.0;
		int brightAdj = 0;



		if (s.contains("toolbar") || s.contains("tab-top-active") || s.contains("menubar") )
		{
//			highlights = false;
			gamma    = 1/1.25f;
			//brightAdj = 10;
			shadows = false;
		}

		if (s.contains("scrollbar") && s.contains("groove"))
		{
			//highlights = false;
			//gamma = 1.5;
			shadows = false;
		}
			//brightAdj = -10;

		if (s.contains("scrollbar") && s.contains("slider"))
		{
			//highlights = false;
			gamma =1/0.7f;
			//shadows = false;
		}


		if (s.contains("menuitem"))
		{
			//highlights = false;
			gamma =1/0.6f;
			//shadows = false;
		}

		image.width   = input.width();
		image.height = input.height();
		image.id         = fullID;
		image.data     = reinterpret_cast<unsigned char*>(strdup(s.latin1()));


		bool reallySolid = true;

		int pixCount = 0;
		int pixSolid = 0;

		cout<<"static const unsigned char "<<s.latin1()<<"[]={\n";

		Q_UINT32* read  = reinterpret_cast< Q_UINT32* >(input.bits() );
		int size = input.width()*input.height();

		for (int pos=0; pos<size; pos++)
		{
			QRgb basePix = (QRgb)*read;

			if (qAlpha(basePix) != 255)
				reallySolid = false;
			else
				pixSolid++;

			pixCount++;
			read++;
		}

		image.haveAlpha = !reallySolid;

		images.push_back(image);

		read  = reinterpret_cast< Q_UINT32* >(input.bits() );
		for (int pos=0; pos<size; pos++)
		{
			QRgb basePix = (QRgb)*read;
			//cout<<(r*destAlpha.alphas[pos])<<"\n";
			//cout<<(int)destAlpha.alphas[pos]<<"\n";
			QColor clr(basePix);
			int h,s,v;
			clr.hsv(&h,&s,&v);

			v=qGray(basePix);

			int targetColorAlpha = 0 , greyAdd = 0;
			//int srcAlpha = qAlpha(basePix);

			if (s>0 || v > 128)
			{ //Non-shadow
				float fv = v/255.0;
				fv = pow(fv, gamma);
				v = int(255.5*fv);


				if (s<17 && highlights) //A bit of a highligt..
				{
					float effectPortion = (16 - s)/15.0;

					greyAdd             = (int)(v/4.0 * effectPortion*1.2);
					targetColorAlpha = v - greyAdd;
				}
				else
				{
					targetColorAlpha = v;//(int)(fv*255);
					greyAdd              = 0;
				}
			}
			else
			{
				if (shadows)
				{
					targetColorAlpha = 0;
					greyAdd              = v;
				}
				else
				{
					targetColorAlpha = v;//(int)(fv*255);
					greyAdd              = 0;
				}
			}

			greyAdd+=brightAdj;

			if (reallySolid)
				cout<<targetColorAlpha<<","<<greyAdd<<",";
			else
				cout<<targetColorAlpha<<","<<greyAdd<<","<<qAlpha(basePix)<<",";
			//cout<<qRed(basePix)<<","<<qGreen(basePix)<<","<<qBlue(basePix)<<","<<qAlpha(basePix)<<",";

			if (pos%8 == 7)
				cout<<"\n";

			read++;
		}

		cerr<<s.latin1()<<":"<<pixSolid<<"/"<<pixCount<<"("<<reallySolid<<")\n";

		cout<<!reallySolid<<"\n";

		cout<<"};\n\n";
	}

	cout<<"static const KeramikEmbedImage  image_db[] = {\n";

	for (unsigned int c=0; c<images.size(); c++)
	{
		cout<<"\t{ "<<(images[c].haveAlpha?"true":"false")<<","<<images[c].width<<", "<<images[c].height<<", "<<images[c].id<<", "<<(char *)images[c].data<<"},";
		cout<<"\n";
	}
	cout<<"\t{0, 0, 0, 0, 0}\n";
	cout<<"};\n\n";

	cout<<"class KeramikImageDb\n";
	cout<<"{\n";
	cout<<"public:\n";
	cout<<"\tstatic KeramikImageDb* getInstance()\n";
	cout<<"\t{\n";
	cout<<"\t\tif (!instance) instance = new KeramikImageDb;\n";
	cout<<"\t\treturn instance;\n";
	cout<<"\t}\n\n";
	cout<<"\tstatic void release()\n";
	cout<<"\t{\n";
	cout<<"\t\tdelete instance;\n";
	cout<<"\t\tinstance=0;\n";
	cout<<"\t}\n\n";
	cout<<"\tKeramikEmbedImage* getImage(int id)\n";
	cout<<"\t{\n";
	cout<<"\t\treturn images[id];\n";
	cout<<"\t}\n\n";
	cout<<"private:\n";
	cout<<"\tKeramikImageDb():images(503)\n";
	cout<<"\t{\n";
	cout<<"\t\tfor (int c=0; image_db[c].width; c++)\n";
	cout<<"\t\t\timages.insert(image_db[c].id, &image_db[c]);\n";
	cout<<"\t}\n";
	cout<<"\tstatic KeramikImageDb* instance;\n";
	cout<<"\tQIntDict<KeramikEmbedImage> images;\n";
	cout<<"};\n\n";
	cout<<"KeramikImageDb* KeramikImageDb::instance = 0;\n\n";

	cout<<"KeramikEmbedImage* KeramikGetDbImage(int id)\n";
	cout<<"{\n";
	cout<<"\treturn KeramikImageDb::getInstance()->getImage(id);\n";
	cout<<"}\n\n";

	cout<<"void KeramikDbCleanup()\n";
	cout<<"{\n";
	cout<<"\t\tKeramikImageDb::release();\n";
	cout<<"}\n";




	QFile file("keramikrc.h");
	file.open(IO_WriteOnly);
	QTextStream ts( &file);
	ts<<"#ifndef KERAMIK_RC_H\n";
	ts<<"#define KERAMIK_RC_H\n";

	ts<<"enum KeramikWidget {\n";
	for (QMap<QString, int>::iterator i = assignID.begin(); i != assignID.end(); ++i)
	{
		QString name = "keramik_"+i.key();
		name.replace("-","_");
		ts<<"\t"<<name<<" = "<<i.data()<<",\n";
	}
	ts<<"\tkeramik_last\n";
	ts<<"};\n";

	ts<<"#endif\n";

	return 0;
}
示例#27
0
bool TableEditor::setTableArea( int bLine, int bCol, int eLine, int eCol, Parser *docParser )
{
  const uint pInitialTableSize = 20;

  m_bLine = bLine;
  m_bCol = bCol;
  m_eLine = eLine;
  m_eCol = eCol;
  m_createNodes = false; //don't create the cell and row content when adding a new cell/row
  Node *node = docParser->nodeAt(bLine, bCol + 1);
  Node *lastNode = docParser->nodeAt(eLine, eCol);
  if (node)
    kdDebug(24000) << "node = " << node->tag->name << endl;
  if (lastNode)
    kdDebug(24000) << "lastnode = " << lastNode->tag->name << endl;
  if (!node || !lastNode)
    return false;
  m_write = node->tag->write();
  m_dtd = node->tag->dtd();
  if ( !QuantaCommon::closesTag(node->tag, lastNode->tag) ) {
    return false;
  }
  int nCol, nRow, maxCol;
  nCol = nRow = maxCol = 0;
  bool countRows = false;
  bool missingBody = false;
  m_rowSpin = 0L;
  m_colSpin = 0L;
  m_dataTable = 0L;
  QValueList<TableNode> tableRowTags;
  QValueVector< QValueVector<TableNode> > mergeMatrix;
  mergeMatrix.resize(pInitialTableSize);
  for (uint i = 0; i < pInitialTableSize; i++)
    mergeMatrix[i].resize(pInitialTableSize);
  TableNode tableNode;
  Node *n = node;
  while (n != lastNode->nextSibling())
  {
    QString tagName = n->tag->name.lower();
    if (tagName == "table")
    {
      if (m_table && m_dataTable && nRow > 0 && nCol > 0) //nested table!
      {
        int line, col;
        n->tag->beginPos(line, col);
        NestedTable table;
        table.row = nRow -1;
        table.col = nCol - 1;
        table.bLine = line;
        table.bCol = col;
        if (n->next && QuantaCommon::closesTag(n->tag, n->next->tag)) {
          n->next->tag->endPos(table.eLine, table.eCol);
          table.node = n;
          table.nestedData = m_write->text(table.bLine, table.bCol, table.eLine, table.eCol);
          m_nestedTables.append(table);
          m_dataTable->item(nRow -1, nCol -1)->setPixmap(QIconSet(UserIcon("quick_table")).pixmap());
          m_dataTable->updateCell(nRow - 1, nCol - 1);
        }
        n = n->next;
      } else
      {
        m_table = new Tag(*(n->tag));
        newNum++;
      }
    }
    else if (tagName == "thead")
    {
      headerCheckBox->setChecked(true);
      countRows = true;
      m_rowSpin = headerRowSpinBox;
      m_colSpin = headerColSpinBox;
      m_dataTable= headerTableData;
      m_tableTags = m_tableHeaderTags;
      m_tableRows = m_tableHeaderRows;
      if (m_thead) { //there was already a <thead> tag in the area
        nRow = m_dataTable->numRows();
      } else {
        m_thead = new Tag(*(n->tag));
        newNum++;
      }
    }
    else if (tagName == "/thead")
    {
      headerRowSpinBox->setValue(nRow);
      headerColSpinBox->setValue(maxCol);
      countRows = false;
      nCol = nRow = maxCol = 0;
      m_rowSpin = 0L;
      m_colSpin = 0L;
      m_dataTable = 0L;
    }
    else if (tagName == "tfoot")
    {
      footerCheckBox->setChecked(true);
      m_rowSpin = footerRowSpinBox;
      m_colSpin = footerColSpinBox;
      m_tableTags = m_tableFooterTags;
      m_tableRows = m_tableFooterRows;
      m_dataTable = footerTableData;
      countRows = true;
      if (m_tfoot) { //there was already a <tfoot> tag in the area
        nRow = m_dataTable->numRows();
      } else {
        m_tfoot = new Tag(*(n->tag));
        newNum++;
      }
    }
    else if (tagName == "/tfoot")
    {
      footerRowSpinBox->setValue(nRow);
      footerColSpinBox->setValue(maxCol);
      countRows = false;
      nCol = nRow = maxCol = 0;
      m_rowSpin = 0L;
      m_colSpin = 0L;
      m_dataTable = 0L;
    }
    else if (tagName == "tbody")
    {
      m_rowSpin = rowSpinBox;
      m_colSpin = colSpinBox;
      m_tableTags = m_tableDataTags;
      m_tableRows = m_tableDataRows;
      m_dataTable = tableData;
      countRows = true;
      m_tbody = new Tag(*(n->tag));
      newNum++;
    }
    else if (tagName == "/tbody")
    {
      rowSpinBox->setValue(nRow);
      colSpinBox->setValue(maxCol);
      countRows = false;
      nCol = nRow = maxCol = 0;
      m_tableTags = 0L;
      m_tableRows = 0L;
      m_rowSpin = 0L;
      m_colSpin = 0L;
      m_dataTable = 0L;
    }
    else if (tagName == "tr")
    {
      if (!countRows)
      {
        missingBody = true;
        m_rowSpin = rowSpinBox;
        m_colSpin = colSpinBox;
        m_tableTags = m_tableDataTags;
        m_tableRows = m_tableDataRows;
        m_dataTable = tableData;
        countRows = true;
        m_tbody = new Tag();
        newNum++;
        m_tbody->parse("<tbody>", m_write);
      }
      nRow++;
      if ((uint)nRow >= mergeMatrix.size()) {  // Check if there are enough rows in mergeMatriz
        mergeMatrix.resize(2 * mergeMatrix.size());
        for (uint i = mergeMatrix.size() / 2; i < mergeMatrix.size(); i++)
          mergeMatrix[i].resize(mergeMatrix[0].size());
      }

      m_rowSpin->setValue(nRow);
      nCol = 0;
      tableNode.node = new Node(0L);
      tableNode.node->tag = new Tag(*(n->tag));
      newNum++;
      tableNode.merged = false;
      m_tableRows->append(tableNode);
    }
    else if (tagName == "/tr")
    {
      if (countRows)
      {
        maxCol = (nCol > maxCol) ? nCol : maxCol;
        maxCol = (maxCol == 0) ? 1 : maxCol;
        for (int col = nCol; col < maxCol; col++)
        {
          if (mergeMatrix[nRow - 1][col].node != 0L) {
            if (m_colSpin->value() < col)
                m_colSpin->setValue(col);
            TableNode tableN = mergeMatrix[nRow - 1][col];
            Node *n = tableN.node;
            setCellText(m_dataTable, nRow - 1, col, i18n("Merged with (%1, %2).").arg(tableN.mergedRow + 1).arg(tableN.mergedCol + 1));
            m_dataTable->item(nRow-1, col)->setEnabled(false);
            tableNode.node = new Node(0L);
            tableNode.node->tag = new Tag(*(n->tag));
            configureCell(nRow-1,  col, tableNode.node);
            newNum++;
            tableNode.merged = true;
            tableNode.mergedRow = tableN.mergedRow;
            tableNode.mergedCol = tableN.mergedCol;
            tableRowTags.append(tableNode);
            if ((uint)nCol >= mergeMatrix[0].size())  // Check if there are enough cols
              for (uint i=0; i<mergeMatrix.size(); i++)
                mergeMatrix[i].resize(2 * mergeMatrix[i].size());
  
          } else
          {
            tableNode.node = new Node(0L);
            newNum++;
            tableNode.node->tag = new Tag();
            tableNode.node->tag->setDtd(m_dtd);
            tableNode.node->tag->parse("<td>", m_write);
            tableNode.merged = false;
            tableRowTags.append(tableNode);
          }
        }
        if (!tableRowTags.isEmpty())
          m_tableTags->append(tableRowTags);
        tableRowTags.clear();
      }
    }
    else if (tagName == "th" || tagName == "td")
    {
      if (countRows)
      {
        int col = nCol;
        while (mergeMatrix[nRow - 1][col].node != 0L) {
          if (m_colSpin->value() < col)
              m_colSpin->setValue(col);
          TableNode tableN = mergeMatrix[nRow - 1][col];
          Node *n = tableN.node;
          setCellText(m_dataTable, nRow - 1, col, i18n("Merged with (%1, %2).").arg(tableN.mergedRow + 1).arg(tableN.mergedCol + 1));
          m_dataTable->item(nRow-1, col)->setEnabled(false);
          tableNode.node = new Node(0L);
          tableNode.node->tag = new Tag(*(n->tag));
          configureCell(nRow-1,  col, tableNode.node);
          newNum++;
          tableNode.merged = true;
          tableNode.mergedRow = tableN.mergedRow;
          tableNode.mergedCol = tableN.mergedCol;
          tableRowTags.append(tableNode);
          col++;
          nCol++;
          if ((uint)nCol >= mergeMatrix[0].size())  // Check if there are enough cols
            for (uint i = 0; i < mergeMatrix.size(); i++)
              mergeMatrix[i].resize(2 * mergeMatrix[i].size());

        }
        nCol++;
        if (m_rowSpin && m_colSpin && m_dataTable)
        {
          m_rowSpin->setValue(nRow);
          if (m_colSpin->value() < nCol)
            m_colSpin->setValue(nCol);
          setCellText(m_dataTable, nRow - 1, nCol - 1, tagContent(n));
          tableNode.node = new Node(0L);
          tableNode.node->tag = new Tag(*(n->tag));
	        configureCell(nRow-1,  col, tableNode.node);
          newNum++;
          tableNode.merged = false;
          tableRowTags.append(tableNode);
        }
        QString colspanValue = n->tag->attributeValue("colspan", true);
        int colValue = 1;
        int lastCol = nCol;
        if (!colspanValue.isEmpty())
        {
          bool ok;
          colValue = colspanValue.toInt(&ok, 10);
          if (ok && colValue > 1)
          {
            nCol += (colValue - 1);
            if (m_colSpin->value() < nCol)
              m_colSpin->setValue(nCol);
            for (int i = 0; i < colValue - 1; i++)
            {
              setCellText(m_dataTable, nRow - 1, lastCol + i, i18n("Merged with (%1, %2).").arg(nRow).arg(lastCol));
              m_dataTable->item(nRow-1, lastCol + i)->setEnabled(false);
              tableNode.node = new Node(0L);
              tableNode.node->tag = new Tag(*(n->tag));
              configureCell(nRow-1,  col, tableNode.node);
              newNum++;
              tableNode.merged = true;
              tableNode.mergedRow = nRow - 1;
              tableNode.mergedCol = lastCol - 1;
              tableRowTags.append(tableNode);
            }
          } else
            colValue = 1;
        }
        QString rowspanValue = n->tag->attributeValue("rowspan", true);
        if (!rowspanValue.isEmpty())
        {
          bool ok;
          int rowValue = rowspanValue.toInt(&ok, 10);
          if (ok && rowValue > 1)
          {
            lastCol--;
            // Check if there are enough columns in mergeMatriz
            if ((uint)(lastCol + colValue) >= mergeMatrix[0].size())
              for (uint i = 0; i < mergeMatrix.size(); i++)
                mergeMatrix[i].resize(2 * mergeMatrix[i].size());
            // Check if there are enough rows in mergeMatriz
            if ((uint)(nRow + rowValue) >= mergeMatrix.size()) {
              mergeMatrix.resize(2 * mergeMatrix.size());
              for (uint i = mergeMatrix.size() / 2; i < mergeMatrix.size(); i++)
                mergeMatrix[i].resize(mergeMatrix[0].size());
            }

            for (int i = 0; i < rowValue - 1; i++)
              for (int j = 0; j < colValue; j++) {
                mergeMatrix[nRow + i][lastCol + j].mergedRow = nRow - 1;
                mergeMatrix[nRow + i][lastCol + j].mergedCol = lastCol;
                mergeMatrix[nRow + i][lastCol + j].node = n;
              }
          }
        }
      }
    }
    else if (tagName == "caption")
    {
      captionText->setText(tagContent(n));
    } else if (tagName == "col" || tagName == "colgroup") {
      m_colTags.append(n->tag);
    }
    n = n->nextSibling();
  }
/*  if (missingBody) { //Hm, why do we need it? I don't remember now. ;-)
      rowSpinBox->setValue(nRow);
      colSpinBox->setValue(maxCol);
  } */
  //by default the current page is the data handling page
  m_tableTags = m_tableDataTags;
  m_tableRows = m_tableDataRows;
  m_dataTable = tableData;
  m_rowSpin = rowSpinBox;
  m_colSpin = colSpinBox;

  //create the thead, tbody, tfoot tags if they were not present in the parsed area
  if (!m_thead) {
    m_thead = new Tag();
    newNum++;
    m_thead->parse("<thead>", m_write);
  }
  if (!m_tfoot) {
    m_tfoot = new Tag();
    newNum++;
    m_tfoot->parse("<tfoot>", m_write);
  }
  m_createNodes = true; //enable cell/row creation

  configureTable(tableData);
  configureTable(headerTableData);
  configureTable(footerTableData);
  return true;
}
示例#28
0
bool KAccelBase::updateConnections()
{
#ifdef Q_WS_X11
    kdDebug(125) << "KAccelBase::updateConnections()  this = " << this << endl;
    // Retrieve the list of keys to be connected, sorted by priority.
    //  (key, variation, seq)
    QValueVector< X > rgKeys;
    createKeyList(rgKeys);
    m_rgActionsNonUnique.clear();

    KKeyToActionMap mapKeyToAction;
    for(uint i = 0; i < rgKeys.size(); i++)
    {
        X &x = rgKeys[i];
        KKeyServer::Key &key = x.key;
        ActionInfo info;
        bool bNonUnique = false;

        info.pAction = m_rgActions.actionPtr(x.iAction);
        info.iSeq = x.iSeq;
        info.iVariation = x.iVari;

        // If this is a multi-key shortcut,
        if(info.pAction->shortcut().seq(info.iSeq).count() > 1)
            bNonUnique = true;
        // If this key is requested by more than one action,
        else if(i < rgKeys.size() - 1 && key == rgKeys[i + 1].key)
        {
            // If multiple actions requesting this key
            //  have the same priority as the first one,
            if(info.iVariation == rgKeys[i + 1].iVari && info.iSeq == rgKeys[i + 1].iSeq)
                bNonUnique = true;

            kdDebug(125) << "key conflict = " << key.key().toStringInternal() << " action1 = " << info.pAction->name()
                         << " action2 = " << m_rgActions.actionPtr(rgKeys[i + 1].iAction)->name() << " non-unique = " << bNonUnique << endl;

            // Skip over the other records with this same key.
            while(i < rgKeys.size() - 1 && key == rgKeys[i + 1].key)
                i++;
        }

        if(bNonUnique)
        {
            // Remove connection to single action if there is one
            if(m_mapKeyToAction.contains(key))
            {
                KAccelAction *pAction = m_mapKeyToAction[key].pAction;
                if(pAction)
                {
                    m_mapKeyToAction.remove(key);
                    disconnectKey(*pAction, key);
                    pAction->decConnections();
                    m_rgActionsNonUnique.append(pAction);
                }
            }
            // Indicate that no single action is associated with this key.
            m_rgActionsNonUnique.append(info.pAction);
            info.pAction = 0;
        }

        // kdDebug(125) << "mapKeyToAction[" << key.toStringInternal() << "] = " << info.pAction << endl;
        mapKeyToAction[key] = info;
    }

    // Disconnect keys which no longer have bindings:
    for(KKeyToActionMap::iterator it = m_mapKeyToAction.begin(); it != m_mapKeyToAction.end(); ++it)
    {
        const KKeyServer::Key &key = it.key();
        KAccelAction *pAction = (*it).pAction;
        // If this key is longer used or it points to a different action now,
        if(!mapKeyToAction.contains(key) || mapKeyToAction[key].pAction != pAction)
        {
            if(pAction)
            {
                disconnectKey(*pAction, key);
                pAction->decConnections();
            }
            else
                disconnectKey(key);
        }
    }

    // Connect any unconnected keys:
    // In other words, connect any keys which are present in the
    //  new action map, but which are _not_ present in the old one.
    for(KKeyToActionMap::iterator it = mapKeyToAction.begin(); it != mapKeyToAction.end(); ++it)
    {
        const KKeyServer::Key &key = it.key();
        KAccelAction *pAction = (*it).pAction;
        if(!m_mapKeyToAction.contains(key) || m_mapKeyToAction[key].pAction != pAction)
        {
            // TODO: Decide what to do if connect fails.
            //  Probably should remove this item from map.
            if(pAction)
            {
                if(connectKey(*pAction, key))
                    pAction->incConnections();
            }
            else
                connectKey(key);
        }
    }

    // Store new map.
    m_mapKeyToAction = mapKeyToAction;

#ifndef NDEBUG
    for(KKeyToActionMap::iterator it = m_mapKeyToAction.begin(); it != m_mapKeyToAction.end(); ++it)
    {
        kdDebug(125) << "Key: " << it.key().key().toStringInternal() << " => '" << (((*it).pAction) ? (*it).pAction->name() : QString::null) << "'"
                     << endl;
    }
#endif
#endif // Q_WS_X11
    return true;
}