MCPcopy Create free account
hub / github.com/TeXworks/texworks / readFile

Method readFile

src/TeXDocumentWindow.cpp:951–1034  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

949#define PEEK_LENGTH 1024
950
951QString TeXDocumentWindow::readFile(const QFileInfo & fileInfo,
952 QTextCodec **codecUsed,
953 int *lineEndings,
954 QTextCodec * forceCodec)
955 // reads the text from a file, after checking for %!TEX encoding.... metadata
956 // sets codecUsed to the QTextCodec used to read the text
957 // returns a null (not just empty) QString on failure
958{
959 if (lineEndings) {
960 // initialize to default for the platform
961#if defined(Q_OS_WIN)
962 *lineEndings = kLineEnd_CRLF;
963#else
964 *lineEndings = kLineEnd_LF;
965#endif
966 }
967
968 utf8BOM = false;
969 QFile file(fileInfo.absoluteFilePath());
970 // Not using QFile::Text because this prevents us reading "classic" Mac files
971 // with CR-only line endings. See issue #242.
972 if (!file.open(QFile::ReadOnly)) {
973 QMessageBox::warning(this, QCoreApplication::applicationName(),
974 tr("Cannot read file \"%1\":\n%2")
975 .arg(fileInfo.absoluteFilePath(), file.errorString()));
976 return QString();
977 }
978
979 QByteArray peekBytes(file.peek(PEEK_LENGTH));
980
981 QString reqName;
982 if (forceCodec)
983 *codecUsed = forceCodec;
984 else {
985 bool hasMetadata{false};
986 *codecUsed = scanForEncoding(QString::fromUtf8(peekBytes.constData()), hasMetadata, reqName);
987 if (!(*codecUsed)) {
988 *codecUsed = TWApp::instance()->getDefaultCodec();
989 if (hasMetadata) {
990 if (QMessageBox::warning(this, tr("Unrecognized encoding"),
991 tr("The text encoding %1 used in %2 is not supported.\n\n"
992 "It will be interpreted as %3 instead, which may result in incorrect text.")
993 .arg(reqName, fileInfo.absoluteFilePath(), QString::fromUtf8((*codecUsed)->name().constData())),
994 QMessageBox::Ok | QMessageBox::Cancel, QMessageBox::Ok) == QMessageBox::Cancel)
995 return QString();
996 }
997 }
998 }
999
1000 // When using the UTF-8 codec (mib = 106), byte order marks (BOMs) are
1001 // ignored during reading and not produced when writing. To keep them in
1002 // files that have them, we need to check for them ourselves.
1003 if ((*codecUsed)->mibEnum() == 106 && peekBytes.size() >= 3 && peekBytes[0] == '\xEF' && peekBytes[1] == '\xBB' && peekBytes[2] == '\xBF')
1004 utf8BOM = true;
1005
1006 // If the file is empty (we're already at the end), don't try to read
1007 // anything using QTextStream below as that would return a Null-String
1008 // (QString()) rather than an empty string (QString("")). Instead, return

Callers 2

logParserTest.jsFile · 0.45
RunTestsFunction · 0.45

Calls 6

getDefaultCodecMethod · 0.80
mibEnumMethod · 0.80
containsMethod · 0.80
absoluteFilePathMethod · 0.45
openMethod · 0.45
nameMethod · 0.45

Tested by

no test coverage detected