Esempio n. 1
1
void QXmppSocksServer::slotReadyRead()
{
    QTcpSocket *socket = qobject_cast<QTcpSocket*>(sender());
    if (!socket || !m_states.contains(socket))
        return;

    if (m_states.value(socket) == ConnectState)
    {
        m_states.insert(socket, CommandState);

        // receive connect to server request
        QByteArray buffer = socket->readAll();
        if (buffer.size() < 3 ||
            buffer.at(0) != SocksVersion ||
            buffer.at(1) + 2 != buffer.size())
        {
            qWarning("QXmppSocksServer received invalid handshake");
            socket->close();
            return;
        }

        // check authentication method
        bool foundMethod = false;
        for (int i = 2; i < buffer.size(); i++)
        {
            if (buffer.at(i) == NoAuthentication)
            {
                foundMethod = true;
                break;
            }
        }
        if (!foundMethod)
        {
            qWarning("QXmppSocksServer received bad authentication method");
            socket->close();
            return;
        }

        // send connect to server response
        buffer.resize(2);
        buffer[0] = SocksVersion;
        buffer[1] = NoAuthentication;
        socket->write(buffer);

    } else if (m_states.value(socket) == CommandState) {
        m_states.insert(socket, ReadyState);

        // disconnect from signals
        disconnect(socket, SIGNAL(readyRead()), this, SLOT(slotReadyRead()));

        // receive command
        QByteArray buffer = socket->readAll();
        if (buffer.size() < 4 ||
            buffer.at(0) != SocksVersion ||
            buffer.at(1) != ConnectCommand ||
            buffer.at(2) != 0x00)
        {
            qWarning("QXmppSocksServer received an invalid command");
            socket->close();
            return;
        }

        // parse host
        quint8 hostType;
        QByteArray hostName;
        quint16 hostPort;
        if (!parseHostAndPort(buffer.mid(3), hostType, hostName, hostPort))
        {
            qWarning("QXmppSocksServer could not parse type/host/port");
            socket->close();
            return;
        }

        // notify of connection
        emit newConnection(socket, hostName, hostPort);

        // send response
        buffer.resize(3);
        buffer[0] = SocksVersion;
        buffer[1] = Succeeded;
        buffer[2] = 0x00;
        buffer.append(encodeHostAndPort(
            DomainName,
            hostName,
            hostPort));
        socket->write(buffer);
    }
}
Esempio n. 2
0
bool QPcxHandler::readPCX(QByteArray data, QImage *image)
{
    QDataStream input(data);
    if (data.isNull())
        input.setDevice(device());
    input.setByteOrder(QDataStream::LittleEndian);

    quint8 manufacturer, version, encoding, bitsPerPixel,
            reserved, colorPlanes;
    quint16 xMin, yMin, xMax, yMax, verticalDPI,
            horizontalDPI, bytesPerPlaneLine,
            paletteType, horizontalScreenSize, verticalScreenSize;

    input >> manufacturer;
    if (manufacturer != 0x0A)
        return false;

    input >> version;
    input >> encoding;
    if (encoding != 0)
        if (encoding != 1)
            return false;

    //Number of bits per pixel in each colour plane (1, 2, 4, 8, 24)
    input >> bitsPerPixel;
    switch (bitsPerPixel) {
    case 1:
    case 2:
    case 4:
    case 8:
    case 24:
        break;
    default: return false;
        break;
    }

    input >> xMin >> yMin >> xMax >> yMax;
    int width = xMax - xMin + 1;
    int height = yMax - yMin + 1;
    input >> verticalDPI >> horizontalDPI;

    //if bitsPerPixel <= 4 palette is present here
    quint8 byte;
    QByteArray colorMap;
    for (int i = 0; i<48; ++i) {
        input >> byte;
        colorMap.append(byte);
    }

    input >> reserved;
    if (reserved != 0)
        return false;

    //observed that pcx file format was badly designed since
    //the number of color planes was placed here and not before the
    //palette. it is needed for 16 color.
    input >> colorPlanes;
    input >> bytesPerPlaneLine;

    /* encountered uneven bytesPerPlaneLine so I decided not to check
     * it if it is an even number or not
    if (bytesPerPlaneLine%2 != 0)
        return false;
    */

    int fillerCount;
    input >> paletteType;
    if (version >= 4) {
        fillerCount = 54;
        input >> horizontalScreenSize >> verticalScreenSize;
    } else {
Esempio n. 3
0
int main(int argc, char** argv){
  
  
  QCoreApplication app(argc, argv);
  QDateTime logTime=QDateTime::currentDateTime();
  
  
  QTextStream standard_out(stdout);
  QTextStream standard_in(stdin);
  QTextStream file_out(stdout);
  QFile logFile(".spiedo.log");
  logFile.open(QIODevice::WriteOnly|QIODevice::Append);
  QTextStream log_out(&logFile);
  log_out << QObject::tr("####### - %1 - #######").arg( logTime.toString() )<< endl;
  
  
  
  
  QSerialPort * SerialSelected=Connection();
  if( SerialSelected == 0 )  return 1;
  ConfigurePort(SerialSelected);
  
  standard_out << QObject::tr("Serial is Configured") << endl;
  
  
  
  
  
  if( !SerialSelected->open(QIODevice::ReadWrite) ) {
    standard_out << QObject::tr(" Failed to open port %1, error: %2").arg(SerialSelected->portName()).arg(SerialSelected->errorString()) << endl;
    return 1;
    
  }else{
  standard_out << QObject::tr("Serial is open.") << endl;
  }
  
  SerialSelected->setRequestToSend(true);
  SerialSelected->setRequestToSend(false);
  
  standard_out << QObject::tr("Serial is Configuration:") << endl
               << QObject::tr("Baud rate: ") <<   SerialSelected->baudRate()  << endl
	       << QObject::tr("DataBit: ") <<   SerialSelected->dataBits() << endl
	       << QObject::tr("Parity: ") << ( SerialSelected->parity() )<< endl
               << QObject::tr("Stop Bits: ") << ( SerialSelected->stopBits() )<< endl
	       << QObject::tr("FlowControl:  ") << ( SerialSelected->flowControl() )<< endl
	       
	       ;
  SerialSelected->setRequestToSend(true);
  SerialSelected->setRequestToSend(false);

         
  
  QThread::sleep(2);
  
  char buf[64];                                                                    
  qint64 leghtbuf=0;
  while( ( SerialSelected->waitForReadyRead(10000) ) ){
    
    if( SerialSelected->canReadLine() ){
      leghtbuf=SerialSelected->readLine(buf,sizeof(buf));
      standard_out << buf << endl;
      if( leghtbuf >= 8 ) break;
      
    }
    standard_out << QObject::tr("Waiting for sketchCode") << endl;

  }
  
  if( leghtbuf == 0 ){
   standard_out << QObject::tr("Error: %1").arg(SerialSelected->errorString() ) << endl
		<< QObject::tr(" No sketchCode :(") << endl;
   return 1;
  }else{
    standard_out << QObject::tr("SketchCode recived!") << endl
		 << QObject::tr(" Code: %1 ").arg(buf) << endl
 		 << QObject::tr("Is it correct[Y/n]?\n>>") << flush
 		 ;
  }
  QString tmp;
  tmp=standard_in.readLine();
  if(  tmp[0] == 'n' ) return 0;
  SerialSelected->write("~");
  SerialSelected->flush();
  SerialSelected->waitForReadyRead(1000);
  SerialSelected->readAll();

  standard_out << QObject::tr("HandShake Terminate.") << endl;
  
  
  
  QByteArray Data;
  QByteArray dataBuffer;
  QString nameFile;
  QFile LogMisure;
  char command=' ';
  bool exit=false;
  
  
  standard_out << QObject::tr("Controllo della Seriale:") << endl
		     << QObject::tr("\t[r] Campiona per 1000 volte e restiusce la seguente stringa:") << endl
		     << QObject::tr("\t\t dutyCicle:Mean:Sigma") << endl
		     << QObject::tr("\t[w] Modifica il duty Cicle") << endl
		     << QObject::tr("\t[a] Fa una scansione completa sul duty Cicle da 0 a 255\n")
		     << QObject::tr("\t\t eseguendo ogni volta la lettura( vedi [r] )")<< endl
		     << QObject::tr("\t[t] Acquisisce misure raw dal fotodiodo ad intervalli regolari\n"
				    "\t\trestituendo ad ogni misura la stringa:\n\t\t\tclock:rawMeasure#\n"
				    "\t\tdove il clock è il tempo trascorso tra l'ultimo reset e la \n"
				    "\t\tmisura rawMeasure, espresso in microsecondi\n" ) << flush
		     << QObject::tr("\t[h] restituisce questo OutPut") << endl
		     << QObject::tr("\t[s] Salva su File") << endl
		     << QObject::tr("\t[q] Salva  Esce") << endl
		     ;
  SerialSelected->write("w");
  SerialSelected->flush();
  SerialSelected->write("0");
  SerialSelected->flush();
  
  
  
  while(true){
    standard_out << ">>" << flush;
    standard_in >> command;
    switch(command){
      case 'r':
	SerialSelected->write("r");
	SerialSelected->flush();
	SerialSelected->clear();
	
	while( ( SerialSelected->waitForReadyRead(10000) ) ){
    
	  if( SerialSelected->canReadLine() ){
	   
	    dataBuffer = SerialSelected->readAll();
	    standard_out << dataBuffer << flush;
	    log_out << QObject::tr("[r]:\n") << dataBuffer << flush;
	    dataBuffer.clear();
	    break;
	  }
	}
	SerialSelected->clear();
	SerialSelected->readAll();

        break;
	
      case 'w':
	SerialSelected->write("w");
	SerialSelected->flush();
	standard_out << QObject::tr("Inserire il valore della duty Cicle\n>>") << flush;
	standard_in >> tmp;
	SerialSelected->write(tmp.toStdString().c_str());
	SerialSelected->flush();
	SerialSelected->readAll();
	break;
	
	
	
      case 'a':
        SerialSelected->write("a");
	SerialSelected->flush();
	SerialSelected->clear();

	Data.append("#").append(logTime.toString("ddMMyyyy hhmmss") ).append("\n");
	Data.append("#Scanning on dutyCicle\n#duty\tmean\tsigma\n");
	{
	  QByteArray tmp_data;
	  bool breakWhile=false;
	  while( ( SerialSelected->waitForReadyRead(-1) ) ){
	      tmp_data.clear();
	      tmp_data.append( SerialSelected->readAll() );

	      
	      if( tmp_data.contains('$') ){
		tmp_data.remove( tmp_data.indexOf('$'),1 );
		standard_out << "ora esco" << endl;

		breakWhile=true;
	      }
	      tmp_data.replace(':','\t');
	      tmp_data.replace('%','\n');
	      standard_out << tmp_data << flush;
	      Data.append(tmp_data);
	      
	      
	      if( breakWhile ) break;
	  }
	}
	SerialSelected->readAll();
	
	break;
	
      case 't':
	SerialSelected->write("t");
	SerialSelected->flush();
	SerialSelected->clear();
	
	Data.append("#").append(logTime.toString("ddMMyyyy hhmmss") ).append("\n");
	Data.append("#Acquire ");
	standard_out << QObject::tr("Inserire il numero di misure che si vuole fare\n>>") << flush;
	standard_in >> tmp;
	SerialSelected->write(tmp.toStdString().c_str());
	SerialSelected->flush();
	
	Data.append(" measure\n#time\tMeasure\n");
	{
	  QByteArray tmp_data;
	  bool breakWhile=false;
	  while( ( SerialSelected->waitForReadyRead(10000) ) ){
	      standard_out << "dentro la lettura" << endl;
	      tmp_data.clear();
	      tmp_data.append( SerialSelected->readAll() );
	      
	      if( tmp_data.contains('$') ){
		standard_out << "ora esco" << endl;
		breakWhile=true;
	      }
	      tmp_data.replace(':','\t');
	      tmp_data.replace('%','\n');
	      tmp_data.replace('$','\n');
	      Data.append(tmp_data);
	      if( breakWhile ) break;
	  }
	}
	SerialSelected->readAll();
	break;
      case 's':
	save:
	if ( Data.isEmpty() ){
	  standard_out << QObject::tr("Nothing to save") << endl;
	  break;
	}
	standard_out << QObject::tr("Nome del file: ") << flush;
	
	standard_in >> nameFile;
	LogMisure.setFileName(nameFile);
	LogMisure.open(QIODevice::WriteOnly|QIODevice::Append);
	log_out << QObject::tr("Saving data in %1/ \b%2").arg( QDir::currentPath() ).arg( LogMisure.fileName() )  << endl;

	
	
	file_out.setDevice(&LogMisure);

	
	file_out << Data << flush;
	file_out.device()->close();
	Data.clear();
	break;
	
	
      case 'q':
	SerialSelected->write("q");
	SerialSelected->flush();
	SerialSelected->clear();

	exit=true;
	goto save;
	
	break;
	
      case 'h':
	standard_out << QObject::tr("Controllo della Seriale:") << endl
		     << QObject::tr("\t[r] Campiona per 1000 volte e restiusce la seguente stringa:") << endl
		     << QObject::tr("\t\t dutyCicle:Mean:Sigma") << endl
		     << QObject::tr("\t[w] Modifica il duty Cicle") << endl
		     << QObject::tr("\t[a] Fa una scansione completa sul duty Cicle da 0 a 255\n")
		     << QObject::tr("\t\teseguendo ogni volta la lettura( vedi [r] )")<< endl
		     << QObject::tr("\t[h] restituisce questo OutPut") << endl
		     << QObject::tr("\t[t] Acquisisce misure raw dal fotodiodo ad intervalli regolari\n"
				    "\t\trestituendo ad ogni misura la stringa:\n\t\t\tclock:rawMeasure#\n"
				    "\t\tdove il clock è il tempo trascorso tra l'ultimo reset e la \n"
				    "\t\tmisura raw Measure, espresso in microsecondi\n" ) << flush
		     << QObject::tr("\t[s] Salva su File") << endl
		     << QObject::tr("\t[q] Salva  Esce") << endl
		     ;
	break;
      default:
	if(exit) break;
    }
    if(exit) break;
    
    
  }
  return 0;
}
Esempio n. 4
0
static bool write_pbm_image(QIODevice *out, const QImage &sourceImage, const QByteArray &sourceFormat)
{
    QByteArray str;
    QImage image = sourceImage;
    QByteArray format = sourceFormat;

    format = format.left(3);                        // ignore RAW part
    bool gray = format == "pgm";

    if (format == "pbm") {
        image = image.convertToFormat(QImage::Format_Mono);
    } else if (image.depth() == 1) {
        image = image.convertToFormat(QImage::Format_Indexed8);
    } else {
        switch (image.format()) {
        case QImage::Format_RGB16:
        case QImage::Format_RGB666:
        case QImage::Format_RGB555:
        case QImage::Format_RGB888:
        case QImage::Format_RGB444:
            image = image.convertToFormat(QImage::Format_RGB32);
            break;
        case QImage::Format_ARGB8565_Premultiplied:
        case QImage::Format_ARGB6666_Premultiplied:
        case QImage::Format_ARGB8555_Premultiplied:
        case QImage::Format_ARGB4444_Premultiplied:
            image = image.convertToFormat(QImage::Format_ARGB32);
            break;
        default:
            break;
        }
    }

    if (image.depth() == 1 && image.colorCount() == 2) {
        if (qGray(image.color(0)) < qGray(image.color(1))) {
            // 0=dark/black, 1=light/white - invert
            image.detach();
            for (int y=0; y<image.height(); y++) {
                uchar *p = image.scanLine(y);
                uchar *end = p + image.bytesPerLine();
                while (p < end)
                    *p++ ^= 0xff;
            }
        }
    }

    uint w = image.width();
    uint h = image.height();

    str = "P\n";
    str += QByteArray::number(w);
    str += ' ';
    str += QByteArray::number(h);
    str += '\n';

    switch (image.depth()) {
        case 1: {
            str.insert(1, '4');
            if (out->write(str, str.length()) != str.length())
                return false;
            w = (w+7)/8;
            for (uint y=0; y<h; y++) {
                uchar* line = image.scanLine(y);
                if (w != (uint)out->write((char*)line, w))
                    return false;
            }
            }
            break;

        case 8: {
            str.insert(1, gray ? '5' : '6');
            str.append("255\n");
            if (out->write(str, str.length()) != str.length())
                return false;
            QVector<QRgb> color = image.colorTable();
            uint bpl = w*(gray ? 1 : 3);
            uchar *buf   = new uchar[bpl];
            for (uint y=0; y<h; y++) {
                uchar *b = image.scanLine(y);
                uchar *p = buf;
                uchar *end = buf+bpl;
                if (gray) {
                    while (p < end) {
                        uchar g = (uchar)qGray(color[*b++]);
                        *p++ = g;
                    }
                } else {
                    while (p < end) {
                        QRgb rgb = color[*b++];
                        *p++ = qRed(rgb);
                        *p++ = qGreen(rgb);
                        *p++ = qBlue(rgb);
                    }
                }
                if (bpl != (uint)out->write((char*)buf, bpl))
                    return false;
            }
            delete [] buf;
            }
            break;

        case 32: {
            str.insert(1, gray ? '5' : '6');
            str.append("255\n");
            if (out->write(str, str.length()) != str.length())
                return false;
            uint bpl = w*(gray ? 1 : 3);
            uchar *buf = new uchar[bpl];
            for (uint y=0; y<h; y++) {
                QRgb  *b = (QRgb*)image.scanLine(y);
                uchar *p = buf;
                uchar *end = buf+bpl;
                if (gray) {
                    while (p < end) {
                        uchar g = (uchar)qGray(*b++);
                        *p++ = g;
                    }
                } else {
                    while (p < end) {
                        QRgb rgb = *b++;
                        *p++ = qRed(rgb);
                        *p++ = qGreen(rgb);
                        *p++ = qBlue(rgb);
                    }
                }
                if (bpl != (uint)out->write((char*)buf, bpl))
                    return false;
            }
            delete [] buf;
            }
            break;

    default:
        return false;
    }

    return true;
}
Esempio n. 5
0
QByteArray SimThread::generatePacket(QByteArray header,QByteArray payload)
{
	QByteArray packet;
	packet.append((char)0xAA);
	unsigned char checksum = 0;
	for (int i=0;i<header.size();i++)
	{
		checksum += header[i];
	}
	for (int i=0;i<payload.size();i++)
	{
		checksum += payload[i];
	}
	payload.append(checksum);
	for (int j=0;j<header.size();j++)
	{
		if (header[j] == (char)0xAA)
		{
			packet.append((char)0xBB);
			packet.append((char)0x55);
		}
		else if (header[j] == (char)0xBB)
		{
			packet.append((char)0xBB);
			packet.append((char)0x44);
		}
		else if (header[j] == (char)0xCC)
		{
			packet.append((char)0xBB);
			packet.append((char)0x33);
		}
		else
		{
			packet.append(header[j]);
		}
	}
	for (int j=0;j<payload.size();j++)
	{
		if (payload[j] == (char)0xAA)
		{
			packet.append((char)0xBB);
			packet.append((char)0x55);
		}
		else if (payload[j] == (char)0xBB)
		{
			packet.append((char)0xBB);
			packet.append((char)0x44);
		}
		else if (payload[j] == (char)0xCC)
		{
			packet.append((char)0xBB);
			packet.append((char)0x33);
		}
		else
		{
			packet.append(payload[j]);
		}
	}
	//packet.append(header);
	//packet.append(payload);
	packet.append((char)0xCC);
	return packet;
}
Esempio n. 6
0
void SimThread::run()
{
	init = true;
	currentLocationPacket=0;
	currentLocationInfoPacket=0;
	QFile logfile(m_filename);
	if (!logfile.open(QIODevice::ReadOnly))
	{
		qDebug() << "Unable to open file. Exiting sim thread";
		return;
	}
	QByteArray logbytes = logfile.readAll();
	nextPacketIsLocation = false;

	QByteArray qbuffer;
	QList<QByteArray> m_queuedMessages;
	QString byteoutofpacket;
	bool m_inpacket = false;
	bool m_inescape = false;
	for (int i=0;i<logbytes.size();i++)
	{
		if ((unsigned char)logbytes[i] == 0xAA)
		{
			if (m_inpacket)
			{
				//Start byte in the middle of a packet
				//Clear out the buffer and start fresh
				m_inescape = false;
				qbuffer.clear();
			}
			//qbuffer.append(buffer[i]);
			//qDebug() << "Start of packet";
			//Start of packet
			m_inpacket = true;
		}
		else if ((unsigned char)logbytes[i] == 0xCC && m_inpacket)
		{
			//qDebug() << "End of packet. Size:" << qbuffer.size();
			//End of packet
			m_inpacket = false;
			//qbuffer.append(buffer[i]);

			//m_logFile->flush();
			//emit parseBuffer(qbuffer);


			//New Location of checksum
			unsigned char sum = 0;
			for (int i=0;i<qbuffer.size()-1;i++)
			{
				sum += qbuffer[i];
			}
			//qDebug() << "Payload sum:" << QString::number(sum);
			//qDebug() << "Checksum sum:" << QString::number((unsigned char)currPacket[currPacket.length()-1]);
			if (sum != (unsigned char)qbuffer[qbuffer.size()-1])
			{
				qDebug() << "BAD CHECKSUM!";
				//return QPair<QByteArray,QByteArray>();
			}
			else
			{
				m_queuedMessages.append(qbuffer.mid(0,qbuffer.length()-1));
			}
			//return qbuffer;
			QString output;
			for (int i=0;i<qbuffer.size();i++)
			{
				int num = (unsigned char)qbuffer[i];
				output.append(" ").append((num < 0xF) ? "0" : "").append(QString::number(num,16));
			}
			//qDebug() << "Full packet:";
			//qDebug() << output;
			qbuffer.clear();
		}
		else
		{
			if (m_inpacket && !m_inescape)
			{
				if ((unsigned char)logbytes[i] == 0xBB)
				{
					//Need to escape the next byte
					//retval = logfile.read(1);
					m_inescape = true;
				}
				else
				{
					qbuffer.append(logbytes[i]);
				}

			}
			else if (m_inpacket && m_inescape)
			{
				if ((unsigned char)logbytes[i] == 0x55)
				{
					qbuffer.append((char)0xAA);
				}
				else if ((unsigned char)logbytes[i] == 0x44)
				{
					qbuffer.append((char)0xBB);
				}
				else if ((unsigned char)logbytes[i] == 0x33)
				{
					qbuffer.append((char)0xCC);
				}
				else
				{
					qDebug() << "Error, escaped character is not valid!:" << QString::number(logbytes[i],16);
				}
				m_inescape = false;
			}
			else
			{
				//qDebug() << "Byte out of a packet:" << QString::number(buffer[i],16);
				byteoutofpacket += QString::number(logbytes[i],16) + " ";
			}
		}
	}
	//qDebug() << "Bytes out of a packet:" << byteoutofpacket;


	//Done.
	qDebug() << m_queuedMessages.size() << "Messages read in";
	for (int i=0;i<m_queuedMessages.size();i++)
	{
		Packet parsedPacket = parseBuffer(m_queuedMessages[i]);
		packetList.append(parsedPacket);
		//parsePacket(parsedPacket);
	}
	int fd=0;
#ifdef HAVE_POSIX_OPENPT
		fd = posix_openpt(O_RDWR | O_NOCTTY);
#else
		fd = open("/dev/ptmx",O_RDWR | O_NOCTTY);
#endif //HAVE_POSIX_OPENPT

		if(-1 == fd) {
#ifdef HAVE_POSIX_OPENPT
			perror("Error in posix_openpt");
#else
			perror("Error opening /dev/ptmx");
#endif //HAVE_POSIX_OPENPT
			return;
		}
		grantpt(fd);
		unlockpt(fd);

		struct termios oldtio;
		if(0 != tcgetattr(fd,&oldtio)) {
			perror("tcgetattr openpt warning");
		}
		//bzero(&newtio,sizeof(newtio));

		oldtio.c_cflag = CS8 | CLOCAL | CREAD; // CBAUD
		oldtio.c_iflag = IGNPAR | ICRNL;
		oldtio.c_oflag = 0;
		oldtio.c_lflag = ICANON & (~ECHO);

		oldtio.c_cc[VEOL]     = '\r';
		// oldtio.c_cc[VEOL2]    = 0;     /* '\0' */

		tcflush(fd,TCIFLUSH);
		if(0 != tcsetattr(fd,TCSANOW,&oldtio)) {
			perror("tcsetattr warning");
		}

#ifdef HAVE_PTSNAME_R
		if(0 != ptsname_r(fd, portname, sizeof(portname))) {
			perror("Couldn't get pty slave name");
		}
#else
		char *ptsname_val = ptsname(fd);
		if(NULL == ptsname_val) {
			perror("Couldn't get pty slave name");
		}
		QString portname = QString(ptsname_val);
		//strncpy(portname, ptsname_val, sizeof(portname));
#endif //HAVE_PTSNAME_R


	fcntl(fd,F_SETFL,O_NONBLOCK); // O_NONBLOCK + fdopen/stdio == bad

	qDebug() << "Port:" << portname << "opened for sim!";
	unsigned char buffer[1024];
	unsigned short nextlocationid;
	bool nextislocation = false;
	init = false;
	while (true)
	{
		int readlen = read(fd,buffer,1024);
		if (readlen < 0)
		{
			//Nothing on the port
			usleep(10000);
		}
		if (readlen == 0)
		{
			usleep(10000);
		}
		for (int i=0;i<readlen;i++)
		{
			if (buffer[i] == 0xAA)
			{
				if (m_inpacket)
				{
					//Start byte in the middle of a packet
					//Clear out the buffer and start fresh
					m_inescape = false;
					qbuffer.clear();
				}
				//qbuffer.append(buffer[i]);
				//qDebug() << "Start of packet";
				//Start of packet
				m_inpacket = true;
			}
			else if (buffer[i] == 0xCC && m_inpacket)
			{
				//qDebug() << "End of packet. Size:" << qbuffer.size();
				//End of packet
				m_inpacket = false;
				//qbuffer.append(buffer[i]);

				//m_logFile->flush();
				//emit parseBuffer(qbuffer);


				//New Location of checksum
				unsigned char sum = 0;
				for (int i=0;i<qbuffer.size()-1;i++)
				{
					sum += qbuffer[i];
				}
				//qDebug() << "Payload sum:" << QString::number(sum);
				//qDebug() << "Checksum sum:" << QString::number((unsigned char)currPacket[currPacket.length()-1]);
				if (sum != (unsigned char)qbuffer[qbuffer.size()-1])
				{
					qDebug() << "BAD CHECKSUM!";
					//return QPair<QByteArray,QByteArray>();
				}
				else
				{
					QByteArray fullmsg = qbuffer.mid(0,qbuffer.length()-1);
					Packet p = parseBuffer(fullmsg);
					if (p.payloadid == 0x0104 || p.payloadid == 0x0106)
					{
						Packet p2 = locationidList[currentLocationPacket++];
						QByteArray tosend = generatePacket(p2.header,p2.payload);
						write(fd,tosend.data(),tosend.length());
					}
					else if (p.payloadid == 0xF8E0)
					{
						Packet p2 = locationidInfoList[currentLocationInfoPacket++];
						QByteArray tosend = generatePacket(p2.header,p2.payload);
						write(fd,tosend.data(),tosend.length());

					}
					/*if (p.payloadid == 0x0106 || p.payloadid == 0x0108)
					{
						//Request for ram.
						if (nextislocation)
						{
							nextislocation = false;
							unsigned short lookforpayload = p.payloadid+1;
							for (int i=0;i<packetList.size();i++)
							{
								if (packetList[i].payloadid == lookforpayload)
								{
									unsigned short tmp = (((unsigned char)p.payload[0]) << 8) + (unsigned char)p.payload[1];
									//if (tmp == nextlocationid)
									//{
										QByteArray tosend = generatePacket(packetList[i].header,packetList[i].payload);
										write(fd,tosend.data(),tosend.length());
										break;
									//}
								}
							}
						}
					}*/
					else
					{
						unsigned short lookforpayload = p.payloadid+1;
						for (int i=0;i<packetList.size();i++)
						{
							if (packetList[i].payloadid == lookforpayload)
							{
								QByteArray tosend = generatePacket(packetList[i].header,packetList[i].payload);
								write(fd,tosend.data(),tosend.length());
								break;
							}
						}
					}

				}
				//return qbuffer;
				QString output;
				for (int i=0;i<qbuffer.size();i++)
				{
					int num = (unsigned char)qbuffer[i];
					output.append(" ").append((num < 0xF) ? "0" : "").append(QString::number(num,16));
				}
				//qDebug() << "Full packet:";
				//qDebug() << output;
				qbuffer.clear();
			}
			else
			{
				if (m_inpacket && !m_inescape)
				{
					if (buffer[i] == 0xBB)
					{
						//Need to escape the next byte
						//retval = logfile.read(1);
						m_inescape = true;
					}
					else
					{
						qbuffer.append(buffer[i]);
					}

				}
				else if (m_inpacket && m_inescape)
				{
					if (buffer[i] == 0x55)
					{
						qbuffer.append((char)0xAA);
					}
					else if (buffer[i] == 0x44)
					{
						qbuffer.append((char)0xBB);
					}
					else if (buffer[i] == 0x33)
					{
						qbuffer.append((char)0xCC);
					}
					else
					{
						qDebug() << "Error, escaped character is not valid!:" << QString::number(buffer[i],16);
					}
					m_inescape = false;
				}
				else
				{
					//qDebug() << "Byte out of a packet:" << QString::number(buffer[i],16);
					byteoutofpacket += QString::number(buffer[i],16) + " ";
				}
			}
		}
		//qDebug() << "Bytes out of a packet:" << byteoutofpacket;
	}
}
void BerTLV::appendTag(QByteArray& buffer) {
    // convert the hexstring to bytes
    QByteArray tagBytes = QByteArray::fromHex(_tag.toAscii());

    buffer.append(tagBytes);
}
Esempio n. 8
0
void Preprocessor::preprocess(const QByteArray &filename, Symbols &preprocessed)
{
    currentFilenames.push(filename);
    preprocessed.reserve(preprocessed.size() + symbols.size());
    while (hasNext()) {
        Token token = next();

        switch (token) {
        case PP_INCLUDE:
        {
            int lineNum = symbol().lineNum;
            QByteArray include;
            bool local = false;
            if (test(PP_STRING_LITERAL)) {
                local = lexem().startsWith('\"');
                include = unquotedLexem();
            } else
                continue;
            until(PP_NEWLINE);

            // #### stringery
            QFileInfo fi;
            if (local)
                fi.setFile(QFileInfo(QString::fromLocal8Bit(filename)).dir(), QString::fromLocal8Bit(include));
            for (int j = 0; j < Preprocessor::includes.size() && !fi.exists(); ++j) {
                const IncludePath &p = Preprocessor::includes.at(j);
                if (p.isFrameworkPath) {
                    const int slashPos = include.indexOf('/');
                    if (slashPos == -1)
                        continue;
                    QByteArray frameworkCandidate = include.left(slashPos);
                    frameworkCandidate.append(".framework/Headers/");
                    fi.setFile(QString::fromLocal8Bit(p.path + '/' + frameworkCandidate), QString::fromLocal8Bit(include.mid(slashPos + 1)));
                } else {
                    fi.setFile(QString::fromLocal8Bit(p.path), QString::fromLocal8Bit(include));
                }
                // try again, maybe there's a file later in the include paths with the same name
                // (186067)
                if (fi.isDir()) {
                    fi = QFileInfo();
                    continue;
                }
            }

            if (!fi.exists() || fi.isDir())
                continue;
            include = fi.canonicalFilePath().toLocal8Bit();

            if (Preprocessor::preprocessedIncludes.contains(include))
                continue;
            Preprocessor::preprocessedIncludes.insert(include);

            QFile file(QString::fromLocal8Bit(include));
            if (!file.open(QFile::ReadOnly))
                continue;

            QByteArray input = file.readAll();
            file.close();
            if (input.isEmpty())
                continue;

            Symbols saveSymbols = symbols;
            int saveIndex = index;

            // phase 1: get rid of backslash-newlines
            input = cleaned(input);

            // phase 2: tokenize for the preprocessor
            symbols = tokenize(input);
            input.clear();

            index = 0;

            // phase 3: preprocess conditions and substitute macros
            preprocessed += Symbol(0, MOC_INCLUDE_BEGIN, include);
            preprocess(include, preprocessed);
            preprocessed += Symbol(lineNum, MOC_INCLUDE_END, include);

            symbols = saveSymbols;
            index = saveIndex;
            continue;
        }
        case PP_DEFINE:
        {
            next(IDENTIFIER);
            QByteArray name = lexem();
            int start = index;
            until(PP_NEWLINE);
            Macro macro;
            macro.symbols.reserve(index - start - 1);
            for (int i = start; i < index - 1; ++i)
                macro.symbols += symbols.at(i);
            macros.insert(name, macro);
            continue;
        }
        case PP_UNDEF: {
            next(IDENTIFIER);
            QByteArray name = lexem();
            until(PP_NEWLINE);
            macros.remove(name);
            continue;
        }
        case PP_IDENTIFIER:
        {
//             if (macros.contains(symbol()))
//                 ;
        }
            // we _could_ easily substitute macros by the following
            // four lines, but we choose not to.
            /*
            if (macros.contains(sym.lexem())) {
                preprocessed += substitute(macros, symbols, i);
                continue;
            }
            */
            break;
        case PP_HASH:
            until(PP_NEWLINE);
            continue; // skip unknown preprocessor statement
        case PP_IFDEF:
        case PP_IFNDEF:
        case PP_IF:
            while (!evaluateCondition()) {
                if (!skipBranch())
                    break;
                if (test(PP_ELIF)) {
                } else {
                    until(PP_NEWLINE);
                    break;
                }
            }
            continue;
        case PP_ELIF:
        case PP_ELSE:
            skipUntilEndif();
            // fall through
        case PP_ENDIF:
            until(PP_NEWLINE);
            continue;
        case SIGNALS:
        case SLOTS: {
            Symbol sym = symbol();
            if (macros.contains("QT_NO_KEYWORDS"))
                sym.token = IDENTIFIER;
            else
                sym.token = (token == SIGNALS ? Q_SIGNALS_TOKEN : Q_SLOTS_TOKEN);
            preprocessed += sym;
        } continue;
        default:
            break;
        }
        preprocessed += symbol();
    }

    currentFilenames.pop();
}
Esempio n. 9
0
QByteArray MumeXmlParser::characters(QByteArray &ch)
{
    QByteArray toUser;

    if (ch.isEmpty()) {
        return toUser;
    }

    // replace > and < chars
    stripXmlEntities(ch);

    const auto &config = getConfig();
    m_stringBuffer = QString::fromLatin1(ch);

    if (m_readSnoopTag && m_stringBuffer.length() > 3 && m_stringBuffer.at(0) == '&'
        && m_stringBuffer.at(2) == ' ') {
        // Remove snoop prefix (i.e. "&J Exits: north.")
        m_stringBuffer = m_stringBuffer.mid(3);
    }

    switch (m_xmlMode) {
    case XmlMode::NONE: // non room info
        m_stringBuffer = normalizeStringCopy(m_stringBuffer.trimmed());
        if (m_stringBuffer.isEmpty()) { // standard end of description parsed
            if (m_readingRoomDesc) {
                m_readingRoomDesc = false; // we finished read desc mode
                m_descriptionReady = true;
                if (config.mumeNative.emulatedExits) {
                    emulateExits();
                }
            }
        } else {
            parseMudCommands(m_stringBuffer);
        }
        if (m_readSnoopTag) {
            if (m_descriptionReady) {
                m_promptFlags.reset(); // Don't trust god prompts
                queue.enqueue(m_move);
                emit showPath(queue, true);
                move();
                m_readSnoopTag = false;
            }
        }
        toUser.append(ch);
        break;

    case XmlMode::ROOM: // dynamic line
        m_dynamicRoomDesc += normalizeStringCopy(m_stringBuffer.simplified().append("\n"));
        toUser.append(ch);
        break;

    case XmlMode::NAME:
        if (m_descriptionReady) {
            move();
        }
        m_readingRoomDesc = true; // start of read desc mode
        m_roomName = normalizeStringCopy(m_stringBuffer);
        toUser.append(ch);
        break;

    case XmlMode::DESCRIPTION: // static line
        m_staticRoomDesc += normalizeStringCopy(m_stringBuffer.simplified().append("\n"));
        if (!m_gratuitous) {
            toUser.append(ch);
        }
        break;

    case XmlMode::EXITS:
        m_exits += m_stringBuffer;
        if (m_readingRoomDesc) {
            m_readingRoomDesc = false;
            m_descriptionReady = true;
        }
        break;

    case XmlMode::PROMPT:
        emit sendPromptLineEvent(normalizeStringCopy(m_stringBuffer).toLatin1());
        if (m_readingRoomDesc) {       // fixes compact mode
            m_readingRoomDesc = false; // we finished read desc mode
            m_descriptionReady = true;
            if (config.mumeNative.emulatedExits) {
                emulateExits();
            }
        }
        if (m_descriptionReady) {
            parsePrompt(normalizeStringCopy(m_stringBuffer));
            move();
        }

        toUser.append(ch);
        break;

    case XmlMode::TERRAIN:
    default:
        toUser.append(ch);
        break;
    }

    if (!getConfig().parser.removeXmlTags) {
        toUser.replace(ampersand, ampersandTemplate);
        toUser.replace(greaterThanChar, greaterThanTemplate);
        toUser.replace(lessThanChar, lessThanTemplate);
    }
    return toUser;
}
Esempio n. 10
0
void CrashReportDialog::sendReport()
{
    if (m_uploadReply)
        return;

    if (!m_allowReport->isChecked())
    {
        done(m_finalResult);
        return;
    }

    QString platform =
#if defined(Q_OS_WIN)
                       QLatin1String("windows");
#elif defined(Q_OS_MAC)
                       QLatin1String("mac");
#elif defined(Q_OS_LINUX)
                       QLatin1String("linux");
#else
                       QLatin1String("unknown");
#endif

    QNetworkAccessManager *nam = new QNetworkAccessManager(this);
#if QT_VERSION < QT_VERSION_CHECK(5, 0, 0)
    QUrl queryUrl(m_reportUrl);
#else
    QUrlQuery queryUrl(m_reportUrl);
    QUrl url;
#endif
    queryUrl.addQueryItem(QLatin1String("version"), qApp->applicationVersion());
    queryUrl.addQueryItem(QLatin1String("platform"), platform);
    if (!m_emailInput->text().isEmpty())
        queryUrl.addQueryItem(QLatin1String("email"), m_emailInput->text());

    if (!m_dumpFile.exists() || !m_dumpFile.open(QIODevice::ReadOnly))
    {
        queryUrl.addQueryItem(QLatin1String("dump"), QLatin1String("0"));
#if QT_VERSION < QT_VERSION_CHECK(5, 0, 0)
        url.setQuery(queryUrl);
#endif
        m_uploadReply = nam->get(QNetworkRequest(url));
    }
    else
    {
#if QT_VERSION < QT_VERSION_CHECK(5, 0, 0)
        url.setQuery(queryUrl);
#endif
        QNetworkRequest req(url);
        const char *boundary = "UPLOADDUMP";
        req.setHeader(QNetworkRequest::ContentTypeHeader, QByteArray("multipart/form-data; boundary=") + boundary);

        QByteArray data;
        data.append("--");
        data.append(boundary);
        data.append("\r\ncontent-disposition: form-data; name=\"dump\"; filename=\"temp.dmp\"\r\nContent-Transfer-Encoding: binary\r\nContent-Length: ");
        data.append(m_dumpFile.size());
        data.append("\r\nContent-type: application/x-octet-stream\r\n\r\n");
        data.append(m_dumpFile.readAll());
        data.append("\r\n--");
        data.append(boundary);
        data.append("--\r\n");
        m_dumpFile.close();

        m_uploadReply = nam->post(req, data);
    }

    connect(m_uploadReply, SIGNAL(finished()), SLOT(uploadFinished()));
    bool ok = connect(m_uploadReply, SIGNAL(uploadProgress(qint64,qint64)), SLOT(setUploadProgress(qint64)));
    Q_UNUSED(ok);
    Q_ASSERT(ok);
    m_uploadProgress->setMaximum((int)m_dumpFile.size());

    m_stackLayout->setCurrentIndex(1);

    setFixedHeight(QWIDGETSIZE_MAX);
    QPropertyAnimation *resizeAnimation = new QPropertyAnimation(this, "size");
    resizeAnimation->setEndValue(QSize(width(), minimumSizeHint().height()));
    resizeAnimation->setDuration(150);
    resizeAnimation->setEasingCurve(QEasingCurve::InQuad);
    resizeAnimation->start(QAbstractAnimation::DeleteWhenStopped);
}
Esempio n. 11
0
/*!
    \fn QString QTextList::itemText(const QTextBlock &block) const

    Returns the text of the list item that corresponds to the given \a block.
*/
QString QTextList::itemText(const QTextBlock &blockIt) const
{
    Q_D(const QTextList);
    int item = d->blocks.indexOf(blockIt) + 1;
    if (item <= 0)
        return QString();

    QTextBlock block = d->blocks.at(item-1);
    QTextBlockFormat blockFormat = block.blockFormat();

    QString result;

    const int style = format().style();
    QString numberPrefix;
    QString numberSuffix = QLatin1String(".");

    if (format().hasProperty(QTextFormat::ListNumberPrefix))
        numberPrefix = format().numberPrefix();
    if (format().hasProperty(QTextFormat::ListNumberSuffix))
        numberSuffix = format().numberSuffix();

    switch (style) {
        case QTextListFormat::ListDecimal:
            result = QString::number(item);
            break;
            // from the old richtext
        case QTextListFormat::ListLowerAlpha:
        case QTextListFormat::ListUpperAlpha:
            {
                const char baseChar = style == QTextListFormat::ListUpperAlpha ? 'A' : 'a';

                int c = item;
                while (c > 0) {
                    c--;
                    result.prepend(QChar(baseChar + (c % 26)));
                    c /= 26;
                }
            }
            break;
        case QTextListFormat::ListLowerRoman:
        case QTextListFormat::ListUpperRoman:
            {
                if (item < 5000) {
                    QByteArray romanNumeral;

                    // works for up to 4999 items
                    static const char romanSymbolsLower[] = "iiivixxxlxcccdcmmmm";
                    static const char romanSymbolsUpper[] = "IIIVIXXXLXCCCDCMMMM";
                    QByteArray romanSymbols; // wrap to have "mid"
                    if (style == QTextListFormat::ListLowerRoman)
                        romanSymbols = QByteArray::fromRawData(romanSymbolsLower, sizeof(romanSymbolsLower));
                    else
                        romanSymbols = QByteArray::fromRawData(romanSymbolsUpper, sizeof(romanSymbolsUpper));

                    int c[] = { 1, 4, 5, 9, 10, 40, 50, 90, 100, 400, 500, 900, 1000 };
                    int n = item;
                    for (int i = 12; i >= 0; n %= c[i], i--) {
                        int q = n / c[i];
                        if (q > 0) {
                            int startDigit = i + (i+3)/4;
                            int numDigits;
                            if (i % 4) {
                                // c[i] == 4|5|9|40|50|90|400|500|900
                                if ((i-2) % 4) {
                                    // c[i] == 4|9|40|90|400|900 => with subtraction (IV, IX, XL, XC, ...)
                                    numDigits = 2;
                                }
                                else {
                                    // c[i] == 5|50|500 (V, L, D)
                                    numDigits = 1;
                                }
                            }
                            else {
                                // c[i] == 1|10|100|1000 (I, II, III, X, XX, ...)
                                numDigits = q;
                            }

                            romanNumeral.append(romanSymbols.mid(startDigit, numDigits));
                        }
                    }
                    result = QString::fromLatin1(romanNumeral);
                }
                else {
                    result = QLatin1String("?");
                }

            }
            break;
        default:
            Q_ASSERT(false);
    }
    if (blockIt.textDirection() == Qt::RightToLeft)
        return numberSuffix + result + numberPrefix;
    else
        return numberPrefix + result + numberSuffix;
}
Esempio n. 12
0
bool KNMusicTagApev2::writeTag(const KNMusicAnalysisItem &analysisItem)
{
    //Write the data according to the detail info.
    const KNMusicDetailInfo &detailInfo=analysisItem.detailInfo;
    //Check the file is still exist or not.
    QFile musicFile(detailInfo.filePath);
    //If the file is not exist then return false.
    if(!musicFile.exists())
    {
        return false;
    }

    //Find the original tag data.
    //ID3v1 header flag.
    bool hasId3v1=false;
    //Generate a header structure.
    APEHeader header;
    //Generate the raw tag data list.
    QList<APETagItem> itemList;
    //Initial the tag start position.
    qint64 tagDataStart=-1, tagDataLength=-1;
    //Open the file first.
    if(musicFile.open(QIODevice::ReadOnly))
    {
        //Generate a data stream.
        QDataStream musicDataStream(&musicFile);
        if(musicFile.size() > 128)
        {
            //ID3v1 header cache.
            char id3v1Header[3];
            //Check whether there's ID3v1 tag in the music file.
            musicDataStream.skipRawData(musicFile.size()-128);
            //Read ID3v1 header.
            musicDataStream.readRawData(id3v1Header, 3);
            //Check the header, and we can know that whether there's ID3v1
            //header.
            hasId3v1=(id3v1Header[0]=='T' &&
                        id3v1Header[1]=='A' &&
                          id3v1Header[2]=='G');
        }
        //Check the beginning of the file.
        if(checkHeader(0,
                       musicDataStream,
                       header))
        {
            //Set the tag data start.
            tagDataStart=0;
            //Set the tag length to header length.
            tagDataLength=header.size;
            //Check whether is a footer in the tag.
            if(header.size > APEv2HeaderSize)
            {
                //Check the footer.
                APEHeader footer;
                //Tried to parse the footer.
                if(checkHeader(header.size,
                               musicDataStream,
                               footer))
                {
                    //Update the tag length.
                    tagDataLength+=APEv2HeaderSize;
                }
            }
            //Reset the device to start.
            musicDataStream.device()->reset();
            //Skip the file data.
            musicDataStream.skipRawData(APEv2HeaderSize);
        }
        //Check the end of the file.
        else if(checkHeader(musicFile.size()-APEv2HeaderSize,
                            musicDataStream,
                            header))
        {
            //Save the tag start data.
            int tagContentStart=musicFile.size()-header.size;
            //Check the footer.
            APEHeader footer;
            //Check whether there's a header in the tag.
            if(checkHeader(tagContentStart-APEv2HeaderSize,
                           musicDataStream,
                           footer))
            {
                //Save the tag data start position as the header start position.
                //This is APEv2 tag.
                tagDataStart=tagContentStart-APEv2HeaderSize;
                //The tag length will be a header size + tag size.
                tagDataLength=APEv2HeaderSize + header.size;
            }
            else
            {
                //This is APEv1 tag.
                tagDataStart=tagContentStart;
                //The tag length will be tag size.
                tagDataLength=header.size;
            }
            //Reset the device to start.
            musicDataStream.device()->reset();
            //Skip the file data.
            musicDataStream.skipRawData(tagContentStart);
        }
        //Check the position before ID3v1. Some file may have both ID3v1 and
        //APEv1/APEv2.
        else if(musicFile.size()>=(ID3v1nAPEv2 + APEv2HeaderSize) &&
                                                            //File size first.
                checkHeader(musicFile.size()-ID3v1nAPEv2,
                            musicDataStream,
                            header))
        {
            //Save the tag start position.
            int tagContentStart=musicFile.size()-ID3v1Size-header.size;
            //Check the footer.
            APEHeader footer;
            //Check whether there's a header in the tag.
            if(checkHeader(tagContentStart-APEv2HeaderSize,
                           musicDataStream,
                           footer))
            {
                //Save the tag data start position as the header start position.
                //This is APEv2 tag.
                tagDataStart=tagContentStart-APEv2HeaderSize;
                //The tag length will be a header size + tag size.
                tagDataLength=APEv2HeaderSize + header.size;
            }
            else
            {
                //This is APEv1 tag.
                tagDataStart=tagContentStart;
                //The tag length will be tag size.
                tagDataLength=header.size;
            }
            //Reset the device to start.
            musicDataStream.device()->reset();
            //Skip the file data.
            musicDataStream.skipRawData(tagContentStart);
        }
        //Parse the data if we find the header.
        if(tagDataStart!=-1)
        {
            //Read the tag from the file.
            char *rawTagData=new char[header.size];
            musicDataStream.readRawData(rawTagData, header.size);
            //Parse the raw tag data list.
            parseRawData(rawTagData, header, itemList);
            //Recover the memory.
            delete[] rawTagData;
        }
        //Close the music file.
        musicFile.close();
    }
    //Add all the text labels to detail frames if it's not empty.
    for(int i=0; i<MusicDataCount; i++)
    {
        //Check if the text is empty.
        if(detailInfo.textLists[i].toString().isEmpty())
        {
            continue;
        }
        //Get the frame key from hash group.
        QString key=m_indexKey.value(i, QString());
        //If the key is empty, means you cannot write this data to APEv2.
        if(key.isEmpty())
        {
            continue;
        }
        //Generate a data frame.
        APETagItem item;
        //Save the key.
        item.key=key;
        //According to the frame, generate the item.
        switch(i)
        {
        case DiscNumber:
            //If disc count isn't empty, then add disc count to disc number
            //data.
            item.value=detailInfo.textLists[DiscCount].toString().isEmpty()?
                        detailInfo.textLists[DiscNumber].toString().toUtf8():
                        (detailInfo.textLists[DiscNumber].toString()+"/"+
                         detailInfo.textLists[DiscCount].toString()).toUtf8();
        default:
            //Add the whole data to the item.
            item.value=detailInfo.textLists[i].toString().toUtf8();
        }
        //Remove the all the original item.
        //We have to check the key from the back to the first, and we won't get
        //mess to the index.
        for(int i=itemList.size()-1; i>-1; i--)
        {
            //If the key is the same as current key,
            if(itemList.at(i).key==key)
            {
                //Remove it.
                itemList.removeAt(i);
            }
        }
        //Add current key to item list.
        itemList.append(item);
    }
    //Now translate the frame structure data to the raw data.
    QByteArray contentData;
    //Prepare the cache size.
    char numberCache[4];
    //Simply transferred the APETagItem to content data.
    for(auto i=itemList.constBegin(); i!=itemList.constEnd(); ++i)
    {
        //Get the item size.
        quint32 size=(*i).value.size();
        //First transfer item size to raw data into cache.
        numberToData(size, numberCache);
        //Add item size to content data.
        contentData.append(numberCache, 4);
        //Transfer the flag to raw data into cache.
        numberToData((*i).flag, numberCache);
        //Add flag data to content data.
        contentData.append(numberCache, 4);
        //Add item key to content data.
        contentData.append((*i).key.toUtf8());
        //Add 0x00 for item key terminator.
        contentData.append('\0');
        //Add item value.
        contentData.append((*i).value);
    }

    //Update the header data.
    header.size=contentData.size()+32;
    header.itemCount=itemList.size();

    //We will write the APEv2 data to the end part of the file. Just before the
    //ID3v1.
    //Check the header data.
    //Open the music file again.
    if(!musicFile.open(QIODevice::ReadOnly))
    {
        return false;
    }
    //Generate a temporary file, write the new data to the temporary file.
    QTemporaryFile updatedTagFile;
    //Open the temporary file, if we cannot open the temporary file it will be
    //failed to write the tag.
    if(!updatedTagFile.open())
    {
        //Close the opened music file.
        musicFile.close();
        return false;
    }
    //Initial the file size.
    qint64 dataSurplusSize=musicFile.size();
    /*
     * Algorithm:
     * We treat the file as these two kinds of format:
     *          APEv2 | xxxx (Content) (| ID3v1)
     * or
     *          xxxx (Content) | APEv2 (| ID3v1)
     * So we have to process the ID3v1 at first. Then the file should be like
     * the following:
     *                 APEv2 | xxxx (Content)
     * or
     *                 xxxx (Content) | APEv2
     * And now, we only have to check if the APEv2 is at the beginning or the
     * end of the content.
     */
    //If we have ID3v1, then remove the tag from the copying bytes.
    if(hasId3v1)
    {
        //Reduce the ID3v1 tag size.
        dataSurplusSize-=128;
    }
    //Check whether we have original APEv2 header.
    if(tagDataStart!=-1)
    {
        //Reduce the tag size from the file size.
        dataSurplusSize-=tagDataLength;
        //Check whether the header is at the start of the music file.
        if(tagDataStart==0)
        {
            //It's at the beginning of the file.
            //Skip the Original APEv2 tag at the beginning of the file.
            musicFile.seek(tagDataLength);
        }
    }
    //Generate the music data cache.
    char *turboCache=new char[DataCacheSize];
    int bytesRead;
    //Now copy all the content from the original file to temporary file.
    while(dataSurplusSize>0)
    {
        //Read the original data.
        bytesRead=musicFile.read(turboCache,
                                 (DataCacheSize < dataSurplusSize ?
                                      DataCacheSize : dataSurplusSize));
        //Write the cache to temporary file.
        updatedTagFile.write(turboCache, bytesRead);
        //Reduce the surplus size.
        dataSurplusSize-=bytesRead;
    }
    //According to the hydrogenaud.io, we have to put the APEv2 at the end of
    //the file.
    //Write new APEv2 tag to the file.
    /*
     * From http://wiki.hydrogenaud.io/index.php?title=Ape_Tags_Flags:
     * Bit 29:
     * 0: This is the footer, not the header
     * 1: This is the header, not the footer
     */
    //First set the item flag to header in header data bytearray.
    updatedTagFile.write(generateHeaderData(header, true));
    //Then, write the content data.
    updatedTagFile.write(contentData);
    //Last, write the footer data.
    updatedTagFile.write(generateHeaderData(header, false));
    //If there's ID3v1 tag, then copy the ID3v1 data from the original file.
    if(hasId3v1)
    {
        //Seek to the ID3v1 tag start.
        musicFile.seek(musicFile.size()-128);
        //Read 128 bytes ID3v1 tag.
        musicFile.read(turboCache, 128);
        //Write the cache to temporary file.
        updatedTagFile.write(turboCache, 128);
    }
    //Close the music file.
    musicFile.close();
    //Reset the temporary file.
    updatedTagFile.reset();
    //Reopen the music file as write only mode, write all the udpated tag file
    //data to the music file.
    if(!musicFile.open(QIODevice::WriteOnly))
    {
        return false;
    }
    //Copy data from temporary file to music file.
    bytesRead=updatedTagFile.read(turboCache, DataCacheSize);
    while(bytesRead>0)
    {
        //Write the cache to music file.
        musicFile.write(turboCache, bytesRead);
        //Read new data from the original file to cache.
        bytesRead=updatedTagFile.read(turboCache, DataCacheSize);
    }
    //Close the music file and temporary file.
    musicFile.close();
    updatedTagFile.close();
    //Clear up the turbo cache.
    delete[] turboCache;
    //The tag rewrite is finished.
    return true;
}
void QDBusMetaObjectGenerator::parseMethods()
{
    //
    // TODO:
    //  Add cloned methods when the remote object has return types
    //

    QDBusIntrospection::Methods::ConstIterator method_it = data->methods.constBegin();
    QDBusIntrospection::Methods::ConstIterator method_end = data->methods.constEnd();
    for ( ; method_it != method_end; ++method_it) {
        const QDBusIntrospection::Method &m = *method_it;
        Method mm;

        mm.name = m.name.toLatin1();
        QByteArray prototype = mm.name;
        prototype += '(';

        bool ok = true;

        // build the input argument list
        for (int i = 0; i < m.inputArgs.count(); ++i) {
            const QDBusIntrospection::Argument &arg = m.inputArgs.at(i);

            Type type = findType(arg.type.toLatin1(), m.annotations, "In", i);
            if (type.id == QVariant::Invalid) {
                ok = false;
                break;
            }

            mm.inputSignature += arg.type.toLatin1();
            mm.inputTypes.append(type.id);

            mm.parameters.append(arg.name.toLatin1());
            mm.parameters.append(',');
            
            prototype.append(type.name);
            prototype.append(',');
        }
        if (!ok) continue;

        // build the output argument list:
        for (int i = 0; i < m.outputArgs.count(); ++i) {
            const QDBusIntrospection::Argument &arg = m.outputArgs.at(i);

            Type type = findType(arg.type.toLatin1(), m.annotations, "Out", i);
            if (type.id == QVariant::Invalid) {
                ok = false;
                break;
            }

            mm.outputSignature += arg.type.toLatin1();
            mm.outputTypes.append(type.id);

            if (i == 0) {
                // return value
                mm.typeName = type.name;
            } else {
                // non-const ref parameter
                mm.parameters.append(arg.name.toLatin1());
                mm.parameters.append(',');

                prototype.append(type.name);
                prototype.append("&,");
            }
        }
        if (!ok) continue;

        // convert the last commas:
        if (!mm.parameters.isEmpty()) {
            mm.parameters.truncate(mm.parameters.length() - 1);
            prototype[prototype.length() - 1] = ')';
        } else {
            prototype.append(')');
        }

        // check the async tag
        if (m.annotations.value(QLatin1String(ANNOTATION_NO_WAIT)) == QLatin1String("true"))
            mm.tag = "Q_NOREPLY";

        // meta method flags
        mm.flags = AccessPublic | MethodSlot | MethodScriptable;

        // add
        methods.insert(QMetaObject::normalizedSignature(prototype), mm);
    }
}
Esempio n. 14
0
const QByteArray
AbstractDictionary::wordData(quint32 indexItemOffset, qint32 indexItemSize)
{
    // Check first whether or not the data is already available in the cache
    foreach (const WordEntry& cacheItem, d->cacheItemList)
    {
        if (!cacheItem.data().isEmpty() && cacheItem.dataOffset() == indexItemOffset)
            return cacheItem.data();
    }

    QByteArray resultData;
    QByteArray originalData;

    if (!d->sameTypeSequence.isEmpty())
    {
        if (d->dictionaryFile->isOpen())
        {
            d->dictionaryFile->seek(indexItemOffset);
            originalData = d->dictionaryFile->read(indexItemSize);
        }
        else
        {
            originalData = d->compressedDictionaryFile->read(indexItemOffset, indexItemSize);
        }

        int sameTypeSequenceLength = d->sameTypeSequence.length();

        int sectionSize = 0;
        int sectionPosition = 0;

        // Copy the head items.
        foreach (const QChar& ch, d->sameTypeSequence.left(sameTypeSequenceLength - 1))
        {
            if (ch.isUpper())
            {
                sectionSize = *reinterpret_cast<quint32 *>(originalData.mid(sectionPosition).data());
                sectionSize += sizeof(quint32);
            }
            else
            {
                sectionSize = qstrlen(originalData.mid(sectionPosition)) + 1;
            }

            resultData.append(ch);
            resultData.append(originalData.mid(sectionPosition, sectionSize));
            sectionPosition += sectionSize;
        }

        // Calculate the last item's size.
        sectionSize = indexItemSize - sectionPosition;
        resultData.append(d->sameTypeSequence.at(sameTypeSequenceLength - 1));
        if (d->sameTypeSequence.at(sameTypeSequenceLength - 1).isUpper())
        {
            resultData.append(reinterpret_cast<char*>(&sectionSize), sizeof(quint32));
            resultData.append(originalData.mid(sectionPosition, sectionSize));
        }
        else
        {
            resultData.append(originalData.mid(sectionPosition, sectionSize));
            sectionPosition += sectionSize;
            resultData.append('\0');
        }
    }
    else
    {
        if (d->dictionaryFile->isOpen())
Esempio n. 15
0
QString chromaprinter::calcFingerPrint(SoundSourceProxy& soundSource){
    soundSource.open();
    m_SampleRate = soundSource.getSampleRate();
    unsigned int length = soundSource.length();
    if (m_SampleRate == 0 ){
        qDebug() << "Skipping invalid file:" << soundSource.getFilename();
        return QString();
    }

    // this is worth 2min of audio, multiply by 2 because we have 2 channels
    // AcoustID only stores a fingerprint for the first two minutes of a song
    // on their server so we need only a fingerprint of the first two minutes
    // --kain88 July 2012
    m_NumSamples = 120*2*m_SampleRate;
    // check that the song is actually longer then the amount of audio we use
    if (m_NumSamples > length) {
        m_NumSamples = length;
    }

    SAMPLE *pData = new SAMPLE[m_NumSamples];
    QTime timerReadingFile;
    timerReadingFile.start();
    unsigned int read = soundSource.read(m_NumSamples, pData);

    if (read!=m_NumSamples) {
        qDebug() << "oh that's embarrasing I couldn't read the track";
        return QString();
    }
    qDebug("reading file took: %d ms" , timerReadingFile.elapsed());

    ChromaprintContext* ctx = chromaprint_new(CHROMAPRINT_ALGORITHM_DEFAULT);
    // we have 2 channels in mixxx always
    chromaprint_start(ctx, m_SampleRate, 2);

    QTime timerGeneratingFingerPrint;
    timerGeneratingFingerPrint.start();
    int success = chromaprint_feed(ctx, pData, m_NumSamples);
    if (!success) {
        qDebug() << "could not generate fingerprint";
        delete [] pData;
        return QString();
    }
    chromaprint_finish(ctx);

    void* fprint = NULL;
    int size = 0;
    int ret = chromaprint_get_raw_fingerprint(ctx, &fprint, &size);
    QByteArray fingerprint;
    if (ret == 1) {
        void* encoded = NULL;
        int encoded_size = 0;
        chromaprint_encode_fingerprint(fprint, size,
                                       CHROMAPRINT_ALGORITHM_DEFAULT,
                                       &encoded,
                                       &encoded_size, 1);

        fingerprint.append(reinterpret_cast<char*>(encoded), encoded_size);

        chromaprint_dealloc(fprint);
        chromaprint_dealloc(encoded);
    }
    chromaprint_free(ctx);
    delete [] pData;

    qDebug("generating fingerprint took: %d ms" , timerGeneratingFingerPrint.elapsed());

    return fingerprint;
}
Esempio n. 16
0
//------------------------------------------------------------------------------
// Name: getString
//------------------------------------------------------------------------------
QString QJsonParser::getString() {

	if(peek() != Quote) {
		throwError(QJsonParseError::IllegalUTF8String);
	}
	++p_;

	QByteArray s;

	while(p_ != end_ && *p_ != Quote && *p_ != '\n') {
		if(*p_ == '\\') {
			++p_;
			if(p_ != end_) {
				switch(*p_) {
				case '"':  s.append('"'); break;
				case '\\': s.append('\\'); break;
				case '/':  s.append('/'); break;
				case 'b':  s.append('\b'); break;
				case 'f':  s.append('\f'); break;
				case 'n':  s.append('\n'); break;
				case 'r':  s.append('\r'); break;
				case 't':  s.append('\t'); break;
				case 'u':
					{

						QString hexChar;

						// convert \uXXXX escape sequences to UTF-8
						char hex[4];
						if(p_ == end_) { throwError(QJsonParseError::IllegalEscapeSequence); } hex[0] = *++p_;
						if(p_ == end_) { throwError(QJsonParseError::IllegalEscapeSequence); } hex[1] = *++p_;
						if(p_ == end_) { throwError(QJsonParseError::IllegalEscapeSequence); } hex[2] = *++p_;
						if(p_ == end_) { throwError(QJsonParseError::IllegalEscapeSequence); } hex[3] = *++p_;

						if(!std::isxdigit(hex[0])) throwError(QJsonParseError::IllegalUTF8String);
						if(!std::isxdigit(hex[1])) throwError(QJsonParseError::IllegalUTF8String);
						if(!std::isxdigit(hex[2])) throwError(QJsonParseError::IllegalUTF8String);
						if(!std::isxdigit(hex[3])) throwError(QJsonParseError::IllegalUTF8String);

						quint16 w1 = 0;
						quint16 w2 = 0;

						w1 |= (to_hex(hex[0]) << 12);
						w1 |= (to_hex(hex[1]) << 8);
						w1 |= (to_hex(hex[2]) << 4);
						w1 |= (to_hex(hex[3]));

						hexChar.append(QChar(w1));

						if((w1 & 0xfc00) == 0xdc00) {
							throwError(QJsonParseError::IllegalUTF8String);
						}

						if((w1 & 0xfc00) == 0xd800) {
							// part of a surrogate pair
							if(p_ == end_ || *++p_ != '\\') { throwError(QJsonParseError::IllegalEscapeSequence); }
							if(p_ == end_ || *++p_ != 'u')  { throwError(QJsonParseError::IllegalEscapeSequence); }

							// convert \uXXXX escape sequences to UTF-8
							if(p_ == end_) { throwError(QJsonParseError::IllegalEscapeSequence); } hex[0] = *++p_;
							if(p_ == end_) { throwError(QJsonParseError::IllegalEscapeSequence); } hex[1] = *++p_;
							if(p_ == end_) { throwError(QJsonParseError::IllegalEscapeSequence); } hex[2] = *++p_;
							if(p_ == end_) { throwError(QJsonParseError::IllegalEscapeSequence); } hex[3] = *++p_;

							if(!std::isxdigit(hex[0])) throwError(QJsonParseError::IllegalUTF8String);
							if(!std::isxdigit(hex[1])) throwError(QJsonParseError::IllegalUTF8String);
							if(!std::isxdigit(hex[2])) throwError(QJsonParseError::IllegalUTF8String);
							if(!std::isxdigit(hex[3])) throwError(QJsonParseError::IllegalUTF8String);

							w2 |= (to_hex(hex[0]) << 12);
							w2 |= (to_hex(hex[1]) << 8);
							w2 |= (to_hex(hex[2]) << 4);
							w2 |= (to_hex(hex[3]));

							hexChar.append(QChar(w2));
						}

						s.append(hexChar.toUtf8());
					}
					break;

				default:
					s.append('\\');
					break;
				}
			}
		} else {
			s.append(*p_);
		}
		++p_;
	}

	if(*p_ != Quote || p_ == end_) {
		throwError(QJsonParseError::UnterminatedString);
	}

	++p_;

	return QString::fromUtf8(s, s.size());
}
Esempio n. 17
0
static Symbols tokenize(const QByteArray &input, int lineNum = 1, TokenizeMode mode = TokenizeCpp)
{
    Symbols symbols;
    const char *begin = input;
    const char *data = begin;
    while (*data) {
        if (mode == TokenizeCpp) {
            int column = 0;

            const char *lexem = data;
            int state = 0;
            Token token = NOTOKEN;
            for (;;) {
                if (static_cast<signed char>(*data) < 0) {
                    ++data;
                    continue;
                }
                int nextindex = keywords[state].next;
                int next = 0;
                if (*data == keywords[state].defchar)
                    next = keywords[state].defnext;
                else if (!state || nextindex)
                    next = keyword_trans[nextindex][(int)*data];
                if (!next)
                    break;
                state = next;
                token = keywords[state].token;
                ++data;
            }

            // suboptimal, is_ident_char  should use a table
            if (keywords[state].ident && is_ident_char(*data))
                token = keywords[state].ident;

            if (token == NOTOKEN) {
                // an error really
                ++data;
                continue;
            }

            ++column;

            if (token > SPECIAL_TREATMENT_MARK) {
                switch (token) {
                case QUOTE:
                    data = skipQuote(data);
                    token = STRING_LITERAL;
                    // concatenate multi-line strings for easier
                    // STRING_LITERAAL handling in moc
                    if (!Preprocessor::preprocessOnly
                        && !symbols.isEmpty()
                        && symbols.last().token == STRING_LITERAL) {

                        QByteArray newString = symbols.last().unquotedLexem();
                        newString += input.mid(lexem - begin + 1, data - lexem - 2);
                        newString.prepend('\"');
                        newString.append('\"');
                        symbols.last() = Symbol(symbols.last().lineNum,
                                                STRING_LITERAL,
                                                newString);
                        continue;
                    }
                    break;
                case SINGLEQUOTE:
                    while (*data && (*data != '\''
                                     || (*(data-1)=='\\'
                                         && *(data-2)!='\\')))
                        ++data;
                    if (*data)
                        ++data;
                    token = CHARACTER_LITERAL;
                    break;
                case LANGLE_SCOPE:
                    // split <:: into two tokens, < and ::
                    token = LANGLE;
                    data -= 2;
                    break;
                case DIGIT:
                    while (is_digit_char(*data))
                        ++data;
                    if (!*data || *data != '.') {
                        token = INTEGER_LITERAL;
                        if (data - lexem == 1 &&
                            (*data == 'x' || *data == 'X')
                            && *lexem == '0') {
                            ++data;
                            while (is_hex_char(*data))
                                ++data;
                        }
                        break;
                    }
                    token = FLOATING_LITERAL;
                    ++data;
                    // fall through
                case FLOATING_LITERAL:
                    while (is_digit_char(*data))
                        ++data;
                    if (*data == '+' || *data == '-')
                        ++data;
                    if (*data == 'e' || *data == 'E') {
                        ++data;
                        while (is_digit_char(*data))
                            ++data;
                    }
                    if (*data == 'f' || *data == 'F'
                        || *data == 'l' || *data == 'L')
                        ++data;
                    break;
                case HASH:
                    if (column == 1) {
                        mode = PreparePreprocessorStatement;
                        while (*data && (*data == ' ' || *data == '\t'))
                            ++data;
                        if (is_ident_char(*data))
                            mode = TokenizePreprocessorStatement;
                        continue;
                    }
                    break;
                case NEWLINE:
                    ++lineNum;
                    continue;
                case BACKSLASH:
                {
                    const char *rewind = data;
                    while (*data && (*data == ' ' || *data == '\t'))
                        ++data;
                    if (*data && *data == '\n') {
                        ++data;
                        continue;
                    }
                    data = rewind;
                } break;
                case CHARACTER:
                    while (is_ident_char(*data))
                        ++data;
                    token = IDENTIFIER;
                    break;
                case C_COMMENT:
                    if (*data) {
                        if (*data == '\n')
                            ++lineNum;
                        ++data;
                        if (*data) {
                            if (*data == '\n')
                                ++lineNum;
                            ++data;
                        }
                    }
                    while (*data && (*(data-1) != '/' || *(data-2) != '*')) {
                        if (*data == '\n')
                            ++lineNum;
                        ++data;
                    }
                    token = WHITESPACE; // one comment, one whitespace
                    // fall through;
                case WHITESPACE:
                    if (column == 1)
                        column = 0;
                    while (*data && (*data == ' ' || *data == '\t'))
                        ++data;
                    if (Preprocessor::preprocessOnly) // tokenize whitespace
                        break;
                    continue;
                case CPP_COMMENT:
                    while (*data && *data != '\n')
                        ++data;
                    continue; // ignore safely, the newline is a separator
                default:
                    continue; //ignore
                }
            }
#ifdef USE_LEXEM_STORE
            if (!Preprocessor::preprocessOnly
                && token != IDENTIFIER
                && token != STRING_LITERAL
                && token != FLOATING_LITERAL
                && token != INTEGER_LITERAL)
                symbols += Symbol(lineNum, token);
            else
#endif
                symbols += Symbol(lineNum, token, input, lexem-begin, data-lexem);

        } else { //   Preprocessor

            const char *lexem = data;
            int state = 0;
            Token token = NOTOKEN;
            if (mode == TokenizePreprocessorStatement) {
                state = pp_keyword_trans[0][(int)'#'];
                mode = TokenizePreprocessor;
            }
            for (;;) {
                if (static_cast<signed char>(*data) < 0) {
                    ++data;
                    continue;
                }

                int nextindex = pp_keywords[state].next;
                int next = 0;
                if (*data == pp_keywords[state].defchar)
                    next = pp_keywords[state].defnext;
                else if (!state || nextindex)
                    next = pp_keyword_trans[nextindex][(int)*data];
                if (!next)
                    break;
                state = next;
                token = pp_keywords[state].token;
                ++data;
            }
            // suboptimal, is_ident_char  should use a table
            if (pp_keywords[state].ident && is_ident_char(*data))
                token = pp_keywords[state].ident;

            switch (token) {
            case NOTOKEN:
                ++data;
                break;
            case PP_IFDEF:
                symbols += Symbol(lineNum, PP_IF);
                symbols += Symbol(lineNum, PP_DEFINED);
                continue;
            case PP_IFNDEF:
                symbols += Symbol(lineNum, PP_IF);
                symbols += Symbol(lineNum, PP_NOT);
                symbols += Symbol(lineNum, PP_DEFINED);
                continue;
            case PP_INCLUDE:
                mode = TokenizeInclude;
                break;
            case PP_QUOTE:
                data = skipQuote(data);
                token = PP_STRING_LITERAL;
                break;
            case PP_SINGLEQUOTE:
                while (*data && (*data != '\''
                                 || (*(data-1)=='\\'
                                     && *(data-2)!='\\')))
                    ++data;
                if (*data)
                    ++data;
                token = PP_CHARACTER_LITERAL;
                break;
            case PP_DIGIT:
                while (is_digit_char(*data))
                    ++data;
                if (!*data || *data != '.') {
                    token = PP_INTEGER_LITERAL;
                    if (data - lexem == 1 &&
                        (*data == 'x' || *data == 'X')
                        && *lexem == '0') {
                        ++data;
                        while (is_hex_char(*data))
                            ++data;
                    }
                    break;
                }
                token = PP_FLOATING_LITERAL;
                ++data;
                // fall through
            case PP_FLOATING_LITERAL:
                while (is_digit_char(*data))
                    ++data;
                if (*data == '+' || *data == '-')
                    ++data;
                if (*data == 'e' || *data == 'E') {
                    ++data;
                    while (is_digit_char(*data))
                        ++data;
                }
                if (*data == 'f' || *data == 'F'
                    || *data == 'l' || *data == 'L')
                    ++data;
                break;
            case PP_CHARACTER:
                if (mode == PreparePreprocessorStatement) {
                    // rewind entire token to begin
                    data = lexem;
                    mode = TokenizePreprocessorStatement;
                    continue;
                }
                while (is_ident_char(*data))
                    ++data;
                token = PP_IDENTIFIER;
                break;
            case PP_C_COMMENT:
                if (*data) {
                    if (*data == '\n')
                        ++lineNum;
                    ++data;
                    if (*data) {
                        if (*data == '\n')
                            ++lineNum;
                        ++data;
                    }
                }
                while (*data && (*(data-1) != '/' || *(data-2) != '*')) {
                    if (*data == '\n')
                        ++lineNum;
                    ++data;
                }
                token = PP_WHITESPACE; // one comment, one whitespace
                // fall through;
            case PP_WHITESPACE:
                while (*data && (*data == ' ' || *data == '\t'))
                    ++data;
                continue; // the preprocessor needs no whitespace
            case PP_CPP_COMMENT:
                while (*data && *data != '\n')
                    ++data;
                continue; // ignore safely, the newline is a separator
            case PP_NEWLINE:
                ++lineNum;
                mode = TokenizeCpp;
                break;
            case PP_BACKSLASH:
            {
                const char *rewind = data;
                while (*data && (*data == ' ' || *data == '\t'))
                    ++data;
                if (*data && *data == '\n') {
                    ++data;
                    continue;
                }
                data = rewind;
            } break;
            case PP_LANGLE:
                if (mode != TokenizeInclude)
                    break;
                token = PP_STRING_LITERAL;
                while (*data && *data != '\n' && *(data-1) != '>')
                    ++data;
                break;
            default:
                break;
            }
            if (mode == PreparePreprocessorStatement)
                continue;
#ifdef USE_LEXEM_STORE
            if (token != PP_IDENTIFIER
                && token != PP_STRING_LITERAL
                && token != PP_FLOATING_LITERAL
                && token != PP_INTEGER_LITERAL)
                symbols += Symbol(lineNum, token);
            else
#endif
                symbols += Symbol(lineNum, token, input, lexem-begin, data-lexem);
        }
    }
    symbols += Symbol(); // eof symbol
    return symbols;
}
Esempio n. 18
0
void OctreeTests::propertyFlagsTests() {
    bool verbose = true;
    
    qDebug() << "FIXME: this test is broken and needs to be fixed.";
    qDebug() << "We're disabling this so that ALL_BUILD works";
    return;

    if (verbose) {
        qDebug() << "******************************************************************************************";
    }
    
    qDebug() << "OctreeTests::propertyFlagsTests()";

    {
        if (verbose) {
            qDebug() << "Test 1: EntityProperties: using setHasProperty()";
        }

        EntityPropertyFlags props;
        props.setHasProperty(PROP_VISIBLE);
        props.setHasProperty(PROP_POSITION);
        props.setHasProperty(PROP_RADIUS);
        props.setHasProperty(PROP_MODEL_URL);
        props.setHasProperty(PROP_COMPOUND_SHAPE_URL);
        props.setHasProperty(PROP_ROTATION);
    
        QByteArray encoded = props.encode();
        QCOMPARE(encoded, makeQByteArray({ (char) 13 }));

    }

    {    
        if (verbose) {
            qDebug() << "Test 2: ExamplePropertyFlags: using setHasProperty()";
        }

        EntityPropertyFlags props2;
        props2.setHasProperty(PROP_VISIBLE);
        props2.setHasProperty(PROP_ANIMATION_URL);
        props2.setHasProperty(PROP_ANIMATION_FPS);
        props2.setHasProperty(PROP_ANIMATION_FRAME_INDEX);
        props2.setHasProperty(PROP_ANIMATION_PLAYING);
    
        QByteArray encoded = props2.encode();
        QCOMPARE(encoded, makeQByteArray({ (char) 196, 15, 2 }));

        if (verbose) {
            qDebug() << "Test 2b: remove flag with setHasProperty() PROP_PAUSE_SIMULATION";
        }

        encoded = props2.encode();
        QCOMPARE(encoded, makeQByteArray({ (char) 136, 30 }));
    }

    {    
        if (verbose) {
            qDebug() << "Test 3: ExamplePropertyFlags: using | operator";
        }
        
        ExamplePropertyFlags props;

        props = ExamplePropertyFlags(EXAMPLE_PROP_VISIBLE) 
                    | ExamplePropertyFlags(EXAMPLE_PROP_ANIMATION_URL)
                    | ExamplePropertyFlags(EXAMPLE_PROP_ANIMATION_FPS)
                    | ExamplePropertyFlags(EXAMPLE_PROP_ANIMATION_FRAME_INDEX)
                    | ExamplePropertyFlags(EXAMPLE_PROP_ANIMATION_PLAYING) 
                    | ExamplePropertyFlags(EXAMPLE_PROP_PAUSE_SIMULATION);
    
        QByteArray encoded = props.encode();
        QCOMPARE(encoded, makeQByteArray({ (char) 196, 15, 2 }));


        if (verbose) {
            qDebug() << "Test 3b: remove flag with -= EXAMPLE_PROP_PAUSE_SIMULATION";
        }
        
        props -= EXAMPLE_PROP_PAUSE_SIMULATION;
    
        encoded = props.encode();
        QCOMPARE(encoded, makeQByteArray({ (char) 136, 30 }));
    }

    {    
        if (verbose) {
            qDebug() << "Test 3c: ExamplePropertyFlags: using |= operator";
        }

        ExamplePropertyFlags props;

        props |= EXAMPLE_PROP_VISIBLE;
        props |= EXAMPLE_PROP_ANIMATION_URL;
        props |= EXAMPLE_PROP_ANIMATION_FPS;
        props |= EXAMPLE_PROP_ANIMATION_FRAME_INDEX;
        props |= EXAMPLE_PROP_ANIMATION_PLAYING;
        props |= EXAMPLE_PROP_PAUSE_SIMULATION;

        QByteArray encoded = props.encode();
        QCOMPARE(encoded, makeQByteArray({ (char) 196, 15, 2 }));
    }

    {    
        if (verbose) {
            qDebug() << "Test 4: ExamplePropertyFlags: using + operator";
        }

        ExamplePropertyFlags props;

        props = ExamplePropertyFlags(EXAMPLE_PROP_VISIBLE) 
                    + ExamplePropertyFlags(EXAMPLE_PROP_ANIMATION_URL)
                    + ExamplePropertyFlags(EXAMPLE_PROP_ANIMATION_FPS)
                    + ExamplePropertyFlags(EXAMPLE_PROP_ANIMATION_FRAME_INDEX)
                    + ExamplePropertyFlags(EXAMPLE_PROP_ANIMATION_PLAYING) 
                    + ExamplePropertyFlags(EXAMPLE_PROP_PAUSE_SIMULATION);
    
        QByteArray encoded = props.encode();
        QCOMPARE(encoded, makeQByteArray({ (char) 196, 15, 2 }));
    }

    {    
        if (verbose) {
            qDebug() << "Test 5: ExamplePropertyFlags: using += operator";
        }
        ExamplePropertyFlags props;

        props += EXAMPLE_PROP_VISIBLE;
        props += EXAMPLE_PROP_ANIMATION_URL;
        props += EXAMPLE_PROP_ANIMATION_FPS;
        props += EXAMPLE_PROP_ANIMATION_FRAME_INDEX;
        props += EXAMPLE_PROP_ANIMATION_PLAYING;
        props += EXAMPLE_PROP_PAUSE_SIMULATION;
    
        QByteArray encoded = props.encode();
        QCOMPARE(encoded, makeQByteArray({ (char) 196, 15, 2 }));
    }

    {    
        if (verbose) {
            qDebug() << "Test 6: ExamplePropertyFlags: using = ... << operator";
        }
        
        ExamplePropertyFlags props;

        props = ExamplePropertyFlags(EXAMPLE_PROP_VISIBLE) 
                    << ExamplePropertyFlags(EXAMPLE_PROP_ANIMATION_URL)
                    << ExamplePropertyFlags(EXAMPLE_PROP_ANIMATION_FPS)
                    << ExamplePropertyFlags(EXAMPLE_PROP_ANIMATION_FRAME_INDEX)
                    << ExamplePropertyFlags(EXAMPLE_PROP_ANIMATION_PLAYING) 
                    << ExamplePropertyFlags(EXAMPLE_PROP_PAUSE_SIMULATION);
    
        QByteArray encoded = props.encode();
        QCOMPARE(encoded, makeQByteArray({ (char) 196, 15, 2 }));
    }

    {
        if (verbose) {
            qDebug() << "Test 7: ExamplePropertyFlags: using <<= operator";
        }
        
        ExamplePropertyFlags props;

        props <<= EXAMPLE_PROP_VISIBLE;
        props <<= EXAMPLE_PROP_ANIMATION_URL;
        props <<= EXAMPLE_PROP_ANIMATION_FPS;
        props <<= EXAMPLE_PROP_ANIMATION_FRAME_INDEX;
        props <<= EXAMPLE_PROP_ANIMATION_PLAYING;
        props <<= EXAMPLE_PROP_PAUSE_SIMULATION;
    
        QByteArray encoded = props.encode();
        QCOMPARE(encoded, makeQByteArray({ (char) 196, 15, 2 }));
    }

    {
        if (verbose) {
            qDebug() << "Test 8: ExamplePropertyFlags: using << enum operator";
        }
        
        ExamplePropertyFlags props;

        props << EXAMPLE_PROP_VISIBLE;
        props << EXAMPLE_PROP_ANIMATION_URL;
        props << EXAMPLE_PROP_ANIMATION_FPS;
        props << EXAMPLE_PROP_ANIMATION_FRAME_INDEX;
        props << EXAMPLE_PROP_ANIMATION_PLAYING;
        props << EXAMPLE_PROP_PAUSE_SIMULATION;

        QByteArray encoded = props.encode();
        QCOMPARE(encoded, makeQByteArray({ (char) 196, 15, 2 }));
    }

    {
        if (verbose) {
            qDebug() << "Test 9: ExamplePropertyFlags: using << flags operator ";
        }

        ExamplePropertyFlags props;
        ExamplePropertyFlags props2;

        props << EXAMPLE_PROP_VISIBLE;
        props << EXAMPLE_PROP_ANIMATION_URL;
        props << EXAMPLE_PROP_ANIMATION_FPS;

        props2 << EXAMPLE_PROP_ANIMATION_FRAME_INDEX;
        props2 << EXAMPLE_PROP_ANIMATION_PLAYING;
        props2 << EXAMPLE_PROP_PAUSE_SIMULATION;

        props << props2;

        QByteArray encoded = props.encode();
        QCOMPARE(encoded, makeQByteArray({ (char) 196, 15, 2 }));
    }
  
    {
        if (verbose) {
            qDebug() << "Test 10: ExamplePropertyFlags comparison";
        }
        ExamplePropertyFlags propsA;

        if (verbose) {
            qDebug() << "!propsA:" << (!propsA) << "{ expect true }";
        }
        QCOMPARE(!propsA, true);

        propsA << EXAMPLE_PROP_VISIBLE;
        propsA << EXAMPLE_PROP_ANIMATION_URL;
        propsA << EXAMPLE_PROP_ANIMATION_FPS;
        propsA << EXAMPLE_PROP_ANIMATION_FRAME_INDEX;
        propsA << EXAMPLE_PROP_ANIMATION_PLAYING;
        propsA << EXAMPLE_PROP_PAUSE_SIMULATION;

        QCOMPARE(!propsA, false);

        ExamplePropertyFlags propsB;
        propsB << EXAMPLE_PROP_VISIBLE;
        propsB << EXAMPLE_PROP_ANIMATION_URL;
        propsB << EXAMPLE_PROP_ANIMATION_FPS;
        propsB << EXAMPLE_PROP_ANIMATION_FRAME_INDEX;
        propsB << EXAMPLE_PROP_ANIMATION_PLAYING;
        propsB << EXAMPLE_PROP_PAUSE_SIMULATION;

        if (verbose) {
            qDebug() << "propsA == propsB:" << (propsA == propsB) << "{ expect true }";
            qDebug() << "propsA != propsB:" << (propsA != propsB) << "{ expect false }";
        }
        QCOMPARE(propsA == propsB, true);
        QCOMPARE(propsA != propsB, false);
        
        if (verbose) {
            qDebug() << "AFTER propsB -= EXAMPLE_PROP_PAUSE_SIMULATION...";
        }
        
        propsB -= EXAMPLE_PROP_PAUSE_SIMULATION;

        QCOMPARE(propsA == propsB, false);
        if (verbose) {
            qDebug() << "AFTER propsB = propsA...";
        }
        propsB = propsA;
        QCOMPARE(propsA == propsB, true);
    }

    {
        if (verbose) {
            qDebug() << "Test 11: ExamplePropertyFlags testing individual properties";
        }
        ExamplePropertyFlags props;

        if (verbose) {
            qDebug() << "ExamplePropertyFlags props;";
        }
        
        QByteArray encoded = props.encode();

        if (verbose) {
            qDebug() << "Test 11b: props.getHasProperty(EXAMPLE_PROP_VISIBLE)" << (props.getHasProperty(EXAMPLE_PROP_VISIBLE)) 
                        << "{ expect false }";
        }
        QCOMPARE(props.getHasProperty(EXAMPLE_PROP_VISIBLE), false);

        if (verbose) {
            qDebug() << "props << EXAMPLE_PROP_VISIBLE;";
        }
        props << EXAMPLE_PROP_VISIBLE;
        QCOMPARE(props.getHasProperty(EXAMPLE_PROP_VISIBLE), true);

        encoded = props.encode();
        QCOMPARE(encoded, makeQByteArray({ (char) 16 }));
        if (verbose) {
            qDebug() << "props << EXAMPLE_PROP_ANIMATION_URL;";
        }
        props << EXAMPLE_PROP_ANIMATION_URL;
    
        encoded = props.encode();
        QCOMPARE(encoded, makeQByteArray({ (char) 136, 16}));
        QCOMPARE(props.getHasProperty(EXAMPLE_PROP_VISIBLE), true);

        if (verbose) {
            qDebug() << "props << ... more ...";
        }
        props << EXAMPLE_PROP_ANIMATION_FPS;
        props << EXAMPLE_PROP_ANIMATION_FRAME_INDEX;
        props << EXAMPLE_PROP_ANIMATION_PLAYING;
        props << EXAMPLE_PROP_PAUSE_SIMULATION;

        encoded = props.encode();
        QCOMPARE(props.getHasProperty(EXAMPLE_PROP_VISIBLE), true);

        if (verbose) {
            qDebug() << "ExamplePropertyFlags propsB = props & EXAMPLE_PROP_VISIBLE;";
        }
        ExamplePropertyFlags propsB = props & EXAMPLE_PROP_VISIBLE;

        QCOMPARE(propsB.getHasProperty(EXAMPLE_PROP_VISIBLE), true);

        encoded = propsB.encode();
        QCOMPARE(encoded, makeQByteArray({ (char) 16 }));

        if (verbose) {
            qDebug() << "ExamplePropertyFlags propsC = ~propsB;";
        }
        ExamplePropertyFlags propsC = ~propsB;
        
        QCOMPARE(propsC.getHasProperty(EXAMPLE_PROP_VISIBLE), false);

        encoded = propsC.encode();
        if (verbose) {
            qDebug() << "propsC... encoded=";
            outputBufferBits((const unsigned char*)encoded.constData(), encoded.size());
        }
    }
    
    {
        if (verbose) {
            qDebug() << "Test 12: ExamplePropertyFlags: decode tests";
        }
        ExamplePropertyFlags props;

        props << EXAMPLE_PROP_VISIBLE;
        props << EXAMPLE_PROP_ANIMATION_URL;
        props << EXAMPLE_PROP_ANIMATION_FPS;
        props << EXAMPLE_PROP_ANIMATION_FRAME_INDEX;
        props << EXAMPLE_PROP_ANIMATION_PLAYING;
        props << EXAMPLE_PROP_PAUSE_SIMULATION;

        QByteArray encoded = props.encode();
        if (verbose) {
            qDebug() << "encoded=";
            outputBufferBits((const unsigned char*)encoded.constData(), encoded.size());
            qDebug() << "encoded.size()=" << encoded.size();
        }

        ExamplePropertyFlags propsDecoded;
        propsDecoded.decode(encoded);
        
        QCOMPARE(propsDecoded, props);

        QByteArray encodedAfterDecoded = propsDecoded.encode();

        QCOMPARE(encoded, encodedAfterDecoded);

        if (verbose) {
            qDebug() << "fill encoded byte array with extra garbage (as if it was bitstream with more content)";
        }
        QByteArray extraContent;
        extraContent.fill(0xbaU, 10);
        encoded.append(extraContent);

        if (verbose) {
            qDebug() << "encoded.size()=" << encoded.size() << "includes extra garbage";
        }

        ExamplePropertyFlags propsDecodedExtra;
        propsDecodedExtra.decode(encoded);
        
        QCOMPARE(propsDecodedExtra, props);

        QByteArray encodedAfterDecodedExtra = propsDecodedExtra.encode();

        if (verbose) {
            qDebug() << "encodedAfterDecodedExtra=";
            outputBufferBits((const unsigned char*)encodedAfterDecodedExtra.constData(), encodedAfterDecodedExtra.size());
        }
    }
    
    {
        if (verbose) {
            qDebug() << "Test 13: ExamplePropertyFlags: QByteArray << / >> tests";
        }
        ExamplePropertyFlags props;

        props << EXAMPLE_PROP_VISIBLE;
        props << EXAMPLE_PROP_ANIMATION_URL;
        props << EXAMPLE_PROP_ANIMATION_FPS;
        props << EXAMPLE_PROP_ANIMATION_FRAME_INDEX;
        props << EXAMPLE_PROP_ANIMATION_PLAYING;
        props << EXAMPLE_PROP_PAUSE_SIMULATION;

        if (verbose) {
            qDebug() << "testing encoded << props";
        }
        QByteArray encoded;
        encoded << props;

        if (verbose) {
            outputBufferBits((const unsigned char*)encoded.constData(), encoded.size());
        }

        ExamplePropertyFlags propsDecoded;
        if (verbose) {
            qDebug() << "testing encoded >> propsDecoded";
        }
        encoded >> propsDecoded;
        
        
        QCOMPARE(propsDecoded, props);
    }

    if (verbose) {
        qDebug() << "******************************************************************************************";
    }
}
Esempio n. 19
0
    /*------------------------------------------------------------------------------*

     *------------------------------------------------------------------------------*/
    void WebProxy::processQuery() {
        QTcpSocket *socket = qobject_cast<QTcpSocket*>(sender());
        QByteArray requestData = socket->readAll();

        int pos = requestData.indexOf("\r\n");
        QByteArray requestLine = requestData.left(pos);
        requestData.remove(0, pos + 2);

        QList<QByteArray> entries = requestLine.split(' ');
        QByteArray method = entries.value(0);
        QByteArray address = entries.value(1);
        QByteArray version = entries.value(2);

        qDebug( )  << __FILE__ << __FUNCTION__ << "Processing " << address;

        QUrl url = QUrl::fromEncoded(address);
        if (!url.isValid()) {
            //qWarning() << "Invalid URL:" << url;
            socket->disconnectFromHost();
            return;
        }

        //Act as server is request are for local server
        if ((url.host() == "") && (QFile(address).exists())) {
            //qDebug( )  << __FILE__ << __FUNCTION__ << "Sending " << address;
            QByteArray header;
            QTextStream headerStream(&header, QIODevice::WriteOnly);
            //Construct response header
            headerStream << "HTTP/1.0 200 OK" << endl;
            headerStream << "Server: gpsbook/" << qApp->applicationVersion() << endl;
            headerStream << "Date: " << QDateTime::currentDateTime().toUTC().toString("ddd, dd MMM yyyy hh:mm:ss") << "GMT" << endl;
            headerStream << "Content-Type: text/html; charset=utf-8" << endl;
            headerStream << "Connection: close" << endl;
            headerStream << "Pragma: no-cache" << endl;
            headerStream << "Cache-Control: no-cache" << endl;
            QFile file(address);
            if (!file.open(QFile::ReadOnly | QFile::Text))
            {
                 qWarning() << "Cannot open:" << address;
                 socket->disconnectFromHost();
                 return ;
            }

            QByteArray content;
            QTextStream contentStream(&content, QIODevice::WriteOnly);

            while (!file.atEnd()) {
                contentStream << file.readLine() << endl;
            }

            headerStream << "Content-Length:" << content.size() << endl;
            headerStream << "" << endl;

            socket->write(header);
            socket->write(content);
            //qDebug( )  << __FILE__ << __FUNCTION__ << "File sent (" << content.size() << "bytes) :-)";
            socket->disconnectFromHost();
        return;
        }


#if ( QT_VERSION >= QT_VERSION_CHECK(5, 0, 0) )
        // Some finction of QUrl have been deprecated
        // This code is require for the internet browser and should be reviewed.
#else


#ifdef Q_OS_LINUX
        //Remove advert to speedup development ;-)
        if (url.toString().contains("googlesyndication") ||
            url.toString().contains("yieldmanager.com")) {
            socket->disconnectFromHost();
            return;
        }
#endif

        qDebug( )  << __FILE__ << __FUNCTION__ << "URL: " << url.toString();

        QString host = url.host();
        int port = (url.port() < 0) ? 80 : url.port();
        QByteArray req = url.encodedPath();
        if (url.hasQuery())
            req.append('?').append(url.encodedQuery());
        requestLine = method + " " + req + " " + version + "\r\n";
        requestData.prepend(requestLine);

        QString key = host + ':' + QString::number(port);
        QTcpSocket *proxySocket = socket->findChild<QTcpSocket*>(key);
        if (proxySocket) {
            proxySocket->setObjectName(key);
            proxySocket->setProperty("url", url);
            proxySocket->setProperty("requestData", requestData);
            proxySocket->write(requestData);
        } else {
            proxySocket = new QTcpSocket(socket);
            proxySocket->setObjectName(key);
            proxySocket->setProperty("url", url);
            proxySocket->setProperty("requestData", requestData);
            connect(proxySocket, SIGNAL(connected()), this, SLOT(sendRequest()));
            connect(proxySocket, SIGNAL(readyRead()), this, SLOT(transferData()));
            connect(proxySocket, SIGNAL(disconnected()), this, SLOT(closeConnection()));
            connect(proxySocket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(closeConnection()));
            proxySocket->connectToHost(host, port);
        }
#endif
    } //WebProxy::processQuery
Esempio n. 20
0
void KettlerConnection::requestAll()
{
    // If something else is blocking mutex, don't start another round of requests
    if (! m_mutex.tryLock())
        return;

    // Discard any existing data
    QByteArray discarded = m_serial->readAll();

    m_serial->write("st\r\n");
    m_serial->waitForBytesWritten(1000);

    QByteArray data;
    bool completeReplyRead = false;
    bool failed = false;
    int maxRetries = 3;
    do
    {
        if (m_serial->waitForReadyRead(500))
        {
            data.append(m_serial->readAll());
        } else {
            failed = true;
        }

        QString dataString = QString(data);
        QStringList splits = dataString.split(QRegExp("\\s"));

        // We need to make sure the last split is 3 chars long, otherwise we
        // might have read a partial power value

        if (splits.size() >= 8 && (splits.at(7).length() >= 3))
        {
            completeReplyRead = true;
            failed = false;
            bool ok;

            quint32 newHeartrate = splits.at(0).toUInt(&ok);
            if (ok)
            {
                emit pulse(newHeartrate);
            }

            quint32 newCadence = splits.at(1).toUInt(&ok);
            if (ok)
            {
                emit cadence(newCadence);
            }

            quint32 newSpeed = splits.at(2).toUInt(&ok);
            if (ok)
            {
                emit speed(newSpeed/10);
            }

            quint32 newPower = splits.at(7).toUInt(&ok);

            if (ok)
            {
                emit power(newPower);
            }
        } else if (splits.size() > 8) {
            qDebug() << "Kettler: Faulty sample, larger than 8 splits.";
            failed = true;
        }

        if (--maxRetries == 0)
        {
            failed = true;
        }
    } while ((!completeReplyRead) || failed);

    if ((m_loadToWrite != m_load))
    {
        QString cmd = QString("pw %1\r\n").arg(m_loadToWrite);
        m_serial->write(cmd.toStdString().c_str());
        if (!m_serial->waitForBytesWritten(500))
        {
            // failure to write to device, bail out
            this->exit(-1);
        }
        m_load = m_loadToWrite;

        // Ignore reply
        QByteArray data = m_serial->readAll();

        data.append('\0');
    }

    m_mutex.unlock();
}
Esempio n. 21
0
void DuktoProtocol::sendData(qint64 b)
{
    QByteArray d;

    // Aggiornamento statistiche
    mSentData += b;
    updateStatus();

    // Verifica se tutti i dati messi nel buffer
    // sono stati inviati
    mSentBuffer -= b;

    // Se ci sono altri dati da inviare, attendo
    // che vengano inviati
    if (mSentBuffer > 0) return;

    // Se si tratta di un invio testuale, butto dentro
    // tutto il testo
    if ((!mTextToSend.isEmpty()) && (mFilesToSend->at(mFileCounter - 1) == "___DUKTO___TEXT___"))
    {
        d.append(mTextToSend.toUtf8().data());
        mCurrentSocket->write(d);
        mSentBuffer = d.size();
        mTextToSend.clear();
        return;
    }

    // Se il file corrente non è ancora terminato
    // invio una nuova parte del file
    if (mCurrentFile)
        d = mCurrentFile->read(10000);
    if (d.size() > 0)
    {
        mCurrentSocket->write(d);
        mSentBuffer = d.size();
        return;
    }

    // Altrimenti chiudo il file e passo al prossimo
    d.append(nextElementHeader());

    // Non ci sono altri file da inviare?
    if (d.size() == 0)
    {
        // Chiudo la connessione
        mCurrentSocket->disconnect();
        mCurrentSocket->disconnectFromHost();
        mCurrentSocket->waitForDisconnected(1000);
        mCurrentSocket->close();
        mCurrentSocket->deleteLater();
        mCurrentSocket = NULL;
        if (mCurrentFile)
        {
            mCurrentFile->close();
            delete mCurrentFile;
            mCurrentFile = NULL;
        }
        mIsSending = false;
        sendFileComplete(mFilesToSend);
        delete mFilesToSend;
        mFilesToSend = NULL;
        return;
    }

    // Invio l'header insime al primo chunk di file
    mTotalSize += d.size();
    if (mCurrentFile)
        d.append(mCurrentFile->read(10000));
    mCurrentSocket->write(d);
    mSentBuffer += d.size();
    return;

}
void SshIncomingPacket::moveFirstBytes(QByteArray &target, QByteArray &source,
    int n)
{
    target.append(source.left(n));
    source.remove(0, n);
}
Esempio n. 23
0
SimThread::Packet SimThread::parseBuffer(QByteArray buffer)
{
	if (buffer.size() <= 2)
	{

		qDebug() << "Not long enough to even contain a header!";
		//emit decoderFailure(buffer);
		return Packet(false);
	}


	//qDebug() << "Packet:" << QString::number(buffer[1],16) << QString::number(buffer[buffer.length()-2],16);
	Packet retval;
	retval.origionalPacket = buffer;
	QByteArray header;
	//currPacket.clear();
	//Parse the packet here
	int headersize = 3;
	int iloc = 0;
	bool seq = false;
	bool len = false;
	if (buffer[iloc] & 0x100)
	{
		//Has header
		seq = true;
		//qDebug() << "Has seq";
		headersize += 1;
	}
	if (buffer[iloc] & 0x1)
	{
		//Has length
		len = true;
		//qDebug() << "Has length";
		headersize += 2;
	}
	header = buffer.mid(0,headersize);
	iloc++;
	unsigned int payloadid = (unsigned int)buffer[iloc] << 8;

	payloadid += (unsigned char)buffer[iloc+1];
	retval.payloadid = payloadid;
	iloc += 2;
	if (seq)
	{
		//qDebug() << "Sequence number" << QString::number(currPacket[iloc]);
		iloc += 1;
		retval.hasseq = true;
	}
	else
	{
		retval.hasseq = false;
	}
	QByteArray payload;
	if (len)
	{
		retval.haslength = true;
		//qDebug() << "Length found, buffer size:" << buffer.length() << "iloc:" << QString::number(iloc);
		unsigned int length = buffer[iloc] << 8;
		length += (unsigned char)buffer[iloc+1];
		retval.length = length;
		//qDebug() << "Length:" << length;
		iloc += 2;
		//curr += length;
		if ((unsigned int)buffer.length() > (unsigned int)(length + iloc))
		{
			qDebug() << "Packet length should be:" << length + iloc << "But it is" << buffer.length();
			//emit decoderFailure(buffer);
			return Packet(false);
		}
		payload.append(buffer.mid(iloc,length));
	}
	else
	{
		retval.haslength = false;
		//qDebug() << "Buffer length:" << buffer.length();
		//qDebug() << "Attempted cut:" << buffer.length() - iloc;
		payload.append(buffer.mid(iloc),(buffer.length()-iloc));
	}
	//qDebug() << "Payload";
	QString output;
	for (int i=0;i<payload.size();i++)
	{
		int num = (unsigned char)payload[i];
		output.append(" ").append((num < 0xF) ? "0" : "").append(QString::number(num,16));
	}
	//qDebug() << output;
	output.clear();
	//qDebug() << "Header";
	for (int i=0;i<header.size();i++)
	{
		int num = (unsigned char)header[i];
		output.append(" ").append((num < 0xF) ? "0" : "").append(QString::number(num,16));
	}
	//qDebug() << output;
	//Last byte of currPacket should be out checksum.
	retval.header = header;
	retval.payload = payload;
	if (header[0] & NAK)
	{
		retval.isNAK = true;
	}
	else
	{
		retval.isNAK = false;
	}
	if (init)
	{
		if (retval.payloadid == 0x0105 || retval.payloadid == 0x0107)
		{
			locationidList.append(retval);
		}
		if (retval.payloadid == 0xF8E1)
		{
			locationidInfoList.append(retval);
		}
		else
		{
			//qDebug() << "Bad packet?";
		}
	}
	if (retval.header.size() >= 3)
	{
		return retval;
	}

	return Packet(false);
}
void JSKitXMLHttpRequest::send(const QJSValue &data)
{
    QByteArray byteData;

    if (data.isUndefined() || data.isNull()) {
        // Do nothing, byteData is empty.
    } else if (data.isString()) {
        byteData = data.toString().toUtf8();
    } else if (data.isObject()) {
        if (data.hasProperty("byteLength")) {
            // Looks like an ArrayView or an ArrayBufferView!
            QJSValue buffer = data.property("buffer");
            if (buffer.isUndefined()) {
                // We must assume we've been passed an ArrayBuffer directly
                buffer = data;
            }

            QJSValue array = data.property("_bytes");
            int byteLength = data.property("byteLength").toInt();

            if (array.isArray()) {
                byteData.reserve(byteLength);

                for (int i = 0; i < byteLength; i++) {
                    byteData.append(array.property(i).toInt());
                }

                qCDebug(l) << "passed an ArrayBufferView of" << byteData.length() << "bytes";
            } else {
                qCWarning(l) << "passed an unknown/invalid ArrayBuffer" << data.toString();
            }
        } else {
            qCWarning(l) << "passed an unknown object" << data.toString();
        }

    }

    QBuffer *buffer;
    if (!byteData.isEmpty()) {
        buffer = new QBuffer;
        buffer->setData(byteData);
    } else {
        buffer = 0;
    }

    qCDebug(l) << "sending" << m_verb << "to" << m_request.url() << "with" << QString::fromUtf8(byteData);
    m_reply = m_net->sendCustomRequest(m_request, m_verb.toLatin1(), buffer);

    connect(m_reply, &QNetworkReply::finished,
            this, &JSKitXMLHttpRequest::handleReplyFinished);
    connect(m_reply, static_cast<void (QNetworkReply::*)(QNetworkReply::NetworkError)>(&QNetworkReply::error),
            this, &JSKitXMLHttpRequest::handleReplyError);

    if (buffer) {
        // So that it gets deleted alongside the reply object.
        buffer->setParent(m_reply);
    }

    if (!m_async) {
        QEventLoop loop; //Hacky way to get QNetworkReply be synchronous

        connect(m_reply, &QNetworkReply::finished,
                &loop, &QEventLoop::quit);
        connect(m_reply, static_cast<void (QNetworkReply::*)(QNetworkReply::NetworkError)>(&QNetworkReply::error),
                &loop, &QEventLoop::quit);

        loop.exec();
    }
}
Esempio n. 25
0
void FeedbackDialog::SendFeedback()
{
    // Get form data

    QString summary = this->summary->text();
    QString description = this->description->toPlainText();
    QString email = this->email->text();
    QString captchaCode = this->captcha_code->text();
    QString captchaID = QString::number(this->captchaID);
    QString version = "HedgewarsFoundation-Hedgewars-v" + *cVersionString + "_r" +
                       *cRevisionString + "|" + *cHashString;

    if (summary.isEmpty() || description.isEmpty())
    {
        ShowErrorMessage(QMessageBox::tr("Please fill out all fields. Email is optional."));
        return;
    }

    // Submit issue to PHP script

    QByteArray body;
    body.append("captcha=");
    body.append(captchaID);
    body.append("&code=");
    body.append(captchaCode);
    body.append("&version=");
    body.append(QUrl::toPercentEncoding(version));
    body.append("&title=");
    body.append(QUrl::toPercentEncoding(summary));
    body.append("&body=");
    body.append(QUrl::toPercentEncoding(description));
    body.append("&email=");
    body.append(QUrl::toPercentEncoding(email));
    if (CheckSendSpecs->isChecked())
    {
        body.append("&specs=");
        body.append(QUrl::toPercentEncoding(specs));
    }

    nam = new QNetworkAccessManager(this);
    connect(nam, SIGNAL(finished(QNetworkReply*)),
            this, SLOT(finishedSlot(QNetworkReply*)));

    QNetworkRequest header(QUrl("http://hedgewars.org/feedback/?submit"));
    header.setRawHeader("Content-Length", QString::number(body.size()).toAscii());
    header.setRawHeader("Content-Type", "application/x-www-form-urlencoded");

    nam->post(header, body);
}
Esempio n. 26
0
QVariant QDbfSqlModel::data(const QModelIndex &index, int role) const
{

    QVariant value = QSqlQueryModel::data(index, role);
    int i,j,k;

    QByteArray tempDateArray;
    QDate tempDate;
    QTime tempTime;
    quint32 l;
    qint32 l1;
    qint64 l2;
    double db;
    bool ok;
    QString currency;
    //QLocale clocale(QLocale::German);
    QLocale clocale(QLocale::C);
    quint8 r,g,b;
    QByteArray tempByteArray;

    //QList<int> charFields;
    for (i=0;i<charFields.count();i++)
        {
            if (index.column() == charFields.at(i))
                {
                    switch (role)
                        {
                            case Qt::DisplayRole:
                                break;
                            case Qt::TextAlignmentRole:
                                value = QVariant(Qt::AlignLeft | Qt::AlignVCenter);
                                break;
                            case Qt::TextColorRole:
                                tempByteArray.append(charFieldColorString);
                                tempByteArray = QByteArray::fromHex(tempByteArray);
                                r = tempByteArray.at(0);
                                g = tempByteArray.at(1);
                                b = tempByteArray.at(2);
                                QColor tempColor(r,g,b);
                                value = qVariantFromValue(tempColor);
                                break;
                        }
                }
        }
    //QList<int> currencyFields;
    for (i=0;i<currencyFields.count();i++)
        {
            if (index.column() == currencyFields.at(i))
                {
                    switch (role)
                        {
                            case Qt::DisplayRole:
                                tempDateArray = value.toByteArray();
                                tempDateArray = QByteArray::fromHex(tempDateArray);

                                l2 = *(qint64 *)tempDateArray.data();

                                db = l2;
                                currency.setNum(db/10000,'f',4);

                                value = clocale.toString(db/10000,'f',4);
                                break;
                            case Qt::TextAlignmentRole:
                                value = QVariant(Qt::AlignRight | Qt::AlignVCenter);
                                break;
                            case Qt::TextColorRole:
                                tempByteArray.append(currencyFieldColorString);
                                tempByteArray = QByteArray::fromHex(tempByteArray);
                                r = tempByteArray.at(0);
                                g = tempByteArray.at(1);
                                b = tempByteArray.at(2);
                                QColor tempColor(r,g,b);
                                value = qVariantFromValue(tempColor);
                                break;
                        }
                }
        }
    //QList<int> numericFields;
    for (i=0;i<numericFields.count();i++)
        {
            if (index.column() == numericFields.at(i))
                {
                    switch (role)
                        {
                            case Qt::DisplayRole:
                                currency=value.toString().simplified();
                                k=currency.count()-1;
                                j=0;
                                ok=false;
                                while (k>0)
                                    {
                                        if (currency.at(k) == '.')
                                            {
                                                ok = true;
                                                break;
                                            }
                                        k--;
                                        j++;
                                    }
                                if (!ok) j=0;
                                value = clocale.toString(currency.toDouble(&ok),'f',j);
                                break;
                            case Qt::TextAlignmentRole:
                                value = QVariant(Qt::AlignRight | Qt::AlignVCenter);
                                break;
                            case Qt::TextColorRole:
                                tempByteArray.append(numericFieldColorString);
                                tempByteArray = QByteArray::fromHex(tempByteArray);
                                r = tempByteArray.at(0);
                                g = tempByteArray.at(1);
                                b = tempByteArray.at(2);
                                QColor tempColor(r,g,b);
                                value = qVariantFromValue(tempColor);
                                break;
                        }
                }
        }
    //QList<int> dateFields;
    for (i=0;i<dateFields.count();i++)
        {
            if (index.column() == dateFields.at(i))
                {
                    switch (role)
                        {
                            case Qt::DisplayRole:
                                value = value.toDate().toString("dd.MM.yyyy");
                                break;
                            case Qt::TextAlignmentRole:
                                value = QVariant(Qt::AlignRight | Qt::AlignVCenter);
                                break;
                            case Qt::TextColorRole:
                                tempByteArray.append(dateFieldColorString);
                                tempByteArray = QByteArray::fromHex(tempByteArray);
                                r = tempByteArray.at(0);
                                g = tempByteArray.at(1);
                                b = tempByteArray.at(2);
                                QColor tempColor(r,g,b);
                                value = qVariantFromValue(tempColor);
                                break;
                        }
                }
        }
    //QList<int> timeFields;
    for (i=0;i<timeFields.count();i++)
        {
            if (index.column() == timeFields.at(i))
                {
                    switch (role)
                        {
                            case Qt::DisplayRole:
                                tempDateArray = value.toByteArray();
                                tempDateArray = QByteArray::fromHex(tempDateArray);

                                l = *(quint32 *)tempDateArray.data();

                                tempDate = QDate::fromJulianDay(l);

                                l = *(quint32 *)(tempDateArray.data()+4);

                                tempTime.setHMS(0,0,0);
                                tempTime = tempTime.addMSecs(l);

                                value = tempDate.toString("dd.MM.yyyy")+" "+tempTime.toString("hh:mm:ss.zzz");

                                break;
                            case Qt::TextAlignmentRole:
                                value = QVariant(Qt::AlignRight | Qt::AlignVCenter);
                                break;
                            case Qt::TextColorRole:                                
                                tempByteArray.append(timeFieldColorString);
                                tempByteArray = QByteArray::fromHex(tempByteArray);
                                r = tempByteArray.at(0);
                                g = tempByteArray.at(1);
                                b = tempByteArray.at(2);
                                QColor tempColor(r,g,b);
                                value = qVariantFromValue(tempColor);
                                break;
                        }
                }
        }
    //QList<int> doubleFields;
    for (i=0;i<doubleFields.count();i++)
        {
            if (index.column() == doubleFields.at(i))
                {
                    switch (role)
                        {
                            case Qt::DisplayRole:
                                tempDateArray = value.toByteArray();
                                tempDateArray = QByteArray::fromHex(tempDateArray);

                                db = *(double *)tempDateArray.data();

                                value = db;
                                //value = clocale.toString(db,'f',4);
                                break;
                            case Qt::TextAlignmentRole:
                                value = QVariant(Qt::AlignRight | Qt::AlignVCenter);
                                break;
                            case Qt::TextColorRole:
                                tempByteArray.append(doubleFieldColorString);
                                tempByteArray = QByteArray::fromHex(tempByteArray);
                                r = tempByteArray.at(0);
                                g = tempByteArray.at(1);
                                b = tempByteArray.at(2);
                                QColor tempColor(r,g,b);
                                value = qVariantFromValue(tempColor);
                                break;
                        }
                }
        }
    //QList<int> intFields;
    for (i=0;i<intFields.count();i++)
        {
            if (index.column() == intFields.at(i))
                {
                    switch (role)
                        {
                            case Qt::DisplayRole:
                                tempDateArray = value.toByteArray();
                                tempDateArray = QByteArray::fromHex(tempDateArray);

                                l1 = *(quint32 *)tempDateArray.data();

                                value = l1;

                                break;
                            case Qt::TextAlignmentRole:
                                value = QVariant(Qt::AlignRight | Qt::AlignVCenter);
                                break;
                            case Qt::TextColorRole:
                                tempByteArray.append(intFieldColorString);
                                tempByteArray = QByteArray::fromHex(tempByteArray);
                                r = tempByteArray.at(0);
                                g = tempByteArray.at(1);
                                b = tempByteArray.at(2);
                                QColor tempColor(r,g,b);
                                value = qVariantFromValue(tempColor);
                                break;
                        }
                }
        }
    //QList<int> logicalFields;
    for (i=0;i<logicalFields.count();i++)
        {
            if (index.column() == logicalFields.at(i))
                {
                    switch (role)
                        {
                            case Qt::DisplayRole:
                                break;
                            case Qt::TextAlignmentRole:
                                value = QVariant(Qt::AlignRight | Qt::AlignVCenter);
                                break;
                            case Qt::TextColorRole:
                                tempByteArray.append(logicalFieldColorString);
                                tempByteArray = QByteArray::fromHex(tempByteArray);
                                r = tempByteArray.at(0);
                                g = tempByteArray.at(1);
                                b = tempByteArray.at(2);
                                QColor tempColor(r,g,b);
                                value = qVariantFromValue(tempColor);
                                break;
                        }
                }
        }
    //QList<int> memoFields;
    for (i=0;i<memoFields.count();i++)
        {
            if (index.column() == memoFields.at(i))
                {
                    switch (role)
                        {
                            case Qt::DisplayRole:
                                break;
                            case Qt::TextAlignmentRole:
                                value = QVariant(Qt::AlignRight | Qt::AlignVCenter);
                                break;
                            case Qt::TextColorRole:
                                tempByteArray.append(memoFieldColorString);
                                tempByteArray = QByteArray::fromHex(tempByteArray);
                                r = tempByteArray.at(0);
                                g = tempByteArray.at(1);
                                b = tempByteArray.at(2);
                                QColor tempColor(r,g,b);
                                value = qVariantFromValue(tempColor);
                                break;
                        }
                }
        }
    //QList<int> memo4Fields;
    for (i=0;i<memo4Fields.count();i++)
        {
            if (index.column() == memo4Fields.at(i))
                {
                    switch (role)
                        {
                            case Qt::DisplayRole:
                                tempDateArray = value.toByteArray();
                                tempDateArray = QByteArray::fromHex(tempDateArray);

                                l = *(quint32 *)tempDateArray.data();

                                value = l;

                                break;
                            case Qt::TextAlignmentRole:
                                value = QVariant(Qt::AlignRight | Qt::AlignVCenter);
                                break;
                            case Qt::TextColorRole:
                                tempByteArray.append(memo4FieldColorString);
                                tempByteArray = QByteArray::fromHex(tempByteArray);
                                r = tempByteArray.at(0);
                                g = tempByteArray.at(1);
                                b = tempByteArray.at(2);
                                QColor tempColor(r,g,b);
                                value = qVariantFromValue(tempColor);
                                break;
                        }
                }
        }
    //QList<int> generalFields;
    for (i=0;i<generalFields.count();i++)
        {
            if (index.column() == generalFields.at(i))
                {
                    switch (role)
                        {
                            case Qt::DisplayRole:
                                break;
                            case Qt::TextAlignmentRole:
                                value = QVariant(Qt::AlignRight | Qt::AlignVCenter);
                                break;
                            case Qt::TextColorRole:
                                tempByteArray.append(generalFieldColorString);
                                tempByteArray = QByteArray::fromHex(tempByteArray);
                                r = tempByteArray.at(0);
                                g = tempByteArray.at(1);
                                b = tempByteArray.at(2);
                                QColor tempColor(r,g,b);
                                value = qVariantFromValue(tempColor);
                                break;
                        }
                }
        }
    return value;
}
Esempio n. 27
0
void ContactUser::updateOutgoingSocket()
{
    if (m_status != Offline && m_status != RequestPending) {
        if (m_outgoingSocket) {
            m_outgoingSocket->disconnect(this);
            m_outgoingSocket->abort();
            m_outgoingSocket->deleteLater();
            m_outgoingSocket = 0;
        }
        return;
    }

    // Refuse to make outgoing connections to the local hostname
    if (hostname() == identity->hostname())
        return;

    if (m_outgoingSocket && m_outgoingSocket->status() == Protocol::OutboundConnector::Ready) {
        BUG() << "Called updateOutgoingSocket with an existing socket in Ready. This should've been deleted.";
        m_outgoingSocket->disconnect(this);
        m_outgoingSocket->deleteLater();
        m_outgoingSocket = 0;
    }

    if (!m_outgoingSocket) {
        m_outgoingSocket = new Protocol::OutboundConnector(this);
        m_outgoingSocket->setAuthPrivateKey(identity->hiddenService()->cryptoKey());
        connect(m_outgoingSocket, &Protocol::OutboundConnector::ready, this,
            [this]() {
                assignConnection(m_outgoingSocket->takeConnection());
            }
        );

        /* As an ugly hack, because Ricochet 1.0.x versions have no way to notify about
         * protocol issues, and it's not feasible to support both protocols for this
         * tiny upgrade period:
         *
         * The first time we make an outgoing connection to an existing contact, if they
         * are using the old version, send a chat message that lets them know about the
         * new version, then disconnect. This message is only sent once per contact.
         *
         * XXX: This logic should be removed an appropriate amount of time after the new
         * protocol has been released.
         */
        connect(m_outgoingSocket, &Protocol::OutboundConnector::oldVersionNegotiated, this,
            [this](QTcpSocket *socket) {
                if (m_settings->read("sentUpgradeNotification").toBool())
                    return;
                QByteArray secret = m_settings->read<Base64Encode>("remoteSecret");
                if (secret.size() != 16)
                    return;

                static const char upgradeMessage[] =
                    "[automatic message] I'm using a newer version of Ricochet that is not "
                    "compatible with yours. This is a one-time change to help improve Ricochet. "
                    "See https://ricochet.im/upgrade for instructions on getting the latest "
                    "version. Once you have upgraded, I will be able to see your messages again.";
                uchar command[] = {
                    0x00, 0x00, 0x10, 0x00, 0x00, 0x01, 0x00,
                    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
                };

                qToBigEndian(quint16(sizeof(upgradeMessage) + 7), command);
                qToBigEndian(quint16(sizeof(upgradeMessage) - 1), command + sizeof(command) - sizeof(quint16));

                QByteArray data;
                data.append((char)0x00);
                data.append(secret);
                data.append(reinterpret_cast<const char*>(command), sizeof(command));
                data.append(upgradeMessage);
                socket->write(data);

                m_settings->write("sentUpgradeNotification", true);
                updateStatus();
            }
        );
    }

    m_outgoingSocket->connectToHost(hostname(), port());
}
Esempio n. 28
0
void QWinSettingsPrivate::set(const QString &uKey, const QVariant &value)
{
    if (writeHandle() == 0) {
        setStatus(QSettings::AccessError);
        return;
    }

    QString rKey = escapedKey(uKey);

    HKEY handle = createOrOpenKey(writeHandle(), registryPermissions, keyPath(rKey));
    if (handle == 0) {
        setStatus(QSettings::AccessError);
        return;
    }

    DWORD type;
    QByteArray regValueBuff;

    // Determine the type
    switch (value.type()) {
        case QVariant::List:
        case QVariant::StringList: {
            // If none of the elements contains '\0', we can use REG_MULTI_SZ, the
            // native registry string list type. Otherwise we use REG_BINARY.
            type = REG_MULTI_SZ;
            QStringList l = variantListToStringList(value.toList());
            QStringList::const_iterator it = l.constBegin();
            for (; it != l.constEnd(); ++it) {
                if ((*it).length() == 0 || stringContainsNullChar(*it)) {
                    type = REG_BINARY;
                    break;
                }
            }

            if (type == REG_BINARY) {
                QString s = variantToString(value);
                regValueBuff = QByteArray((const char*)s.utf16(), s.length() * 2);
            } else {
                QStringList::const_iterator it = l.constBegin();
                for (; it != l.constEnd(); ++it) {
                    const QString &s = *it;
                    regValueBuff += QByteArray((const char*)s.utf16(), (s.length() + 1) * 2);
                }
                regValueBuff.append((char)0);
                regValueBuff.append((char)0);
            }
            break;
        }

        case QVariant::Int:
        case QVariant::UInt: {
            type = REG_DWORD;
            qint32 i = value.toInt();
            regValueBuff = QByteArray((const char*)&i, sizeof(qint32));
            break;
        }

        case QVariant::LongLong:
        case QVariant::ULongLong: {
            type = REG_QWORD;
            qint64 i = value.toLongLong();
            regValueBuff = QByteArray((const char*)&i, sizeof(qint64));
            break;
        }

        case QVariant::ByteArray:
            // fallthrough intended

        default: {
            // If the string does not contain '\0', we can use REG_SZ, the native registry
            // string type. Otherwise we use REG_BINARY.
            QString s = variantToString(value);
            type = stringContainsNullChar(s) ? REG_BINARY : REG_SZ;
            if (type == REG_BINARY) {
                regValueBuff = QByteArray((const char*)s.utf16(), s.length() * 2);
            } else {
                regValueBuff = QByteArray((const char*)s.utf16(), (s.length() + 1) * 2);
            }
            break;
        }
    }

    // set the value
    LONG res = RegSetValueEx(handle, reinterpret_cast<const wchar_t *>(keyName(rKey).utf16()), 0, type,
                             reinterpret_cast<const unsigned char*>(regValueBuff.constData()),
                             regValueBuff.size());

    if (res == ERROR_SUCCESS) {
        deleteWriteHandleOnExit = false;
    } else {
        qWarning("QSettings: failed to set subkey \"%s\": %s",
                rKey.toLatin1().data(), errorCodeToString(res).toLatin1().data());
        setStatus(QSettings::AccessError);
    }

    RegCloseKey(handle);
}
Esempio n. 29
0
void PaymentServer::handleURIOrFile(const QString& s)
{
    if (saveURIs)
    {
        savedPaymentRequests.append(s);
        return;
    }

    if (s.startsWith(BITCOIN_IPC_PREFIX, Qt::CaseInsensitive)) // bitcoin: URI
    {
#if QT_VERSION < 0x050000
        QUrl uri(s);
#else
        QUrlQuery uri((QUrl(s)));
#endif
        if (uri.hasQueryItem("r")) // payment request URI
        {
            QByteArray temp;
            temp.append(uri.queryItemValue("r"));
            QString decoded = QUrl::fromPercentEncoding(temp);
            QUrl fetchUrl(decoded, QUrl::StrictMode);

            if (fetchUrl.isValid())
            {
                qDebug() << "PaymentServer::handleURIOrFile: fetchRequest(" << fetchUrl << ")";
                fetchRequest(fetchUrl);
            }
            else
            {
                qWarning() << "PaymentServer::handleURIOrFile: Invalid URL: " << fetchUrl;
                Q_EMIT message(tr("URI handling"),
                    tr("Payment request fetch URL is invalid: %1").arg(fetchUrl.toString()),
                    CClientUIInterface::ICON_WARNING);
            }

            return;
        }
        else // normal URI
        {
            SendCoinsRecipient recipient;
            if (GUIUtil::parseBitcoinURI(s, &recipient))
            {
                if (!IsValidDestinationString(recipient.address.toStdString())) {
                    Q_EMIT message(tr("URI handling"), tr("Invalid payment address %1").arg(recipient.address),
                        CClientUIInterface::MSG_ERROR);
                }
                else
                    Q_EMIT receivedPaymentRequest(recipient);
            }
            else
                Q_EMIT message(tr("URI handling"),
                    tr("URI cannot be parsed! This can be caused by an invalid Bitcoin address or malformed URI parameters."),
                    CClientUIInterface::ICON_WARNING);

            return;
        }
    }

    if (QFile::exists(s)) // payment request file
    {
        PaymentRequestPlus request;
        SendCoinsRecipient recipient;
        if (!readPaymentRequestFromFile(s, request))
        {
            Q_EMIT message(tr("Payment request file handling"),
                tr("Payment request file cannot be read! This can be caused by an invalid payment request file."),
                CClientUIInterface::ICON_WARNING);
        }
        else if (processPaymentRequest(request, recipient))
            Q_EMIT receivedPaymentRequest(recipient);

        return;
    }
}
Esempio n. 30
0
void BytesInteger::transform(const QByteArray &input, QByteArray &output)
{
    output.clear();
    if (input.isEmpty())
        return;

    bool reverseByteOrdering = false;

#ifdef Q_LITTLE_ENDIAN
    bool currentSystemLittleEndian = true;
#else
    bool currentSystemLittleEndian = false;
#endif

    if (currentSystemLittleEndian != littleendian) {
        reverseByteOrdering = true;
    }

    QByteArray temp = input;
    if (wayValue == INBOUND) {

        if (temp.size() > integerSize) {
            temp = temp.mid(0,integerSize);
            emit warning(tr("Input size too big for the selected Integer size. the last bytes have been ignored"),id);
        }

        if (temp.size() < integerSize) {
            if (reverseByteOrdering)
                temp.prepend(QByteArray(integerSize - temp.size(),'\x00'));
            else
                temp.append(QByteArray(integerSize - temp.size(),'\x00'));
            emit error(tr("Input size too small for the selected Integer size. Padded with zeros"),id);
        }

        if (reverseByteOrdering) {
            QByteArray temp2;
            for (int i = temp.size() - 1; i >= 0; i--) {
                temp2.append(temp.at(i));
            }
            temp = temp2;
        }



        if (signedInteger) {
            switch (integerSize) {
            case I8bits: {
                    qint8 val = 0;
                    memcpy(&val, temp.data(), integerSize);
                    output.append(QByteArray::number(val));
                    break;
            }
            case I16bits: {
                    qint16 val = 0;
                    memcpy(&val, temp.data(), integerSize);
                    output.append(QByteArray::number(val));
                    break;
            }
            case I32bits: {
                    qint32 val = 0;
                    memcpy(&val, temp.data(), integerSize);
                    output.append(QByteArray::number(val));
                    break;
            }
            case I64bits: {
                    qint64 val = 0;
                    memcpy(&val, temp.data(), integerSize);
                    output.append(QByteArray::number(val));
                    break;
            }
            }

        } else {
            switch (integerSize) {
            case I8bits: {
                    quint8 val = 0;
                    memcpy(&val, temp.data(), integerSize);
                    output.append(QByteArray::number(val));
                    break;
            }
            case I16bits: {
                    quint16 val = 0;
                    memcpy(&val, temp.data(), integerSize);
                    output.append(QByteArray::number(val));
                    break;
            }
            case I32bits: {
                    quint32 val = 0;
                    memcpy(&val, temp.data(), integerSize);
                    output.append(QByteArray::number(val));
                    break;
            }
            case I64bits: {
                    quint64 val = 0;
                    memcpy(&val, temp.data(), integerSize);
                    output.append(QByteArray::number(val));
                    break;
            }
            }
        }
    } else {
        bool ok;
        char data[8] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };

        if (signedInteger) {
            switch (integerSize) {
            case I8bits: {
                    qint16 val16 = input.toShort(&ok);
                    if (ok && val16 > -129 && val16 < 128) {
                        qint8 val8 = (qint8)val16;
                        memcpy(data, &val8, I8bits);
                    } else {
                        emit error(tr("Invalid 8bits signed Integer"),id);
                    }

                    break;
            }
            case I16bits: {
                    qint16 val16 = input.toShort(&ok);
                    if (ok) {
                        memcpy(data, &val16, I16bits);
                    } else {
                        emit error(tr("Invalid 16bits signed Integer"),id);
                    }
                    break;
            }
            case I32bits: {
                    qint32 val32 = input.toInt(&ok);
                    if (ok) {
                        memcpy(data, &val32, I32bits);
                    } else {
                        emit error(tr("Invalid 32bits signed Integer"),id);
                    }
                    break;
            }
            case I64bits: {
                    qint64 val64 = input.toInt(&ok);
                    if (ok) {
                        memcpy(data, &val64, I64bits);
                    } else {
                        emit error(tr("Invalid 64bits signed Integer"),id);
                    }
                    break;
            }
            }
        } else {
                switch (integerSize) {
                case I8bits: {
                        quint16 val16 = input.toShort(&ok);
                        if (ok && val16 < 256) {
                            quint8 val8 = (qint8)val16;
                            memcpy(data, &val8, I8bits);
                        } else {
                            emit error(tr("Invalid 8bits unsigned Integer"),id);
                        }
                }
                case I16bits: {
                        quint16 val16 = input.toShort(&ok);
                        if (ok) {
                            memcpy(data, &val16, I16bits);
                        } else {
                            emit error(tr("Invalid 16bits unsigned Integer"),id);
                        }
                        break;
                }
                case I32bits: {
                        quint32 val32 = input.toInt(&ok);
                        if (ok) {
                            memcpy(data, &val32, I32bits);
                        } else {
                            emit error(tr("Invalid 32bits unsigned Integer"),id);
                        }
                        break;
                }
                case I64bits: {
                        quint64 val64 = input.toInt(&ok);
                        if (ok) {
                            memcpy(data, &val64, I64bits);
                        } else {
                            emit error(tr("Invalid 64bits unsigned Integer"),id);
                        }
                        break;
                }
                }
            }
        if (reverseByteOrdering) {
            for (int i = integerSize - 1; i >= 0; i--) {
                output.append(data[i]);
            }
        } else {
            output = QByteArray(data, integerSize);
        }

    }
}