Exemplo 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 "";
    }
}
//------------------------------------------------------------------------------
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."));
}
Exemplo n.º 3
0
void KompareProcess::setEncoding( const QString& encoding )
{
	if ( encoding.lower() == "default" )
	{
		m_textDecoder = QTextCodec::codecForLocale()->makeDecoder();
	}
	else
	{
		QTextCodec* textCodec = KGlobal::charsets()->codecForName( encoding.latin1() );
		if ( textCodec )
			m_textDecoder = textCodec->makeDecoder();
		else
		{
			kdDebug(8101) << "Using locale codec as backup..." << endl;
			textCodec = QTextCodec::codecForLocale();
			m_textDecoder = textCodec->makeDecoder();
		}
	}
}
Exemplo 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;
}
Exemplo n.º 5
0
VT100Parser::VT100Parser(ScreenModel* screen) :
    Parser(screen)
{
    QTextCodec *codec = QTextCodec::codecForName("UTF-8");
    decoder = codec->makeDecoder();

    decodeState = PlainText;
    currentTokenStart = 0;
    currentPosition = 0;
    intermediateChar = QChar();
    m_cursorKeyMode = 0;
}
Exemplo n.º 6
0
 KEncodingDetectorPrivate(QTextCodec *codec, KEncodingDetector::EncodingChoiceSource source, KEncodingDetector::AutoDetectScript script)
     : m_codec(codec)
     , m_decoder(m_codec->makeDecoder())
     , m_defaultCodec(m_codec)
     , m_source(source)
     , m_autoDetectLanguage(script)
     , m_visualRTL(false)
     , m_seenBody(false)
     , m_writtingHappened(false)
     , m_analyzeCalled(false)
     , m_multiByte(0)
 {
 }
Exemplo n.º 7
0
 KEncodingDetectorPrivate()
     : m_codec(QTextCodec::codecForMib(MibLatin1))
     , m_decoder(m_codec->makeDecoder())
     , m_defaultCodec(m_codec)
     , m_source(KEncodingDetector::DefaultEncoding)
     , m_autoDetectLanguage(KEncodingDetector::SemiautomaticDetection)
     , m_visualRTL(false)
     , m_seenBody(false)
     , m_writtingHappened(false)
     , m_analyzeCalled(false)
     , m_multiByte(0)
 {
 }
Exemplo n.º 8
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;
}
Exemplo n.º 9
0
QString TextShow::quoteText(const char *t, const char *charset)
{
    if (t == NULL)
        t = "";
    QString text;
    QTextCodec *codec = NULL;
    if (charset)
        codec = QTextCodec::codecForName(charset);
    if (codec){
        text = codec->makeDecoder()->toUnicode(t, strlen(t));
    }else{
        text = QString::fromLocal8Bit(t);
    }
    return quoteString(text);
}
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();
}
Exemplo n.º 11
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());
		}
void CustomScriptSearchProvider::parseAsHtml(QNetworkReply* pReply)
{
    if (m_pEngine)
    {
        QString contentType = pReply->header(QNetworkRequest::ContentTypeHeader).toString();
        QString encoding = detectEncoding(contentType);
        QTextCodec* codec = QTextCodec::codecForName(encoding.toLocal8Bit());
        QString data = codec->makeDecoder()->toUnicode(pReply->readAll());
        QSgml* sgml = new QSgml(data);
        QScriptValue htmlResult = m_pEngine->newQObject(sgml);
        QScriptValue thisObj = m_scriptVal;

        if (thisObj.isObject() && thisObj.isValid())
        {
            thisObj.setProperty("htmlResult", htmlResult);
            emit HtmlResultReady();
        }
    }
}
Exemplo n.º 13
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();
}
Exemplo n.º 14
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;
}
Exemplo n.º 15
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();
}
Exemplo n.º 16
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 );
}
Exemplo n.º 17
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;
			}
		}
	}
Exemplo n.º 18
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;
}
//------------------------------------------------------------------------------
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;
}
Exemplo n.º 20
0
void TextSubtitleParser::LoadSubtitles(const QString &fileName,
                                       TextSubtitles &target,
                                       bool inBackground)
{
    if (inBackground)
    {
        if (!SubtitleLoadHelper::IsLoading(&target))
            MThreadPool::globalInstance()->
                start(new SubtitleLoadHelper(fileName, &target),
                      "SubtitleLoadHelper");
        return;
    }
    demux_sputext_t sub_data;
    RemoteFileWrapper rfile(fileName/*, false, false, 0*/);

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

    // Only reload if rfile.GetFileSize() 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;
    }
    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));

    // try to determine the text codec
    QByteArray test(sub_data.rbuffer_text, sub_data.rbuffer_len);
    QTextCodec *textCodec = QTextCodec::codecForUtfText(test, NULL);
    if (!textCodec)
    {
        LOG(VB_VBI, LOG_WARNING, "Failed to autodetect a UTF encoding.");
        QString codec = gCoreContext->GetSetting("SubtitleCodec", "");
        if (!codec.isEmpty())
            textCodec = QTextCodec::codecForName(codec.toLatin1());
        if (!textCodec)
            textCodec = QTextCodec::codecForName("utf-8");
        if (!textCodec)
        {
            LOG(VB_VBI, LOG_ERR,
                QString("Failed to find codec for subtitle file '%1'")
                .arg(fileName));
            return;
        }
    }

    LOG(VB_VBI, LOG_INFO, QString("Opened subtitle file '%1' with codec '%2'")
        .arg(fileName).arg(textCodec->name().constData()));

    // load the entire subtitle file, converting to unicode as we go
    QScopedPointer<QTextDecoder> dec(textCodec->makeDecoder());
    QString data = dec->toUnicode(sub_data.rbuffer_text, sub_data.rbuffer_len);
    if (data.isEmpty())
    {
        LOG(VB_VBI, LOG_WARNING,
            QString("Data loaded from subtitle file '%1' is empty.")
            .arg(fileName));
        return;
    }

    // convert back to utf-8 for parsing
    QByteArray ba = data.toUtf8();
    delete[] sub_data.rbuffer_text;
    sub_data.rbuffer_text = ba.data();
    sub_data.rbuffer_len = ba.size();

    subtitle_t *loaded_subs = sub_read_file(&sub_data);
    if (!loaded_subs)
    {
        // Don't delete[] sub_data.rbuffer_text; because the
        // QByteArray destructor will clean up.
        LOG(VB_VBI, LOG_ERR, QString("Failed to read subtitles from '%1'")
            .arg(fileName));
        return;
    }

    LOG(VB_VBI, LOG_INFO, QString("Found %1 subtitles in file '%2'")
        .arg(sub_data.num).arg(fileName));
    target.SetFrameBasedTiming(!sub_data.uses_time);
    target.Clear();

    // convert the subtitles to our own format, free the original structures
    // and convert back to unicode
    textCodec = QTextCodec::codecForName("utf-8");
    if (textCodec)
        dec.reset(textCodec->makeDecoder());

    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;
            if (textCodec)
                str = dec->toUnicode(subLine, strlen(subLine));
            else
                str = QString(subLine);
            newsub.textLines.push_back(str);

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

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

    free(loaded_subs);
    // Don't delete[] sub_data.rbuffer_text; because the QByteArray
    // destructor will clean up.

    target.SetLastLoaded();
}
Exemplo n.º 21
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
}
Exemplo n.º 22
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;
}
Exemplo n.º 23
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;
}