Ejemplo n.º 1
0
QString generalFunctions::getOutputFromFileMimeCmd(QString file, QString mimeArg)
{
    try {
      QProcess *process = new QProcess();
      QStringList *args = new QStringList();
      args->append("--brief");
      args->append(mimeArg);
      args->append(file);
      process->start("file", *args);
      if(process->waitForStarted(2000))
      {
          process->closeWriteChannel();
          process->waitForFinished(2000);
          QByteArray qba = process->readAll();
          QTextCodec *codec = QTextCodec::codecForLocale();
          QTextDecoder *decoder = codec->makeDecoder();
          QString result = decoder->toUnicode(qba);

          delete args;
          delete decoder;
          delete process;

          result = result.trimmed();
          return result;
      } else
      {
          return "";
      }

    }
    catch (...) {
       return "";
    }
}
Ejemplo n.º 2
0
QString Encoder::decrypt(QString input) {

    input.remove(0,4); // Remove the n_n_ at the beginning, this is just used for recognizing types
    input.remove(input.length()-1,1); // Remove the _ at the end, this is also not part of the original string

#ifndef Q_OS_MAC
    QTextEncoder* encoder = QTextCodec::codecForName("Windows-1252")->makeEncoder(); //Encode in Windows-1252
    QTextDecoder* decoder = QTextCodec::codecForName("UTF-8")->makeDecoder();        //Decode as if it's UTF-8

    QByteArray outputData = encoder->fromUnicode(input);

    input = decoder->toUnicode(outputData,outputData.length());
#endif

    QString output;


    for(int i=input.length() -1; i>=0; i--) {
        output += (QChar)((input[i].unicode()-32)%255);
    }

    //qDebug() << output.mid(2,output.length());

    output.replace("Ý"," ");
    return output.mid(0,output.length());


}
//------------------------------------------------------------------------------
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    QCoreApplication::setOrganizationName(programName); //Avoid QSettings trouble in Vista x64
    QCoreApplication::addLibraryPath("plugins");

    ui->setupUi(this);

    timer = new QTimer(this);
    connect(timer, SIGNAL(timeout()), this, SLOT(timerProc()));

    programVersion = "0.2";
    programName = "PMP";
    formalProgramName = "Privacy Mask Program";

    setWindowTitle(tr(formalProgramName.toAscii()) + "(" + programName + ")");

    // Prepare help widget
    formHelp = new FormHelp(0, tr(formalProgramName.toAscii()) + "(" + programName + ")");

    pthread = new PThread();
    connect(pthread, SIGNAL(finished()), this, SLOT(pthreadDone()));

    QTextCodec *codec = QTextCodec::codecForName("Shift-JIS");
    QTextDecoder *decoder = codec->makeDecoder();

    QString iniFname = programName + ".ini";
    QSettings *ini_settings;
    ini_settings = new QSettings(iniFname, QSettings::IniFormat);

    // Get MeCab_HOME
    meCabHome = decoder->toUnicode(ini_settings->value("MeCab/MeCab_HOME").toByteArray());
    if(meCabHome == ""){
        meCabHome = "c:/Program Files (x86)/MeCab/bin/";
    }

    // Get Mask Column No
    maskColumnNo = ini_settings->value("Target/MaskColumnNo").toString();
    if(maskColumnNo == ""){
        maskColumnNo = "";
    }

    // Get Process Execution Timeout (default 600sec)
    processExecutionTimeoutSeconds = ini_settings->value("Timeout/ProcessExecution").toString();
    if(processExecutionTimeoutSeconds == ""){
        processExecutionTimeoutSeconds = "600";
    }

    // Check the path to GnuPG
    if(! CheckMeCabHome(ini_settings)){
        timer->start(1000);
        return;
    }

    ui->listWidgetStatus->addItem(tr("Processing status."));
}
Ejemplo n.º 4
0
/**
  Reads the ini file and returns the dictionary name.
  */
MetaInfo BibleQuoteDict::readInfo(QFile &file)
{
    const QString encoding = m_settings->encoding;
    QTextCodec *codec = QTextCodec::codecForName(encoding.toStdString().c_str());
    QTextDecoder *decoder = codec->makeDecoder();
    QByteArray byteline = file.readLine();
    QString line = decoder->toUnicode(byteline);
    file.close();
    MetaInfo info;
    info.setName(line.simplified());
    return info;
}
Ejemplo n.º 5
0
bool ICQClient::translate(const char *to, const char *from, string &str)
{
    if (*str.c_str() == 0)
        return true;
    if (!strcasecmp(from, to))
        return true;
    QTextCodec *fromCodec = (*from) ? codecForName(from) : QTextCodec::codecForLocale();
    QTextCodec *toCodec = (*to) ? codecForName(to) : QTextCodec::codecForLocale();
    if ((fromCodec == NULL) && (toCodec == NULL) &&
            strcasecmp(from, "UCS-2") &&
            strcasecmp(from, "UTF-8") && strcasecmp(to, "UTF-8")){
        if ((*from && strcmp(from, "ascii")) || (*to && strcmp(to, "ascii")))
            log(L_WARN, "Codec for %s -> %s not found", from, to);
        return true;
    }
    QString s;
    if (fromCodec == NULL){
        if (strcasecmp(from, "utf-8") == 0){
            s = QString::fromUtf8(str.c_str());
        }else if (strcasecmp(from, "ucs-2") == 0){
            for (unsigned i = 0; i < str.length() / 2; i += 2)
                s += QChar(*((uint*)(str.c_str() + i)));
        }else{
            if (*from && strcmp(from, "ascii"))
                log(L_WARN, "Codec for %s not found", from);
            s = QString::fromLocal8Bit(str.c_str());
        }
    }else{
        QTextDecoder *decoder = fromCodec->makeDecoder();
        s = decoder->toUnicode(str.c_str(), strlen(str.c_str()));
    }
    if (s.length() == 0){
        s = "";
        return true;
    }
    if (toCodec == NULL){
        if (strcasecmp(to, "utf-8")){
            if (*to && strcmp(to, "ascii"))
                log(L_WARN, "Codec for %s not found", to);
            str = s.local8Bit();
        }else{
            str = s.utf8();
        }
    }else{
        QTextEncoder *encoder = toCodec->makeEncoder();
        int size = s.length();
        str = encoder->fromUnicode(s, size);
    }
    return true;
}
Ejemplo n.º 6
0
	bool tryExtractPart(QString *s)
	{
		int size = in.size() - at;
		if(size == 0)
			return false;
		uchar *p = (uchar *)in.data() + at;
		QString nextChars;
		while(1) {
			nextChars = dec->toUnicode((const char *)p, 1);
			++p;
			++at;
			if(!nextChars.isEmpty())
				break;
			if(at == (int)in.size())
				return false;
		}
		last_string += nextChars;
		*s = nextChars;

		// free processed data?
		if(at >= 1024) {
			char *p = in.data();
			int size = in.size() - at;
			memmove(p, p + at, size);
			in.resize(size);
			at = 0;
		}

		return true;
	}
void CWizDocumentStatusCheckThread::downloadData(const QString& strUrl)
{
    QNetworkAccessManager net;
    QNetworkReply* reply = net.get(QNetworkRequest(strUrl));

    QEventLoop loop;
    loop.connect(reply, SIGNAL(finished()), SLOT(quit()));
    loop.exec();

    if (reply->error()) {
        Q_EMIT checkFinished(QString(), QStringList());
        reply->deleteLater();
        return;
    }

    rapidjson::Document d;
    d.Parse<0>(reply->readAll().constData());
    if (d.IsArray())
    {
        QStringList strList;
        QTextCodec* codec = QTextCodec::codecForName("UTF-8");
        QTextDecoder* encoder = codec->makeDecoder();
        for (rapidjson::SizeType i = 0; i < d.Size(); i++)
        {
            const rapidjson::Value& u = d[i];
            strList.append(encoder->toUnicode(u.GetString(), u.GetStringLength()));
        }
        //
        {
            QMutexLocker lock(&m_mutexWait);
            if (strUrl.indexOf(m_strGUID) != -1)
            {
                emit checkFinished(m_strGUID, strList);
            }
            else
            {
                needRecheck();
            }
        }
        reply->deleteLater();
        return;
    }
    Q_EMIT checkFinished(QString(), QStringList());
    reply->deleteLater();
}
Ejemplo n.º 8
0
void WebView::applyEncoding()
{
	if (m_encoding_in_progress)
		return;

	if (webPage() && webPage()->mainWindow())
	{
		QString enc = webPage()->mainWindow()->m_currentEncoding;
		if (enc.isEmpty())
			return;

		if (enc == m_current_encoding && m_current_encoding_url == url() )
			return;

		QWebPage *page = webPage();
		if (!page)
			return;

		QWebFrame *mainframe = page->mainFrame();
		if (!mainframe)
			return;

		QString html = mainframe->toHtml();

		QTextCodec *codec = QTextCodec::codecForName( enc.toAscii() );
		if (!codec)
			return;

		QTextDecoder *decoder = codec->makeDecoder();
		if (!decoder)
			return;

		m_encoding_in_progress = true;
		m_current_encoding = enc;
		m_current_encoding_url = url();
		QString output = decoder->toUnicode(html.toAscii());
		mainframe->setHtml(output, mainframe->url());

		QList<QWebFrame *> children = mainframe->childFrames();
		foreach(QWebFrame *frame, children)
		{
			html = frame->toHtml();
			output = decoder->toUnicode(html.toAscii());
			frame->setHtml(output, frame->url());
		}
Ejemplo n.º 9
0
void widget::readSongList(QString fileName)
{
    QFile file(fileName);
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
    {
        qDebug()<<file.errorString();
        file.close();
        return;
    }


    QTextCodec *codec = QTextCodec::codecForName("GBK");
    QTextDecoder *decoder = codec->makeDecoder();

    while (!file.atEnd()) {
       QByteArray line = file.readLine();
       QString path;
       path += decoder->toUnicode(line);
//       QString path = file.readLine();
       if(!path.isEmpty()){
           path.remove("\n");
           qDebug()<<path;
       playList->addMedia(QUrl::fromLocalFile(path));

       QString fileName1 = path.split("\\").last();

       int rownum = this->ui->tableWidget->rowCount();
       this->ui->tableWidget->insertRow(rownum);

       int index = fileName1.lastIndexOf(".");
       QString str = fileName1.left(index);
       QString rowStr = QString::number(rownum+1,10);
       this->ui->tableWidget->setItem(rownum, 0, new QTableWidgetItem(rowStr));
       this->ui->tableWidget->setItem(rownum, 1, new QTableWidgetItem(str));
       this->ui->tableWidget->setItem(rownum, 2, new QTableWidgetItem(path));
       }
    }
 //   int currentIndex = playList->currentIndex();
 //   qDebug()<<currentIndex;

    file.close();
}
Ejemplo n.º 10
0
bool ICQClient::translate(const char *to, const char *from, string &str)
{
    if (*str.c_str() == 0)
        return true;
    if (!strcasecmp(from, to))
        return true;
    QTextCodec *fromCodec = codecForName(from);
    QTextCodec *toCodec = codecForName(to);
    if ((fromCodec == NULL) && (toCodec == NULL)){
        if ((*from && strcmp(from, "ascii")) || (*to && strcmp(to, "ascii")))
            log(L_WARN, "Codec for %s -> %s not found", from, to);
        return true;
    }
    QString s;
    if (fromCodec == NULL){
        if (*from && strcmp(from, "ascii"))
            log(L_WARN, "Codec for %s not found", from);
        s = QString::fromLocal8Bit(str.c_str());
    }else{
        QTextDecoder *decoder = fromCodec->makeDecoder();
        s = decoder->toUnicode(str.c_str(), strlen(str.c_str()));
    }
    if (s.length() == 0){
        s = "";
        return true;
    }
    if (toCodec == NULL){
        if (*to && strcmp(to, "ascii"))
            log(L_WARN, "Codec for %s not found", to);
        str = s.local8Bit();
    }else{
        QTextEncoder *encoder = toCodec->makeEncoder();
        int size = s.length();
        str = encoder->fromUnicode(s, size);
    }
    return true;
}
Ejemplo n.º 11
0
void widget::setCurrentLrc()//设置当前歌词显示
{
    int row = playList->currentIndex();

 //   QString fileName = "one.mp3";
//    QString fileName = mList->ui->tableWidget->item(row,1)->text();
    QString fileName = ui->tableWidget->item(row,2)->text();
    QString lrcName = fileName.remove(fileName.right(3)) + "lrc";
    qDebug()<<lrcName;
    QFile file(lrcName);
    if(!file.open(QIODevice::ReadOnly | QIODevice::Text))
    {
        ui->label_lrc->setText(tr("当前目录下未找到歌词文件"));
        lrc->setText(tr("当前目录下未找到歌词文件"));
        qDebug()<<"读文件出错";
      //  file.close();
     //   return;
    }
    QTextCodec *codec = QTextCodec::codecForName("GBK");
    QTextDecoder *decoder = codec->makeDecoder();
  //  QTextStream in(&file);
  //  ui->textEdit->setText(in.readAll());
    QString strLrc;
    while(!file.atEnd()){
        QByteArray line = file.readLine();
        QString path;

        path += decoder->toUnicode(line);
        //path.remove("\n");
        strLrc += path;
    }
  //  qDebug()<<strLrc;
    ui->textEdit->setText(strLrc);
    qDebug()<<ui->textEdit->textCursor().block().text();
    file.close();
}
Ejemplo n.º 12
0
bool TextSubtitleParser::LoadSubtitles(const QString &fileName,
                                       TextSubtitles &target)
{
    demux_sputext_t sub_data;
    RemoteFile rfile(fileName, false, false, 0);

    LOG(VB_VBI, LOG_INFO,
        QString("Preparing to load subtitle file (%1)").arg(fileName));
    if (!rfile.Open())
    {
        LOG(VB_VBI, LOG_INFO,
            QString("Failed to load subtitle file (%1)").arg(fileName));
        return false;
    }
    target.SetHasSubtitles(true);
    target.SetFilename(fileName);

    // Only reload if rfile.GetRealFileSize() has changed.
    off_t new_len = rfile.GetFileSize();
    if (target.GetByteCount() == new_len)
    {
        LOG(VB_VBI, LOG_INFO,
            QString("Filesize unchanged (%1), not reloading subs (%2)")
            .arg(new_len).arg(fileName));
        target.SetLastLoaded();
        return new_len;
    }
    LOG(VB_VBI, LOG_INFO,
        QString("Preparing to read %1 subtitle bytes from %2")
        .arg(new_len).arg(fileName));
    target.SetByteCount(new_len);
    sub_data.rbuffer_len = new_len;
    sub_data.rbuffer_text = new char[sub_data.rbuffer_len + 1];
    sub_data.rbuffer_cur = 0;
    sub_data.errs = 0;
    int numread = rfile.Read(sub_data.rbuffer_text, sub_data.rbuffer_len);
    LOG(VB_VBI, LOG_INFO,
        QString("Finished reading %1 subtitle bytes (requested %2)")
        .arg(numread).arg(new_len));
    subtitle_t *loaded_subs = sub_read_file(&sub_data);
    if (!loaded_subs)
    {
        delete sub_data.rbuffer_text;
        return false;
    }

    target.SetFrameBasedTiming(!sub_data.uses_time);
    target.Clear();

    QTextCodec *textCodec = NULL;
    QString codec = gCoreContext->GetSetting("SubtitleCodec", "");
    if (!codec.isEmpty())
        textCodec = QTextCodec::codecForName(codec.toLatin1());
    if (!textCodec)
        textCodec = QTextCodec::codecForName("utf-8");
    if (!textCodec)
    {
        delete sub_data.rbuffer_text;
        return false;
    }

    QTextDecoder *dec = textCodec->makeDecoder();

    // convert the subtitles to our own format and free the original structures
    for (int sub_i = 0; sub_i < sub_data.num; ++sub_i)
    {
        const subtitle_t *sub = &loaded_subs[sub_i];
        text_subtitle_t newsub(sub->start, sub->end);

        if (!target.IsFrameBasedTiming())
        {
            newsub.start *= 10; // convert from csec to msec
            newsub.end *= 10;
        }

        for (int line = 0; line < sub->lines; ++line)
        {
            const char *subLine = sub->text[line];
            QString str = dec->toUnicode(subLine, strlen(subLine));
            newsub.textLines.push_back(str);

            free(sub->text[line]);
        }
        target.AddSubtitle(newsub);
    }

    delete dec;
    // textCodec object is managed by Qt, do not delete...

    free(loaded_subs);
    delete sub_data.rbuffer_text;

    target.SetLastLoaded();

    return true;
}
Ejemplo n.º 13
0
static void generate_qpath( mlt_properties producer_properties )
{
	QPainterPath* qPath = static_cast<QPainterPath*>( mlt_properties_get_data( producer_properties, "_qpath", NULL ) );
	int outline = mlt_properties_get_int( producer_properties, "outline" );
	char* align = mlt_properties_get( producer_properties, "align" );
	char* style = mlt_properties_get( producer_properties, "style" );
	char* text = mlt_properties_get( producer_properties, "text" );
	char* encoding = mlt_properties_get( producer_properties, "encoding" );
	int pad = mlt_properties_get_int( producer_properties, "pad" );
	int offset = pad + ( outline / 2 );
	int width = 0;
	int height = 0;

	// Make the path empty
	*qPath = QPainterPath();

	// Get the strings to display
	QTextCodec *codec = QTextCodec::codecForName( encoding );
	QTextDecoder *decoder = codec->makeDecoder();
	QString s = decoder->toUnicode( text );
	delete decoder;
	QStringList lines = s.split( "\n" );

	// Configure the font
	QFont font;
	font.setPixelSize( mlt_properties_get_int( producer_properties, "size" ) );
	font.setFamily( mlt_properties_get( producer_properties, "family" ) );
	font.setWeight( ( mlt_properties_get_int( producer_properties, "weight" ) / 10 ) -1 );
	switch( style[0] )
	{
	case 'i':
	case 'I':
		font.setStyle( QFont::StyleItalic );
		break;
	}
	QFontMetrics fm( font );

	// Determine the text rectangle size
	height = fm.lineSpacing() * lines.size();
	for( int i = 0; i < lines.size(); ++i )
	{
		int line_width = fm.width( lines.at(i) );
		if( line_width > width ) width = line_width;
	}

	// Lay out the text in the path
	int x = 0;
	int y = fm.ascent() + 1 + offset;
	for( int i = 0; i < lines.size(); ++i )
	{
		QString line = lines.at(i);
		x = offset;
		switch( align[0] )
		{
			default:
			case 'l':
			case 'L':
				break;
			case 'c':
			case 'C':
				x += ( width - fm.width( line ) ) / 2;
				break;
			case 'r':
			case 'R':
				x += width - fm.width( line );
				break;
		}
		qPath->addText( x, y, font, line );
		y += fm.lineSpacing();
	}

	// Account for outline and pad
	width += offset * 2;
	height += offset * 2;
	// Sanity check
	if( width == 0 ) width = 1;
	if( height == 0 ) height = 1;
	mlt_properties_set_int( producer_properties, "meta.media.width", width );
	mlt_properties_set_int( producer_properties, "meta.media.height", height );
}
//------------------------------------------------------------------------------
bool MainWindow::editOutputFile(QString inputPath, QString meCabOutputPath, QString outputPath, QString maskColumnNo)
{
    bool stat = true;
    QString errmsg = "";
    int col = 0;
    QTextCodec *codec = QTextCodec::codecForName("Shift-JIS");
    QTextDecoder *decoder = codec->makeDecoder();
    QTextEncoder *encoder = codec->makeEncoder();
    
    QFile wfile(outputPath);
    QFile rfileMeCab(meCabOutputPath);
    QFile rfile(inputPath);
    if (wfile.open(QIODevice::WriteOnly | QIODevice::Text)){
        if (rfileMeCab.open(QIODevice::ReadOnly | QIODevice::Text)){
            if(maskColumnNo != ""){
                if (rfile.open(QIODevice::ReadOnly | QIODevice::Text)){
                    bool ok;
                    col = maskColumnNo.toInt(&ok, 10);
                    if(! ok){
                        errmsg = tr("Illegal Mask Column No.") + "(" + maskColumnNo + ")";
                        rfile.close();
                        stat = false;
                    }
                }
                else{
                    // Can't open input file.
                    errmsg = tr("Can't open the intput file.") + "(" + inputPath + ")";
                    stat = false;
                }
            }
            
            if(stat){
                QString outline = "";
                while (!rfileMeCab.atEnd()) {
                    QByteArray line = rfileMeCab.readLine();
                    //QString str = decoder->toUnicode(line);
                    QString str = line;
                    if(str == "EOS\n"){
                        if(maskColumnNo != ""){
                            QByteArray wline = rfile.readLine();
                            str = wline;
                            QStringList wlist = str.split("\t", QString::KeepEmptyParts, Qt::CaseSensitive);
                            str = outline;
                            outline = "";
                            for(int ii = 0; ii < wlist.count(); ii++){
                                if(outline != ""){
                                    outline += "\t";
                                }
                                if(ii == col){
                                    outline += str;
                                }
                                else{
                                    outline += wlist[ii];
                                }
                            }
                        }
                        wfile.write((outline + "\n").toAscii());
                        outline = "";
                    }
                    else{
                        QStringList wlist = str.split("\t", QString::KeepEmptyParts, Qt::CaseSensitive);
                        if(wlist[1].left(13) == "����,�ŗL����"){
                            QString unicodeStr = decoder->toUnicode(wlist[0].toAscii());
                            QString maskStr = unicodeStr.replace(QRegExp("."), decoder->toUnicode("��"));
                            outline += encoder->fromUnicode(maskStr);
                        }
                        else{
                            outline += wlist[0];
                        }
                    }
                }
                rfileMeCab.close();
                if(maskColumnNo != ""){
                    rfile.close();
                }
            }
        }
        else{
            // Can't open MeCab output file.
            errmsg = tr("Can't open the MeCab output file.") + "(" + meCabOutputPath + ")";
            stat = false;
        }
        
        wfile.close();
    }
    else{
        // Can't open the output file.
        errmsg = tr("Can't open the output file.") + "(" + outputPath + ")";
        stat = false;
    }
    
    if(! stat){
        QMessageBox::StandardButton reply;
        reply = QMessageBox::critical(this, tr("ERROR"),
            errmsg,
            QMessageBox::Abort);
        if (reply == QMessageBox::Abort){
            close();
        }
    }
    
    return stat;
}
Ejemplo n.º 15
0
//------------------------------------------------------------------------------
MetaInfo BibleQuoteModule::readInfo(QFile &file)
{
    bool useShortName = false;
    m_moduleName.clear();
    m_moduleShortName.clear();
    int countlines = 0;

    QString encoding = getEncodingFromFile(file.fileName());
    m_codec = QTextCodec::codecForName(encoding.toStdString().c_str());

    QTextDecoder *decoder = m_codec->makeDecoder();
    while(!file.atEnd())
    {
        /*if (countlines > 50) { //wenn eine ini datei ungueltig ist soll damit nicht zuviel zeit verguedet werden
            break;
        }*/
        QByteArray byteline = file.readLine();
        QString line = decoder->toUnicode(byteline);
        if(!line.startsWith("//"))
        {
            countlines++;
        }
        else
        {
            continue;
        }

        if(line.contains("BibleName", Qt::CaseInsensitive) and m_moduleName.isEmpty())
        {
            m_moduleName = formatFromIni(line.
                                         remove(QRegExp("BibleName(\\s*)=(\\s*)",
                                                        Qt::CaseInsensitive)));
            if(m_moduleName.isEmpty())
            {
                useShortName = true;
            }
            if(useShortName && !m_moduleShortName.isEmpty())
            {
                break;
            }
            /// what is ?
            //            else if(!useShortName)
            //            {
            //                break;
            //            }
        }
        if(line.contains("BibleShortName", Qt::CaseInsensitive) and m_moduleShortName.isEmpty())
        {
            m_moduleShortName = formatFromIni(line.
                                              remove(QRegExp("BibleShortName(\\s*)=(\\s*)",
                                                             Qt::CaseInsensitive)));
            if(useShortName)
                break;
        }
    }
    file.close();
    if(useShortName)
    {
        m_moduleName = m_moduleShortName;
    }
    if(m_moduleName.isEmpty())
    {
        myWarning() << "invalid ini File " << file.fileName();
    }

    MetaInfo ret;
    ret.setName(m_moduleName);
    ret.setShortName(m_moduleShortName);

    if (m_typeModule == "Apocrypha")
        ret.type = OBVCore::Type_BibleQuoteApocrypha;

    if (m_typeModule == "Comments")
        ret.type = OBVCore::Type_BibleQuoteComments;

    if (m_typeModule == "Bible")
        ret.type = OBVCore::Type_BibleQuoteModule;

    if (m_typeModule == "Book")
        ret.type = OBVCore::Type_BibleQuoteBook;

    return ret;
    return MetaInfo();
}
Ejemplo n.º 16
0
void TextView::updateText(quintptr source)
{
    if (source == reinterpret_cast<quintptr>(this))
        return;

    QByteArray rawdata = byteSource->getRawData();
#ifdef SCINTILLA
    scintEditor->blockSignals(true);
    if (rawdata.size() > 0) {
        if (currentCodec != nullptr) { //safeguard
            QTextDecoder *decoder = currentCodec->makeDecoder(QTextCodec::ConvertInvalidToNull); // when decoding take possible BOM headers into account
            QString textf = decoder->toUnicode(rawdata.constData(),rawdata.size());
            if (decoder->hasFailure()) {
                if (errorNotReported) {
                    logger->logWarning(tr("invalid text decoding [%1]").arg(QString::fromUtf8(currentCodec->name())),LOGID);
                    ui->codecsComboBox->setStyleSheet(GuiStyles::ComboBoxError);
                    errorNotReported = false;
                }
            } else {
                ui->codecsComboBox->setStyleSheet("");
                errorNotReported = true;
            }
            delete decoder;
            scintEditor->setText(textf);
            updateStats();
            scintEditor->setCursorPosition(0,0);
            scintEditor->ensureCursorVisible();
        } else {
            qCritical() << tr("%1:updatedText() currentCodec is nullptr T_T").arg(metaObject()->className());
        }

        if (autoCopyToClipboard)
            copyToClipboard();
    } else {
        scintEditor->setText(QString());
        updateStats();
    }

    scintEditor->blockSignals(false);
#else
    plainTextEdit->blockSignals(true);
    plainTextEdit->clear();
    if (rawdata.size() > MAX_TEXT_VIEW) {
        plainTextEdit->appendPlainText("Data Too large for this view");
        plainTextEdit->blockSignals(false);
        plainTextEdit->setEnabled(false);
        ui->statsLabel->setText(QString(""));
        ui->codecsComboBox->setStyleSheet("");
        emit invalidText();
    } else {
        if (rawdata.size() > 0) {
            if (currentCodec != nullptr) { //safeguard
                QTextDecoder *decoder = currentCodec->makeDecoder(QTextCodec::ConvertInvalidToNull); // when decoding take possible BOM headers into account
                QString textf = decoder->toUnicode(rawdata.constData(),rawdata.size());
                if (decoder->hasFailure()) {
                    if (errorNotReported) {
                        logger->logWarning(tr("invalid text decoding [%1]").arg(QString::fromUtf8(currentCodec->name())),LOGID);
                        ui->codecsComboBox->setStyleSheet(GuiStyles::ComboBoxError);
                        errorNotReported = false;
                    }
                } else {
                    ui->codecsComboBox->setStyleSheet("");
                    errorNotReported = true;
                }
                delete decoder;
                plainTextEdit->appendPlainText(textf);
                updateStats();
                plainTextEdit->moveCursor(QTextCursor::Start);
                plainTextEdit->ensureCursorVisible();
                plainTextEdit->setEnabled(true);
            } else {
                qCritical() << tr("%1:updatedText() currentCodec is nullptr T_T").arg(metaObject()->className());
            }
        } else {
            plainTextEdit->setEnabled(true);
        }
        if (autoCopyToClipboard)
            copyToClipboard();
    }
    plainTextEdit->blockSignals(false);
#endif
}
Ejemplo n.º 17
0
bool BaseTextDocument::open(const QString &fileName)
{
    QString title = tr("untitled");
    if (!fileName.isEmpty()) {
        const QFileInfo fi(fileName);
        m_fileName = fi.absoluteFilePath();

        QFile file(fileName);
        if (!file.exists())
            return false;

        if (!fi.isReadable())
            return false;

        if (!fi.isWritable()) {
            if (!file.open(QIODevice::ReadOnly))
                return false;
        } else {
            if (!file.open(QIODevice::ReadWrite))
                return false;
        }
        title = fi.fileName();

        QByteArray buf = file.readAll();
        int bytesRead = buf.size();

        QTextCodec *codec = m_codec;

        // code taken from qtextstream
        if (bytesRead >= 4 && ((uchar(buf[0]) == 0xff && uchar(buf[1]) == 0xfe && uchar(buf[2]) == 0 && uchar(buf[3]) == 0)
                               || (uchar(buf[0]) == 0 && uchar(buf[1]) == 0 && uchar(buf[2]) == 0xfe && uchar(buf[3]) == 0xff))) {
            codec = QTextCodec::codecForName("UTF-32");
        } else if (bytesRead >= 2 && ((uchar(buf[0]) == 0xff && uchar(buf[1]) == 0xfe)
                                      || (uchar(buf[0]) == 0xfe && uchar(buf[1]) == 0xff))) {
            codec = QTextCodec::codecForName("UTF-16");
        } else if (!codec) {
            codec = QTextCodec::codecForLocale();
        }
        // end code taken from qtextstream

        m_codec = codec;

#if 0 // should work, but does not, Qt bug with "system" codec
        QTextDecoder *decoder = m_codec->makeDecoder();
        QString text = decoder->toUnicode(buf);
        m_hasDecodingError = (decoder->hasFailure());
        delete decoder;
#else
        QString text = m_codec->toUnicode(buf);
        QByteArray verifyBuf = m_codec->fromUnicode(text); // slow
        // the minSize trick lets us ignore unicode headers
        int minSize = qMin(verifyBuf.size(), buf.size());
        m_hasDecodingError = (minSize < buf.size()- 4
                              || memcmp(verifyBuf.constData() + verifyBuf.size() - minSize,
                                        buf.constData() + buf.size() - minSize, minSize));
#endif

        if (m_hasDecodingError) {
            int p = buf.indexOf('\n', 16384);
            if (p < 0)
                m_decodingErrorSample = buf;
            else
                m_decodingErrorSample = buf.left(p);
        } else {
            m_decodingErrorSample.clear();
        }

        int lf = text.indexOf('\n');
        if (lf > 0 && text.at(lf-1) == QLatin1Char('\r')) {
            m_lineTerminatorMode = CRLFLineTerminator;
        } else if (lf >= 0) {
            m_lineTerminatorMode = LFLineTerminator;
        } else {
            m_lineTerminatorMode = NativeLineTerminator;
        }

        m_document->setModified(false);
        m_document->setUndoRedoEnabled(false);
        if (m_isBinaryData)
            m_document->setHtml(tr("<em>Binary data</em>"));
        else
            m_document->setPlainText(text);
        m_document->setUndoRedoEnabled(true);
        TextEditDocumentLayout *documentLayout = qobject_cast<TextEditDocumentLayout*>(m_document->documentLayout());
        QTC_ASSERT(documentLayout, return true);
        documentLayout->lastSaveRevision = 0;
        m_document->setModified(false);
        emit titleChanged(title);
        emit changed();
    }
    return true;
}
Ejemplo n.º 18
0
void DataFilesModel::addFiles(const QString &path)
{
    QDir dir(path);
    QStringList filters;
    filters << "*.esp" << "*.esm";
    dir.setNameFilters(filters);

    // Create a decoder for non-latin characters in esx metadata
    QTextCodec *codec;

    if (mEncoding == QLatin1String("win1252")) {
        codec = QTextCodec::codecForName("windows-1252");
    } else if (mEncoding == QLatin1String("win1251")) {
        codec = QTextCodec::codecForName("windows-1251");
    } else if (mEncoding == QLatin1String("win1250")) {
        codec = QTextCodec::codecForName("windows-1250");
    } else {
        return; // This should never happen;
    }

    QTextDecoder *decoder = codec->makeDecoder();

    foreach (const QString &path, dir.entryList()) {
        QFileInfo info(dir.absoluteFilePath(path));
        EsmFile *file = new EsmFile(path);

        try {
            ESM::ESMReader fileReader;
            ToUTF8::Utf8Encoder encoder(ToUTF8::calculateEncoding(mEncoding.toStdString()));
            fileReader.setEncoder(&encoder);
            fileReader.open(dir.absoluteFilePath(path).toStdString());

            std::vector<ESM::Header::MasterData> mlist = fileReader.getMasters();

            QStringList masters;

            for (unsigned int i = 0; i < mlist.size(); ++i) {
                QString master = QString::fromStdString(mlist[i].name);
                masters.append(master);
            }

            file->setAuthor(decoder->toUnicode(fileReader.getAuthor().c_str()));
            file->setSize(info.size());
            file->setDates(info.lastModified(), info.lastRead());
            file->setVersion(fileReader.getFVer());
            file->setPath(info.absoluteFilePath());
            file->setMasters(masters);
            file->setDescription(decoder->toUnicode(fileReader.getDesc().c_str()));


            // Put the file in the table
            if (findItem(path) == 0)
                addFile(file);
        } catch(std::runtime_error &e) {
            // An error occurred while reading the .esp
            qWarning() << "Error reading esp: " << e.what();
            continue;
        }

    }

    delete decoder;
}
Ejemplo n.º 19
0
bool CGpgExec::gpgExecute(QString request, QString param1, QString param2, QString *result)
{
    QTextCodec *codec = QTextCodec::codecForName("Shift-JIS");
    QTextDecoder *decoder = codec->makeDecoder();

    QString cmdPath = pathToGnuPG;
    QProcess coprocess;
    QString filePath;
    QString keyid;
    bool stat = false;

    coprocess.setProcessChannelMode(QProcess::MergedChannels);

    if(request == "check"){
        filePath = param1;
        coprocess.start(cmdPath, QStringList() << "-n" << "--verbose" << "--import" << filePath);
        //coprocess.start(cmdPath, QStringList() << "--batch" << "--interactive" << "--import" << filePath);
    }
    else if(request == "import"){
        filePath = param1;
        coprocess.start(cmdPath, QStringList() << "--verbose" << "--import" << filePath);
    }
    else if(request == "fingerprint"){
        keyid = param1;
        coprocess.start(cmdPath, QStringList() << "--fingerprint" << keyid);
    }
    else if(request == "list-sigs"){
        keyid = param1;
        coprocess.start(cmdPath, QStringList() << "--list-sigs" << keyid);
    }
    else if(request == "delete-keys"){
        keyid = param1;
        coprocess.start(cmdPath, QStringList() << "--batch" << "--yes" << "--delete-keys" << keyid);
    }
//    else if(request == "encrypt"){
//        keyid = param1;
//        filePath = param2;
//        QProcess coprocess1;
//        coprocess1.setStandardOutputProcess(&coprocess);
//        coprocess1.start("cmd.exe", QStringList() << "/c" << "echo" << "y");
//        coprocess.start(cmdPath, QStringList() << "--command-fd" << "0" << "--encrypt" << "--recipient" << keyid << filePath);
//    }

    if (coprocess.waitForStarted()){
        int timeoutSec = 60;
        if(! processExecutionTimeoutSeconds.isEmpty()){
            bool ok;
            timeoutSec = processExecutionTimeoutSeconds.toInt(&ok, 10);
            if(timeoutSec == 0){
                timeoutSec = 60;
            }
        }
        if (!coprocess.waitForFinished(timeoutSec * 1000)){
            QMessageBox::information(this, tr("Confirm"), decoder->toUnicode(coprocess.readAll()));
        }
        else{
            *result = QString(coprocess.readAll());
//            if(request == "encrypt"){
//                if(result->isEmpty()
//                        || result->mid(15, 56) == "There is no assurance this key belongs to the named user"
//                        || result->mid(15, 56) == "この鍵が本当に本人のものである、という兆候が、ありません"
//                        ){
//                    sleepCount = timeoutSec;
//                    waitingFilePath = filePath + ".gpg";
//                    timer->start(1000);
//                    stat = true;
//               }
//                else{
//                    stat = false;
//                }
//            }
//            else{
                stat = true;
//            }
        }
    }
    else{
        QString errmsg = coprocess.errorString();
        QMessageBox::StandardButton reply;
        reply = QMessageBox::critical(this, tr("Error"),
                                        tr("Can't start GNU PG."),
                                        QMessageBox::Abort);
        if (reply == QMessageBox::Abort){
            close();
        }
    }
    return stat;
}
Ejemplo n.º 20
0
void TEWidget::inputMethodEvent( QInputMethodEvent * e)  // is a virtual function
{
  static int c=0;
  qDebug("in TEWidget::inputMethodEvent : %d", c++);
  static QString preedit_string;
  preedit_string=e->preeditString();
  if (!e->commitString().isEmpty())
  {
    qDebug("!e->commitString() : %d", e->commitString().length() );
    static QString commit_string;
    commit_string=e->commitString();
    const char *ch=commit_string.toStdString().c_str();
    for (int i=0 ; i < commit_string.toStdString().length() ; ++i)
      qDebug("ch[i] : %x", ch[i]);
    //input_text_->setText(preedit_string+"*"+commit_string);
    input_text_->clear();
    //input_text_->setText("test"+commit_string);
    //input_text_->set_text("commit"+e->commitString() );
    //input_text_->show();
    //onRcvBlock();


    // QKeyEvent ( Type type, int key, Qt::KeyboardModifiers modifiers, const QString & text = QString(), bool autorep = false, ushort count = 1 )
#if 0
    int encode=get_encoding();
    QTextDecoder* decoder;
    QTextCodec *codec;
    QByteArray qba;
    const QChar * qchar;



    if ( get_input_encoding() == DS::BIG5)
    {
      codec = QTextCodec::codecForName("BIG5");
      //qDebug("(encoding==DS::BIG5)");
      //qDebug("(encoding==DS::UTF8)");
      qDebug("in encode==DS::BIG5");

    }
    if ( get_input_encoding() == DS::UTF8)
    {
      codec = QTextCodec::codecForName("UTF-8");
      //qchar= e->commitString().unicode();
      //codec = QTextCodec::codecForName("UTF-8");
      //qDebug("in encode==DS::UTF8");
      //qba=e->commitString().toUtf8();
    }



    QByteArray ba = codec->fromUnicode(ev->text());
    char *ba_data=ba.data();
    emit sndBlock(ba_data ,strlen(ba_data));    


    //for (int i=0 ; i < e->commitString().length() ; ++i)
      //qDebug("qchar[i] : %x", qchar[i].unicode () );
      //qDebug("qchar[i] : %x", i);
    decoder = codec->makeDecoder();
    const char *c_str= e->commitString().toStdString().c_str();
      qDebug("c_str len: %d", strlen(c_str));

    for (int i=0 ; i < strlen(c_str) ; ++i)
      qDebug("c_str[i]: %x", c_str[i]);

    commit_string=decoder->toUnicode(c_str, strlen(c_str));
#endif
    //QString str(qba);

    QKeyEvent* ke = new QKeyEvent(QEvent::KeyPress, 0, Qt::NoModifier, commit_string);

    //actSel=0; // Key stroke implies a screen update, so TEWidget won't
              // know where the current selection is.

    emit keyPressedSignal(ke); // expose
    //preedit_string="";
    //commit_string="";
    //sleep(3);
  }
  else
  {
    qDebug("e->commitString()");
    #if 0
    if (!preedit_string.isEmpty())
    {
    input_text_->set_text("preedit"+preedit_string);
    input_text_->show();
    }
    #endif
  }
#if 0
  if (!preedit_string.isEmpty())
  {
    input_text_->set_text(preedit_string);
    input_text_->show();
  }
#endif
}
Ejemplo n.º 21
0
	void processBuf()
	{
#ifdef XMPP_PARSER_DEBUG
		printf("processing.  size=%d, at=%d\n", in.size(), at);
#endif
		if(!dec) {
			QTextCodec *codec = 0;
			uchar *p = (uchar *)in.data() + at;
			int size = in.size() - at;

			// do we have enough information to determine the encoding?
			if(size == 0)
				return;
			bool utf16 = false;
			if(p[0] == 0xfe || p[0] == 0xff) {
				// probably going to be a UTF-16 byte order mark
				if(size < 2)
					return;
				if((p[0] == 0xfe && p[1] == 0xff) || (p[0] == 0xff && p[1] == 0xfe)) {
					// ok it is UTF-16
					utf16 = true;
				}
			}
			if(utf16)
				codec = QTextCodec::codecForMib(1000); // UTF-16
			else
				codec = QTextCodec::codecForMib(106); // UTF-8

			v_encoding = codec->name();
			dec = codec->makeDecoder();

			// for utf16, put in the byte order mark
			if(utf16) {
				out += dec->toUnicode((const char *)p, 2);
				at += 2;
			}
		}

		if(mightChangeEncoding) {
			while(1) {
				int n = out.indexOf('<');
				if(n != -1) {
					// we need a closing bracket
					int n2 = out.indexOf('>', n);
					if(n2 != -1) {
						++n2;
						QString h = out.mid(n, n2-n);
						QString enc = processXmlHeader(h);
						QTextCodec *codec = 0;
						if(!enc.isEmpty())
							codec = QTextCodec::codecForName(enc.toLatin1());

						// changing codecs
						if(codec) {
							v_encoding = codec->name();
							delete dec;
							dec = codec->makeDecoder();
						}
						mightChangeEncoding = false;
						out.truncate(0);
						at = 0;
						resetLastData();
						break;
					}
				}
				QString s;
				if(!tryExtractPart(&s))
					break;
				if(checkBad && checkForBadChars(s)) {
					// go to the parser
					mightChangeEncoding = false;
					out.truncate(0);
					at = 0;
					resetLastData();
					break;
				}
				out += s;
			}
		}
	}