Ejemplo n.º 1
0
QString MIMECodec::translate(const QCString &name)
{
  QString output;

  if (!name.isEmpty()) {
    int begin = -1, end = -1, pos = -1;
    QCString translated_name(name);
    QCString charset, encoding;
    QCString token;
    bool sem(true);

    while (sem) {
      begin = translated_name.find("=?", 0);

      if (begin != -1)
        end = translated_name.find("?=", begin + 2);
      else
        end = -1;

      if (end != -1) {
        output += QString::fromAscii(translated_name.left(begin));
        token = translated_name.mid(begin + 2, end - begin - 2);

        pos = token.find('?');
        charset = token.left(pos);
        token.remove(0, pos + 1);

        pos = token.find('?');
        encoding = token.left(pos);
        token.remove(0, pos + 1);
        encoding = encoding.upper();

        if (encoding == "Q") {
          encoding = "quoted-printable";
        } else if (encoding == "B") {
          encoding = "base64";
        } else {
          encoding = "none";
        }
        token = decode(token, encoding);

        QTextCodec *codec = QTextCodec::codecForName(charset);
        if (codec) {
          output += codec->toUnicode(token);
        } else {
          if (charset.lower() == "utf-8") {
            output += QString::fromUtf8(token);
          } else if (charset.lower() == "us-ascii") {
            output += QString::fromAscii(token);
          }
          // just use something
          else {
            qDebug("Warning: could not find textcodec for %s.", (const char *)charset);
            output += QString::fromLatin1(token);
          }
        }

        translated_name = translated_name.mid(end + 2);
      } else {
        output += QString::fromAscii(translated_name);
        sem = false;
      }
    }
  }

  return output;
}
Ejemplo n.º 2
0
bool DocumentEditor::load(const QString &fileName_) {
	QFile file(fileName_);
	if (!file.open(QFile::ReadOnly)) {
		QMessageBox::warning(this, PACKAGE_NAME,
							 tr("Cannot read file %1:\n%2.")
							 .arg(fileName_)
							 .arg(file.errorString()));
		return false;
	}

	///@todo better charset detection
	char bom[6];
	file.read(bom, 6);
	file.reset();
	detectBOM(bom);

	QString shebang;
	for(uint8_t i = 0; i < 5; i++){
		if(bom[i] == '#'){
			if(bom[i+1] == '!'){
				char line[80];
				file.readLine(line, 80);
				file.reset();
				shebang = line;
			}
		}
	}

	QTextCodec* codec = QTextCodec::codecForName(_codec.toUtf8());
	if(codec == 0) {
		QMessageBox::critical(this, PACKAGE_NAME,
							  tr("Cannot load file %1:\nUnsupported charset %2 !!")
							  .arg(fileName_).arg(_codec));
		return false;
	}

	QApplication::setOverrideCursor(Qt::WaitCursor);

	QString data = codec->toUnicode(file.readAll());
	setText(data);

	_fullPath = fileName_;
	_isNew = false;
	setModified(false);

	if(_autoDetectEol)
		autoDetectEol();
	if(_autoDetectIndent)
		autoDetectIndent();

	//add lexer
	QsciLexer* l = lexer();
	//detach lexer from document before delete it
	setLexer(0);
	if(l != 0) {
		delete l;
		l = 0;
	}
	setLexer(LexerManager::getInstance().getAutoLexer(this, shebang));

	//reload settings for lexer
	Settings settings;
	settings.applyToDocument(this);

	//add it to the watcher
	_watcher.addPath(_fullPath);

	QApplication::restoreOverrideCursor();
	_notified = true;

	return true;
}
Ejemplo n.º 3
0
void Process::slotError(QProcess::ProcessError err){
	if (myProcess->exitCode()!=0){

		QTextStream stdErr(stderr);
		QString lang = this->getLocale();

		QTextCodec *codec = QTextCodec::codecForName(lang.toAscii());
		if (!codec){
			stdErr<<"[ee] Can't setup codec for \""<<lang<<"\""<<endl;
			stdErr<<"[ee] Aborting current operation!"<<endl;
			reject();
			return;
		}

		QString string = codec->toUnicode(myProcess->readAllStandardError());

		if (!string.isEmpty()){
			QMessageBox::warning(this, tr("Error"), tr("It seems procces fail.<br><br>Error log:<br>%1").arg(string));
		} else {
			switch (err){
			case 0:
				QMessageBox::warning(this, tr("Error"), tr("Process: The process failed to start. Either the invoked program is missing, or you may have insufficient permissions to invoke the program."));
				break;
			case 1:
				QMessageBox::warning(this, tr("Error"), tr("Process: The process crashed some time after starting successfully."));
				break;
			case 2:
				QMessageBox::warning(this, tr("Error"), tr("Process: The last waitFor...() function timed out."));
				break;
			case 3:
				QMessageBox::warning(this, tr("Error"), tr("Process: An error occurred when attempting to read from the process. For example, the process may not be running."));
				break;
			case 4:
				QMessageBox::warning(this, tr("Error"), tr("Process: An error occurred when attempting to write to the process. For example, the process may not be running, or it may have closed its input channel."));
				break;
			case 5:
				QMessageBox::warning(this, tr("Error"), tr("Process: An unknown error occurred. This is the default return value of error()."));
				break;
			}
            reject ();
		}
	} else {
		switch (err){
			case 0:
			QMessageBox::warning(this, tr("Error"), tr("Process: The process failed to start. Either the invoked program is missing, or you may have insufficient permissions to invoke the program."));
			break;
			case 1:
			QMessageBox::warning(this, tr("Error"), tr("Process: The process crashed some time after starting successfully."));
			break;
			case 2:
			QMessageBox::warning(this, tr("Error"), tr("Process: The last waitFor...() function timed out."));
			break;
			case 3:
			QMessageBox::warning(this, tr("Error"), tr("Process: An error occurred when attempting to read from the process. For example, the process may not be running."));
			break;
			case 4:
			QMessageBox::warning(this, tr("Error"), tr("Process: An error occurred when attempting to write to the process. For example, the process may not be running, or it may have closed its input channel."));
			break;
			case 5:
			QMessageBox::warning(this, tr("Error"), tr("Process: An unknown error occurred. This is the default return value of error()."));
			break;
		}
		reject ();
	}
	return;
}
Ejemplo n.º 4
0
void        DasmDlg::on_execaction_clicked()
{
    QTextCodec *codec = QTextCodec::codecForLocale();

    QString elffile     = m_ui.ElfName->text().trimmed() ;
    QString param       = m_ui.ActParam->text().trimmed ();
    enum EExcDasmMode actmod = EExcDasmAll;

    switch(m_ui.ActMode->currentIndex() ){
        case 0: actmod  = EExcDasmAll; break;
        case 1: actmod  = param.isEmpty() ? EExcDasmFuncList : EExcDasmFuncMatchList;
                break;
        case 2: actmod  = EExcDasmFuncMatch; break;
        case 3: actmod  = EExcDasmFunc;    break;
        case 4: actmod  = EExcDasmAddr;    break;
        default:    break;
    }

    if( elffile.isEmpty() ){
        QMessageBox::warning( 0 /* Core::ICore::instance()->mainWindow()  */,
                codec->toUnicode("无法执行操作"),
                codec->toUnicode("未指定elf文件名"));
        return ;
    }

    if( param.isEmpty() 
            && (actmod == EExcDasmFuncMatch 
                || actmod == EExcDasmFunc 
                || actmod == EExcDasmAddr ) ){
        QMessageBox::warning( 0 /* Core::ICore::instance()->mainWindow()  */,
                codec->toUnicode("无法执行操作"),
                actmod == EExcDasmAddr ? 
                codec->toUnicode("操作需要传入一个数字类型的参数")
                :codec->toUnicode("操作需要传入字符串参数"));
        return ;
    }

    QString tmp ;
    tmp = QDesktopServices::storageLocation(QDesktopServices::TempLocation)+ "/exc_dasm.txt";

    if( actmod  == EExcDasmAll ){
        QString name = QFileDialog::getSaveFileName(this,
                codec->toUnicode("全部反汇编需要的时间较长,你想把反汇编结果另存到文件吗?"), m_curpath, tr("txt Files (*.txt)"));
        if(!name.isEmpty()) {
            tmp = name;
        }
    }

    FILE    *fp = fopen(tmp.toLatin1().data(),"w+");
    if( !fp ){
        QMessageBox::warning  ( 0 /* Core::ICore::instance()->mainWindow()  */,
                codec->toUnicode("无法执行操作"),
                codec->toUnicode("创建输出文件失败"));
        return ;
    }

    int ret     = Exc_Dasm(fp,elffile.toLatin1().data(),
            actmod,param.toLatin1().data());

    QFile scriptFile;
    fseek(fp,0,SEEK_SET);
    scriptFile.open(fp,QIODevice::ReadOnly);   

    m_ui.textEdit->setPlainText(scriptFile.readAll());
    scriptFile.close();

    if( ret != 0 ){
        QString  err;
        err.sprintf("analyse error code:%d",ret);
        QMessageBox::warning( 0 /* Core::ICore::instance()->mainWindow()  */,
                exc_tr("dasm fail"),
                err);
    }
}
Ejemplo n.º 5
0
QString myDecoderFunc(const QByteArray &localFileName)
{
    QTextCodec* codec = QTextCodec::codecForName("UTF-8");
    return codec->toUnicode(localFileName);
}
Ejemplo n.º 6
0
int main(int argc, char *argv[])
{
	SetErrorMode(SEM_NOGPFAULTERRORBOX);
	SetUnhandledExceptionFilter(MyUnhandledExceptionFilter);
	SingleApplication a(argc, argv);
	
	if (a.isRunning()) {

		return 0;
	}
	
	char *pFile = NULL;
	QString strFile = "";
	if (argc >= 2)
	{
		pFile = argv[1];
		QTextCodec *textcode = QTextCodec::codecForName("GB18030");
		strFile = textcode->toUnicode(pFile);
	}
#ifndef QT_NO_DEBUG
	showMainDlgNoExcept(a, strFile);
	return 1;

/*	QString appDir = QApplication::applicationDirPath() + "/";
	if (argc <= 1 || strcmp(argv[1], "-s") != 0)
	{

		QProcess::startDetached(appDir + Verify::startExe());
		return 0;

	}*/
#else
#ifdef UKey
	showMainDlgNoExcept(a, strFile);
	return 0;
#else
	AuthorFile=QApplication::applicationDirPath() + "/AuthorFile";
	initDb();
	MD5 md5_toApply;//用于生成申请码

	unsigned char address[1024];

	memset(address, 0, 1024);
#ifndef DISKSN
	if (getLocalMac(address) > 0)
#else
	if (GetHardDriveSerialNumber((char*)address, 1024) > 0)
#endif
	{
		md5_toApply.update((const char *)address);//生成申请码
	}
	else
	{

	}

	if (!Dialog::hasKey())
	{
		Dialog w;
		w.show();
		a.exec();
		exit(0);
	}
	showMainDlgNoExcept(a, strFile);
#endif
#endif 
}
Ejemplo n.º 7
0
/** @brief Parse xml-data
 *----------------------------------------------------------------------------*/
void ParseObject::slotParse(const QByteArray &xmlData, const int &feedId,
                            const QDateTime &dtReply, const QString &codecName)
{
  if (mainApp->isSaveDataLastFeed()) {
    QFile file(mainApp->dataDir()  + "/lastfeed.dat");
    file.open(QIODevice::WriteOnly);
    file.write(xmlData);
    file.close();
  }

  qDebug() << "=================== parseXml:start ============================";

  db_.transaction();

  // extract feed id and duplicate news mode from feed table
  parseFeedId_ = feedId;
  QString feedUrl;
  duplicateNewsMode_ = false;
  QSqlQuery q(db_);
  q.setForwardOnly(true);
  q.exec(QString("SELECT duplicateNewsMode, xmlUrl FROM feeds WHERE id=='%1'").arg(parseFeedId_));
  if (q.first()) {
    duplicateNewsMode_ = q.value(0).toBool();
    feedUrl = q.value(1).toString();
  }

  // id not found (ex. feed deleted while updating)
  if (feedUrl.isEmpty()) {
    qWarning() << QString("Feed with id = '%1' not found").arg(parseFeedId_);
    emit signalFinishUpdate(parseFeedId_, false, 0, "0");
    db_.commit();
    return;
  }

  qDebug() << QString("Feed '%1' found with id = %2").arg(feedUrl).arg(parseFeedId_);

  // actually parsing
  feedChanged_ = false;

  bool codecOk = false;
  QString convertData(xmlData);
  QString feedType;
  QDomDocument doc;
  QString errorStr;
  int errorLine;
  int errorColumn;

  QRegExp rx("encoding=\"([^\"]+)",
             Qt::CaseInsensitive, QRegExp::RegExp2);
  int pos = rx.indexIn(xmlData);
  if (pos == -1) {
    rx.setPattern("encoding='([^']+)");
    pos = rx.indexIn(xmlData);
  }
  if (pos > -1) {
    QString codecNameT = rx.cap(1);
    qDebug() << "Codec name (1):" << codecNameT;
    QTextCodec *codec = QTextCodec::codecForName(codecNameT.toUtf8());
    if (codec) {
      convertData = codec->toUnicode(xmlData);
    } else {
      qWarning() << "Codec not found (1): " << codecNameT << feedUrl;
      if (codecNameT.contains("us-ascii", Qt::CaseInsensitive)) {
        QString str(xmlData);
        convertData = str.remove(rx.cap(0)+"\"");
      }
    }
  } else {
    if (!codecName.isEmpty()) {
      qDebug() << "Codec name (2):" << codecName;
      QTextCodec *codec = QTextCodec::codecForName(codecName.toUtf8());
      if (codec) {
        convertData = codec->toUnicode(xmlData);
        codecOk = true;
      } else {
        qWarning() << "Codec not found (2): " << codecName << feedUrl;
      }
    }
    if (!codecOk) {
      codecOk = false;
      QStringList codecNameList;
      codecNameList << "UTF-8" << "Windows-1251" << "KOI8-R" << "KOI8-U"
                    << "ISO 8859-5" << "IBM 866";
      foreach (QString codecNameT, codecNameList) {
        QTextCodec *codec = QTextCodec::codecForName(codecNameT.toUtf8());
        if (codec && codec->canEncode(xmlData)) {
          qDebug() << "Codec name (3):" << codecNameT;
          convertData = codec->toUnicode(xmlData);
          codecOk = true;
          break;
        }
      }
      if (!codecOk) {
        convertData = QString::fromLocal8Bit(xmlData);
      }
    }
Ejemplo n.º 8
0
int SyncEngine::treewalkFile( TREE_WALK_FILE *file, bool remote )
{
    if( ! file ) return -1;

    QTextCodec::ConverterState utf8State;
    QTextCodec *codec = QTextCodec::codecForName("UTF-8");
    Q_ASSERT(codec);
    QString fileUtf8 = codec->toUnicode(file->path, qstrlen(file->path), &utf8State);
    QString renameTarget;
    QString key = fileUtf8;

    auto instruction = file->instruction;
    if (utf8State.invalidChars > 0 || utf8State.remainingChars > 0) {
        qWarning() << "File ignored because of invalid utf-8 sequence: " << file->path;
        instruction = CSYNC_INSTRUCTION_IGNORE;
    } else {
        renameTarget = codec->toUnicode(file->rename_path, qstrlen(file->rename_path), &utf8State);
        if (utf8State.invalidChars > 0 || utf8State.remainingChars > 0) {
            qWarning() << "File ignored because of invalid utf-8 sequence in the rename_path: " << file->path << file->rename_path;
            instruction = CSYNC_INSTRUCTION_IGNORE;
        }
        if (instruction == CSYNC_INSTRUCTION_RENAME) {
            key = renameTarget;
        }
    }

    // Gets a default-contructed SyncFileItemPtr or the one from the first walk (=local walk)
    SyncFileItemPtr item = _syncItemMap.value(key);
    if (!item)
        item = SyncFileItemPtr(new SyncFileItem);

    if (item->_file.isEmpty() || instruction == CSYNC_INSTRUCTION_RENAME) {
        item->_file = fileUtf8;
    }
    item->_originalFile = item->_file;

    if (item->_instruction == CSYNC_INSTRUCTION_NONE
            || (item->_instruction == CSYNC_INSTRUCTION_IGNORE && instruction != CSYNC_INSTRUCTION_NONE)) {
        item->_instruction = instruction;
        item->_modtime = file->modtime;
    } else {
        if (instruction != CSYNC_INSTRUCTION_NONE) {
            qDebug() << "ERROR: Instruction" << item->_instruction << "vs" << instruction << "for" << fileUtf8;
            Q_ASSERT(!"Instructions are both unequal NONE");
            return -1;
        }
    }

    if (file->file_id && strlen(file->file_id) > 0) {
        item->_fileId = file->file_id;
    }
    if (file->directDownloadUrl) {
        item->_directDownloadUrl = QString::fromUtf8( file->directDownloadUrl );
    }
    if (file->directDownloadCookies) {
        item->_directDownloadCookies = QString::fromUtf8( file->directDownloadCookies );
    }
    if (file->remotePerm && file->remotePerm[0]) {
        item->_remotePerm = QByteArray(file->remotePerm);
    }

    item->_should_update_metadata = item->_should_update_metadata || file->should_update_metadata;

    /* The flag "serverHasIgnoredFiles" is true if item in question is a directory
     * that has children which are ignored in sync, either because the files are
     * matched by an ignore pattern, or because they are  hidden.
     *
     * Only the information about the server side ignored files is stored to the
     * database and thus written to the item here. For the local repository its
     * generated by the walk through the real file tree by discovery phase.
     *
     * It needs to go to the sync journal becasue the stat information about remote
     * files are often read from database rather than being pulled from remote.
     */
    if( remote ) {
        item->_serverHasIgnoredFiles    = (file->has_ignored_files > 0);
    }

    // record the seen files to be able to clean the journal later
    _seenFiles.insert(item->_file);
    if (!renameTarget.isEmpty()) {
        // Yes, this record both the rename renameTarget and the original so we keep both in case of a rename
        _seenFiles.insert(renameTarget);
    }

    if (remote && file->remotePerm && file->remotePerm[0]) {
        _remotePerms[item->_file] = file->remotePerm;
    }

    switch(file->error_status) {
    case CSYNC_STATUS_OK:
        break;
    case CSYNC_STATUS_INDIVIDUAL_IS_SYMLINK:
        item->_errorString = tr("Symbolic links are not supported in syncing.");
        break;
    case CSYNC_STATUS_INDIVIDUAL_IGNORE_LIST:
        item->_errorString = tr("File is listed on the ignore list.");
        break;
    case CSYNC_STATUS_INDIVIDUAL_IS_INVALID_CHARS:
        item->_errorString = tr("Filename contains invalid characters that can not be synced cross platform.");
        break;
    case CSYNC_STATUS_INDIVIDUAL_EXCLUDE_LONG_FILENAME:
        item->_errorString = tr("Filename is too long.");
        break;
    case CSYNC_STATUS_INDIVIDUAL_EXCLUDE_HIDDEN:
        item->_errorString = tr("File is ignored because it's hidden.");
        break;
    case CYSNC_STATUS_FILE_LOCKED_OR_OPEN:
        item->_errorString = QLatin1String("File locked"); // don't translate, internal use!
        break;
    case CSYNC_STATUS_INDIVIDUAL_STAT_FAILED:
        item->_errorString = tr("Stat failed.");
        break;
    case CSYNC_STATUS_SERVICE_UNAVAILABLE:
        item->_errorString = QLatin1String("Server temporarily unavailable.");
        break;
    case CSYNC_STATUS_STORAGE_UNAVAILABLE:
        item->_errorString = QLatin1String("Directory temporarily not available on server.");
        item->_status = SyncFileItem::SoftError;
        _temporarilyUnavailablePaths.insert(item->_file);
        break;
    case CSYNC_STATUS_PERMISSION_DENIED:
        item->_errorString = QLatin1String("Directory not accessible on client, permission denied.");
        item->_status = SyncFileItem::SoftError;
        break;
    default:
        Q_ASSERT("Non handled error-status");
        /* No error string */
    }

    if (item->_instruction == CSYNC_INSTRUCTION_IGNORE && (utf8State.invalidChars > 0 || utf8State.remainingChars > 0)) {
        item->_status = SyncFileItem::NormalError;
        //item->_instruction = CSYNC_INSTRUCTION_ERROR;
        item->_errorString = tr("Filename encoding is not valid");
    }

    item->_isDirectory = file->type == CSYNC_FTW_TYPE_DIR;

    // The etag is already set in the previous sync phases somewhere. Maybe we should remove it there
    // and do it here so we have a consistent state about which tree stores information from which source.
    item->_etag = file->etag;
    item->_size = file->size;

    if (!remote) {
        item->_inode = file->inode;
    }

    switch( file->type ) {
    case CSYNC_FTW_TYPE_DIR:
        item->_type = SyncFileItem::Directory;
        break;
    case CSYNC_FTW_TYPE_FILE:
        item->_type = SyncFileItem::File;
        break;
    case CSYNC_FTW_TYPE_SLINK:
        item->_type = SyncFileItem::SoftLink;
        break;
    default:
        item->_type = SyncFileItem::UnknownType;
    }

    SyncFileItem::Direction dir = SyncFileItem::None;

    int re = 0;
    switch(file->instruction) {
    case CSYNC_INSTRUCTION_NONE:
        if (remote && item->_should_update_metadata && !item->_isDirectory && item->_instruction == CSYNC_INSTRUCTION_NONE) {
            // Update the database now already:  New fileid or Etag or RemotePerm
            // Or for files that were detected as "resolved conflict".
            // They should have been a conflict because they both were new, or both
            // had their local mtime or remote etag modified, but the size and mtime
            // is the same on the server.  This typically happen when the database is removed.
            // Nothing will be done for those file, but we still need to update the database.

            // Even if the mtime is different on the server, we always want to keep the mtime from
            // the file system in the DB, this is to avoid spurious upload on the next sync
            item->_modtime = file->other.modtime;

            _journal->setFileRecord(SyncJournalFileRecord(*item, _localPath + item->_file));
            item->_should_update_metadata = false;
        }
        if (item->_isDirectory && file->should_update_metadata) {
            // Because we want still to update etags of directories
            dir = SyncFileItem::None;
        } else {
            // No need to do anything.
            if (file->other.instruction == CSYNC_INSTRUCTION_NONE) {
                _hasNoneFiles = true;
            }

            return re;
        }
        break;
    case CSYNC_INSTRUCTION_RENAME:
        dir = !remote ? SyncFileItem::Down : SyncFileItem::Up;
        item->_renameTarget = renameTarget;
        if (item->_isDirectory)
            _renamedFolders.insert(item->_file, item->_renameTarget);
        break;
    case CSYNC_INSTRUCTION_REMOVE:
        _hasRemoveFile = true;
        dir = !remote ? SyncFileItem::Down : SyncFileItem::Up;
        break;
    case CSYNC_INSTRUCTION_CONFLICT:
    case CSYNC_INSTRUCTION_IGNORE:
    case CSYNC_INSTRUCTION_ERROR:
        dir = SyncFileItem::None;
        break;
    case CSYNC_INSTRUCTION_EVAL:
    case CSYNC_INSTRUCTION_NEW:
    case CSYNC_INSTRUCTION_SYNC:
    case CSYNC_INSTRUCTION_STAT_ERROR:
    default:
        dir = remote ? SyncFileItem::Down : SyncFileItem::Up;
        if (!remote && file->instruction == CSYNC_INSTRUCTION_SYNC) {
            // An upload of an existing file means that the file was left unchanged on the server
            // This count as a NONE for detecting if all the file on the server were changed
            _hasNoneFiles = true;
        }
        break;
    }

    item->_direction = dir;
    if (instruction != CSYNC_INSTRUCTION_NONE) {
        // check for blacklisting of this item.
        // if the item is on blacklist, the instruction was set to ERROR
        checkErrorBlacklisting( *item );
    }

    _progressInfo->adjustTotalsForFile(*item);

    _needsUpdate = true;

    item->log._etag          = file->etag;
    item->log._fileId        = file->file_id;
    item->log._instruction   = file->instruction;
    item->log._modtime       = file->modtime;
    item->log._size          = file->size;

    item->log._other_etag        = file->other.etag;
    item->log._other_fileId      = file->other.file_id;
    item->log._other_instruction = file->other.instruction;
    item->log._other_modtime     = file->other.modtime;
    item->log._other_size        = file->other.size;

    _syncItemMap.insert(key, item);

    emit syncItemDiscovered(*item);
    return re;
}
Ejemplo n.º 9
0
TPage loadSNX(QString fname, int cpage) {
	TPage page;
	QFile file(fname);
	if (!file.open(QFile::ReadOnly)) return page;
	TLine line;
	line.type = TL_TEXT;
	QTextCodec* codec = QTextCodec::codecForName("Shift-JIS");

	int count = get4(file);
	int p1 = get4(file);
	int p2,p3;
	int len;

	long dataPos = count * 12 + 8;
	long curPos = 0;
//	long adr = 0;
	char buf[1024];
	char cbuf[1024];
	char* sptr;
	char* dptr;

//	if (dump) printf("; bytecode\n\n");

	while (count > 0) {
		p1 = get4(file);
		p2 = get4(file);
		p3 = get4(file);
		if ((p1 == 0x11) && (p2 == 0x02)) {
			curPos = file.pos();
			file.seek(dataPos + p3);
			len = get4(file);
			file.read(buf,len);
			file.seek(curPos);
			sptr = buf;
			dptr = buf;
			if (*sptr == 0x01) {
				sptr += 3;
			}
			while(1) {
				if ((*sptr > 0x00) && (*sptr < 0x04)) {
					sptr++;
				} else {
					*dptr = *sptr;
					if (*dptr == 0x00) break;
					dptr++;
					sptr++;
				}
			}
		}
		if (p1 == 0x0d) {
			if (p2 == 0x012) {
				sprintf(cbuf,"[ %s ]",buf);
				//fwrite(cbuf,strlen(cbuf),1,ofile);
				line.src.name.clear();
				line.src.text = codec->toUnicode(cbuf);
				page.text.append(line);
			} else if (p2 == 0x2c) {
				sprintf(cbuf,"%s\n",buf);
				//fwrite(cbuf,strlen(cbuf),1,ofile);
				line.src.name.clear();
				line.src.text = codec->toUnicode(buf);
				normLine(line);
				page.text.append(line);
			}
		}
//		if (dump) printf("\n");
		count--;
	}

	return page;
}
Ejemplo n.º 10
0
QVariant QXcbMime::mimeConvertToFormat(QXcbConnection *connection, xcb_atom_t a, const QByteArray &data, const QString &format,
                                       QVariant::Type requestedType, const QByteArray &encoding)
{
    QString atomName = mimeAtomToString(connection, a);
//    qDebug() << "mimeConvertDataToFormat" << format << atomName << data;

    if (!encoding.isEmpty()
        && atomName == format + QLatin1String(";charset=") + QString::fromLatin1(encoding)) {

#ifndef QT_NO_TEXTCODEC
        if (requestedType == QVariant::String) {
            QTextCodec *codec = QTextCodec::codecForName(encoding);
            if (codec)
                return codec->toUnicode(data);
        }
#endif

        return data;
    }

    // special cases for string types
    if (format == QLatin1String("text/plain")) {
        if (a == connection->atom(QXcbAtom::UTF8_STRING))
            return QString::fromUtf8(data);
        if (a == XCB_ATOM_STRING ||
            a == connection->atom(QXcbAtom::TEXT))
            return QString::fromLatin1(data);
    }

    // special case for uri types
    if (format == QLatin1String("text/uri-list")) {
        if (atomName == QLatin1String("text/x-moz-url")) {
            // we expect this as utf16 <url><space><title>
            // the first part is a url that should only contain ascci char
            // so it should be safe to check that the second char is 0
            // to verify that it is utf16
            if (data.size() > 1 && data.at(1) == 0)
                return QString::fromRawData((const QChar *)data.constData(),
                                data.size() / 2).split(QLatin1Char('\n')).first().toLatin1();
        }
    }

    if (atomName == format)
        return data;

#if 0 // ###
    // special case for images
    if (format == QLatin1String("image/ppm")) {
        if (a == XCB_ATOM_PIXMAP && data.size() == sizeof(Pixmap)) {
            Pixmap xpm = *((Pixmap*)data.data());
            if (!xpm)
                return QByteArray();
            Window root;
            int x;
            int y;
            uint width;
            uint height;
            uint border_width;
            uint depth;

            XGetGeometry(display, xpm, &root, &x, &y, &width, &height, &border_width, &depth);
            XImage *ximg = XGetImage(display,xpm,x,y,width,height,AllPlanes,depth==1 ? XYPixmap : ZPixmap);
            QImage qimg = QXlibStatic::qimageFromXImage(ximg);
            XDestroyImage(ximg);

            QImageWriter imageWriter;
            imageWriter.setFormat("PPMRAW");
            QBuffer buf;
            buf.open(QIODevice::WriteOnly);
            imageWriter.setDevice(&buf);
            imageWriter.write(qimg);
            return buf.buffer();
        }
    }
#endif
    return QVariant();
}
Ejemplo n.º 11
0
// 和甜椒的服务通讯
bool SubmitData::GetDriverInfoFromWeb(GetDriverParam param,DriverInfo &driver)
{
	QMap<QString,QString> sendData = param.toMap();

	CommSendData2Web(sendData,PackageService,GetDriver,true);

	QTextCodec *tc = QTextCodec::codecForName("UTF-8");
	QByteArray ba = http->readAll();
	QString str = tc->toUnicode(ba);

	if (http!=NULL)
		delete http;
	if (loop!=NULL)
		delete loop;
	QDomDocument document; 
	if (!document.setContent(str))
	{
		driver.Clear();
		return false;  
	}  
	QDomElement root = document.documentElement();  

	QString isSuccess=getXmlValue(root,"IsSuccess");
	if (isSuccess=="") 
	{
		driver.Clear();
		qDebug() << "network report infomation error\n\n";
		return false;
	}
	else if (isSuccess.toLower()=="false")
	{
		driver.Clear();
		driver.DriverId = -2;
		qDebug() << "backstage not set driver\n\n";
		return false;
	}
	QString deviceId=getXmlValue(root,"DeviceID");
	driver.DriverId=deviceId.toLongLong();
	driver.Url=getXmlValue(root,"Url");
	driver.MD5=getXmlValue(root,"MD5");
	QString tmpDeviceType=getXmlValue(root,"DeviceType");

	if (tmpDeviceType=="INI")
		driver.DrvierType=1;
	else
		driver.DrvierType=2;

	driver.DriverName=getXmlValue(root,"MachineName");
	driver.StartFile=getXmlValue(root,"StartFile");
	driver.Version=getXmlValue(root,"Version").toInt();
	QString s= getXmlValue(root, "IsDeviceCollect");
	driver.isDeviceCollect= s == "true" ? true : false;
	driver.deviceStatue = getXmlValue(root, "DeviceStatue").toInt();
	QString strType = getXmlValue(root, "DataType");
	bool deviceType = strType == "true" ? true : false;
	if (deviceType) 
	{
		qDebug() << "exact driver recognition\n\n";
	}
	else 
	{
		qDebug() << "general driver recognition\n\n";
	}
	driver.DataType = deviceType;

	return true;
}
Ejemplo n.º 12
0
void RTFGenParser::text(const QString &text)
{
    for (int i = 0; i < (int)(text.length()); i++){
        QChar c = text[i];
        // In Qt, unless you force the paragraph direction with (Left/Right)
        // Ctrl-Shift (also known as Key_Direction_L and Key_Direction_R),
        // the P tag won't have a DIR attribute at all. In such cases, unlike
        // HTML, Qt will render the paragraph LTR or RTL according to the
        // first strong character (as Unicode TR#9 defines). Thus, if the
        // direction isn't known yet, we check each character till we find
        // a strong one.
        if ((m_lastParagraphPos != 0) && (m_paragraphDir == DirUnknown))
        {
            switch(c.direction())
            {
            case QChar::DirL:
                res.insert(m_lastParagraphPos, "\\ltrpar");
                m_paragraphDir = DirLTR;
                break;
            case QChar::DirR:
                res.insert(m_lastParagraphPos, "\\rtlpar");
                m_paragraphDir = DirRTL;
                break;
            default: // to avoid warnings
                break;
            }
        }

        unsigned short u = c.unicode();
        if (c == '\r' || c == '\n')
            continue;
        if ((c == '{') || (c == '}') || (c == '\\')){
            char b[5];
            snprintf(b, sizeof(b), "\\\'%02x", u & 0xFF);
            res += b;
            m_bSpace = false;
            continue;
        }
        if (u < 0x80){
            if (m_bSpace)
                res += ' ';
            res += (char)u;
            m_bSpace = false;
            continue;
        }
        QString s;
        s += c;
        if (m_codec){
            string plain;
            plain = m_codec->fromUnicode(s);
            if ((plain.length() == 1) && (m_codec->toUnicode(plain.c_str()) == s)){
                char b[5];
                snprintf(b, sizeof(b), "\\\'%02x", plain[0] & 0xFF);
                res += b;
                m_bSpace = false;
                continue;
            }
        }
        res += "\\u";
        res += number(s[0].unicode());
        res += "?";
        m_bSpace = false;
    }
}
Ejemplo n.º 13
0
void QuaMainWindow::on_mIBFTreeView_selectionChanged_triggered(const QModelIndex & current, const QModelIndex & previous)
{
    if ( mQuaTextEdit->document()->isModified() )
    {
        mQuaTextEdit->IBFSaveToFile(mQuaTextEdit->windowFilePath());
    }

    if ( !mIBFFileSystemModel->fileInfo(current).isFile() )
    {
        const bool wasBlocked = mQuaTextEdit->blockSignals(true);

        mQuaTextEdit->clear();
        mQuaTextEdit->setEnabled(false);

        mQuaTextEdit->blockSignals(wasBlocked);

        return;
    }

    QString tFileName = mIBFFileSystemModel->fileInfo(current).absoluteFilePath();

    if ( tFileName.isEmpty() )
    {
        return;
    }

    if ( !QFile::exists(tFileName) )
    {
        return;
    }

    QFile tFile(tFileName);

    if ( !tFile.open(QFile::ReadOnly) )
    {
        return;
    }

    QByteArray tByteArray = tFile.readAll();
    QTextCodec * tTextCodec = Qt::codecForHtml(tByteArray);

    QString tString = tTextCodec->toUnicode(tByteArray);

    const bool wasBlocked = mQuaTextEdit->blockSignals(true);

    if ( Qt::mightBeRichText(tString) )
    {
        mQuaTextEdit->setHtml(tString);
    }
    else
    {
        tString = QString::fromLocal8Bit(tByteArray);
        mQuaTextEdit->setPlainText(tString);
    }

    mQuaTextEdit->blockSignals(wasBlocked);

    mQuaTextEdit->setWindowFilePath(tFileName);
    mQuaTextEdit->setEnabled(true);

}