本文整理汇总了C++中QTextDecoder::toUnicode方法的典型用法代码示例。如果您正苦于以下问题:C++ QTextDecoder::toUnicode方法的具体用法?C++ QTextDecoder::toUnicode怎么用?C++ QTextDecoder::toUnicode使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类QTextDecoder
的用法示例。
在下文中一共展示了QTextDecoder::toUnicode方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: getOutputFromFileMimeCmd
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 "";
}
}
示例2: decrypt
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());
}
示例3: tryExtractPart
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;
}
示例4: applyEncoding
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());
}
示例5: QMainWindow
//------------------------------------------------------------------------------
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."));
}
示例6: readInfo
/**
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;
}
示例7: downloadData
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();
}
示例8: readSongList
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();
}
示例9: setCurrentLrc
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();
}
示例10: LoadSubtitles
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;
}
示例11: generate_qpath
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 );
}
示例12: editOutputFile
//------------------------------------------------------------------------------
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();
}
//.........这里部分代码省略.........
示例13: readInfo
//------------------------------------------------------------------------------
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();
}
示例14: updateText
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
}
示例15: open
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;
}