Sat, 15 Jun 2013 01:20:07 +0300
Converted from C-style fopen to the new File class
src/addObjectDialog.cpp | file | annotate | diff | comparison | revisions | |
src/addObjectDialog.h | file | annotate | diff | comparison | revisions | |
src/colors.cpp | file | annotate | diff | comparison | revisions | |
src/extprogs.cpp | file | annotate | diff | comparison | revisions | |
src/file.cpp | file | annotate | diff | comparison | revisions | |
src/file.h | file | annotate | diff | comparison | revisions | |
src/gui_actions.cpp | file | annotate | diff | comparison | revisions | |
src/main.cpp | file | annotate | diff | comparison | revisions | |
src/types.cpp | file | annotate | diff | comparison | revisions | |
src/types.h | file | annotate | diff | comparison | revisions |
--- a/src/addObjectDialog.cpp Fri Jun 14 19:34:30 2013 +0300 +++ b/src/addObjectDialog.cpp Sat Jun 15 01:20:07 2013 +0300 @@ -113,9 +113,9 @@ for (partListEntry& part : g_PartList) { QList<QTreeWidgetItem*> subfileItems; - str fileName = part.sName; + str fileName = part.name; const bool isSubpart = fileName.mid (0, 2) == "s\\"; - const bool isPrimitive = str (part.sTitle).mid (0, 9) == "Primitive"; + const bool isPrimitive = part.title.mid (0, 9) == "Primitive"; const bool isHiRes = fileName.mid (0, 3) == "48\\"; if ((i == Subparts && isSubpart) || @@ -124,7 +124,7 @@ (i == Parts && !isSubpart && !isPrimitive && !isHiRes)) { SubfileListItem* item = new SubfileListItem (parentItem, j); - item->setText (0, fmt ("%1 - %2", part.sName, part.sTitle)); + item->setText (0, fmt ("%1 - %2", part.name, part.title)); subfileItems.append (item); } @@ -308,13 +308,13 @@ // ============================================================================= // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // ============================================================================= -char* AddObjectDialog::currentSubfileName() { +str AddObjectDialog::currentSubfileName() { SubfileListItem* item = static_cast<SubfileListItem*> (tw_subfileList->currentItem ()); if (item->subfileID == -1) - return null; // selected a heading + return ""; // selected a heading - return g_PartList[item->subfileID].sName; + return g_PartList[item->subfileID].name; } // ============================================================================= @@ -337,9 +337,9 @@ // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // ============================================================================= void AddObjectDialog::slot_subfileTypeChanged () { - char* name = currentSubfileName (); + str name = currentSubfileName (); - if (name) + if (name.length () > 0) le_subfileName->setText (name); }
--- a/src/addObjectDialog.h Fri Jun 14 19:34:30 2013 +0300 +++ b/src/addObjectDialog.h Sat Jun 15 01:20:07 2013 +0300 @@ -67,7 +67,7 @@ private: void setButtonBackground (QPushButton* button, short color); - char* currentSubfileName (); + str currentSubfileName (); short colnum;
--- a/src/colors.cpp Fri Jun 14 19:34:30 2013 +0300 +++ b/src/colors.cpp Sat Jun 15 01:20:07 2013 +0300 @@ -78,23 +78,23 @@ // ============================================================================= void parseLDConfig () { - FILE* fp = openLDrawFile ("LDConfig.ldr", false); + File* f = openLDrawFile ("LDConfig.ldr", false); - if (!fp) { + if (!*f) { critical (fmt ("Unable to open LDConfig.ldr for parsing! (%1)", strerror (errno))); + delete f; return; } // Read in the lines - char buf[1024]; - while (fgets (buf, sizeof buf, fp)) { - if (strlen (buf) == 0 || buf[0] != '0') + for (str line : *f) { + if (line.length () == 0 || line[0] != '0') continue; // empty or illogical - // Use StringParser to parse the LDConfig.ldr file. - str line = buf; line.remove ('\r'); line.remove ('\n'); + + // Parse the line StringParser pars (line, ' '); short code = 0, alpha = 255; @@ -145,5 +145,5 @@ g_LDColors[code] = col; } - fclose (fp); + delete f; } \ No newline at end of file
--- a/src/extprogs.cpp Fri Jun 14 19:34:30 2013 +0300 +++ b/src/extprogs.cpp Sat Jun 15 01:20:07 2013 +0300 @@ -106,37 +106,35 @@ } // ============================================================================= -void writeObjects (vector<LDObject*>& objects, FILE* fp) { +void writeObjects (vector<LDObject*>& objects, File& f) { for (LDObject* obj : objects) { if (obj->getType () == LDObject::Subfile) { vector<LDObject*> objs = static_cast<LDSubfile*> (obj)->inlineContents (true, false); - writeObjects (objs, fp); + writeObjects (objs, f); for (LDObject* obj : objs) delete obj; } else if (obj->getType () == LDObject::Radial) { vector<LDObject*> objs = static_cast<LDRadial*> (obj)->decompose (true); - writeObjects (objs, fp); + writeObjects (objs, f); for (LDObject* obj : objs) delete obj; - } else { - str line = obj->raw () + "\r\n"; - fwrite (qchars (line), 1, line.length (), fp); - } + } else + f.write (obj->raw () + "\r\n"); } } void writeObjects (vector<LDObject*>& objects, str fname) { // Write the input file - FILE* fp = fopen (qchars (fname), "w"); - if (!fp) { + File f (fname, File::Write); + if (!f) { critical (fmt ("Couldn't open temporary file %1 for writing.\n", fname)); return; } - writeObjects (objects, fp); - fclose (fp); + writeObjects (objects, f); + f.close (); } // ============================================================================= @@ -171,17 +169,14 @@ QProcess proc; // Init stdin - FILE* stdinfp = fopen (qchars (inputname), "w"); + File stdinfp (inputname, File::Write); // Begin! proc.setStandardInputFile (inputname); proc.start (path, argv); // Write an enter - one is expected - char enter[2] = "\n"; - enter[1] = '\0'; - fwrite (enter, 1, sizeof enter, stdinfp); - fflush (stdinfp); + stdinfp.write ("\n"); // Wait while it runs proc.waitForFinished (); @@ -203,13 +198,13 @@ #endif // RELEASE // Read the output file - FILE* fp = fopen (qchars (fname), "r"); - if (!fp) { + File f (fname, File::Read); + if (!f) { critical (fmt ("Couldn't open temporary file %1 for reading.\n", fname)); return; } - vector<LDObject*> objs = loadFileContents (fp, null); + vector<LDObject*> objs = loadFileContents (&f, null); // If we replace the objects, delete the selection now. if (replace) @@ -230,7 +225,6 @@ g_win->sel () << obj; } - fclose (fp); g_win->fullRefresh (); }
--- a/src/file.cpp Fri Jun 14 19:34:30 2013 +0300 +++ b/src/file.cpp Sat Jun 15 01:20:07 2013 +0300 @@ -141,8 +141,9 @@ } // ============================================================================= -FILE* openLDrawFile (str relpath, bool subdirs) { - printf ("%s: Try to open %s\n", __func__, qchars (relpath)); +File* openLDrawFile (str relpath, bool subdirs) { + print ("%1: Try to open %2\n", __func__, relpath); + File* f = new File; #ifndef WIN32 relpath.replace ("\\", "/"); @@ -150,28 +151,24 @@ if (g_curfile != null) { str partpath = fmt ("%1" DIRSLASH "%2", dirname (g_curfile->name ()), relpath); - printf ("try %s\n", qchars (partpath)); - FILE* fp = fopen (qchars (partpath), "r"); + print ("try %1\n", partpath); - if (fp != null) - return fp; + if (f->open (partpath, File::Read)) + return f; } - printf ("try %s\n", qchars (relpath)); - FILE* fp = fopen (qchars (relpath), "r"); - str fullPath; + print ("try %1\n", relpath); + if (f->open (relpath, File::Read)) + return f; - if (fp != null) - return fp; - + str fullPath; if (io_ldpath.value.length () > 0) { // Try with just the LDraw path first fullPath = fmt ("%1" DIRSLASH "%2", io_ldpath, relpath); - printf ("try %s\n", qchars (fullPath)); + print ("try %1\n", fullPath); - fp = fopen (qchars (fullPath), "r"); - if (fp != null) - return fp; + if (f->open (fullPath, File::Read)) + return f; if (subdirs) { for (auto subdir : initlist<const char*> ({"parts", "p"})) { @@ -179,14 +176,13 @@ io_ldpath, subdir, relpath); printf ("try %s\n", qchars (fullPath)); - fp = fopen (qchars (fullPath), "r"); - - if (fp) - return fp; + if (f->open (fullPath, File::Read)) + return f; } } } + delete f; return null; } @@ -194,18 +190,16 @@ // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // ============================================================================= void FileLoader::work () { - char line[1024]; m_progress = 0; abortflag = false; - while (fgets (line, sizeof line, filePointer ())) { + for (str line : *PROP_NAME (file)) { // Trim the trailing newline - str data = line; qchar c; - while ((c = data[data.length () - 1]) == '\n' || c == '\r') - data.chop (1); + while ((c = line[line.length () - 1]) == '\n' || c == '\r') + line.chop (1); - LDObject* obj = parseLine (data); + LDObject* obj = parseLine (line); assert (obj != null); // Check for parse errors and warn about tthem @@ -213,7 +207,7 @@ logf (LOG_Warning, "Couldn't parse line #%lu: %s\n", m_progress + 1, qchars (static_cast<LDGibberish*> (obj)->reason)); - logf (LOG_Warning, "- Line was: %s\n", qchars (data)); + logf (LOG_Warning, "- Line was: %s\n", qchars (line)); if (m_warningsPointer) (*m_warningsPointer)++; @@ -240,7 +234,7 @@ // ============================================================================= // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // ============================================================================= -vector<LDObject*> loadFileContents (FILE* fp, ulong* numWarnings, bool* ok) { +vector<LDObject*> loadFileContents (File* f, ulong* numWarnings, bool* ok) { vector<str> lines; vector<LDObject*> objs; @@ -248,16 +242,17 @@ *numWarnings = 0; FileLoader* loader = new FileLoader; - loader->setFilePointer (fp); + loader->setFile (f); loader->setWarningsPointer (numWarnings); // Calculate the amount of lines ulong numLines = 0; - char line[1024]; - while (fgets (line, sizeof line, fp)) + for (str line : *f) { + (void) line; numLines++; + } - rewind (fp); + f->rewind (); if (g_loadingMainFile) { // Show a progress dialog if we're loading the main file here and move @@ -304,13 +299,19 @@ // Convert the file name to lowercase since some parts contain uppercase // file names. I'll assume here that the library will always use lowercase // file names for the actual parts.. - FILE* fp; + File* f; if (search) - fp = openLDrawFile (path.toLower (), true); - else - fp = fopen (qchars (path), "r"); + f = openLDrawFile (path.toLower (), true); + else { + f = new File (path, File::Read); + + if (!*f) { + delete f; + f = null; + } + } - if (!fp) + if (!f) return null; LDOpenFile* oldLoad = g_curfile; @@ -324,7 +325,7 @@ ulong numWarnings; bool ok; - vector<LDObject*> objs = loadFileContents (fp, &numWarnings, &ok); + vector<LDObject*> objs = loadFileContents (f, &numWarnings, &ok); if (!ok) { load = oldLoad; @@ -334,7 +335,7 @@ for (LDObject* obj : objs) load->addObject (obj); - fclose (fp); + delete f; g_loadedFiles << load; logf ("File %s parsed successfully (%lu warning%s).\n", @@ -479,6 +480,10 @@ LDOpenFile* file = openDATFile (path, false); if (!file) { + // Loading failed, thus drop down to a new file since we + // closed everything prior. + newFile (); + // Tell the user loading failed. setlocale (LC_ALL, "C"); critical (fmt ("Failed to open %1: %2", path, strerror (errno))); @@ -511,9 +516,9 @@ if (!savepath.length ()) savepath = name (); - FILE* fp = fopen (qchars (savepath), "w"); + File f (savepath, File::Write); - if (!fp) + if (!f) return false; // If the second object in the list holds the file name, update that now. @@ -539,11 +544,10 @@ // Write all entries now for (LDObject* obj : objs ()) { // LDraw requires files to have DOS line endings - str line = obj->raw () + "\r\n"; - fwrite (qchars (line), 1, line.length (), fp); + f.write (obj->raw () + "\r\n"); } - fclose (fp); + f.close (); // We have successfully saved, update the save position now. setSavePos (history ().pos ()); @@ -862,51 +866,22 @@ vector<partListEntry> g_PartList; void initPartList () { - FILE* fp = openLDrawFile ("parts.lst", false); + File* f = openLDrawFile ("parts.lst", false); - if (!fp) + if (!f) return; - char sLine[1024]; - while (fgets (sLine, sizeof sLine, fp)) { - // Locate the first whitespace - char* cpWhite = strstr (sLine, " "); - - char sName[65]; - size_t uLength = (cpWhite - sLine); - - if (uLength >= 64) - continue; // too long - - strncpy (sName, sLine, uLength); - sName[uLength] = '\0'; - - // Surf through the whitespace sea! - while (*cpWhite == ' ') - cpWhite++; - - // Get the end point - char* cpEnd = strstr (sLine, "\r"); - - if (cpEnd == null) { - // must not be DOS-formatted - cpEnd = strstr (sLine, "\n"); - } - - assert (cpEnd != null); - - // Make the file title now - char sTitle[81]; - uLength = (cpEnd - cpWhite); - strncpy (sTitle, cpWhite, uLength); - sTitle[uLength] = '\0'; + for (str line : *f) { + int white = line.indexOf (" "); + str name = line.left (white); + str title = line.mid (white + 1); // Add it to the array. - partListEntry entry; - strcpy (entry.sName, sName); - strcpy (entry.sTitle, sTitle); + partListEntry entry = { name, title }; g_PartList << entry; } + + delete f; } // =============================================================================
--- a/src/file.h Fri Jun 14 19:34:30 2013 +0300 +++ b/src/file.h Sat Jun 15 01:20:07 2013 +0300 @@ -114,7 +114,7 @@ LDOpenFile* openDATFile (str path, bool search); // Opens the given file and returns a pointer to it, potentially looking in /parts and /p -FILE* openLDrawFile (str path, bool bSubDirectories); +File* openLDrawFile (str relpath, bool subdirs); // Close all open files, whether user-opened or subfile caches. void closeAll (); @@ -132,13 +132,13 @@ bool safeToCloseAll (); typedef struct { - char sName[65], sTitle[81]; + str name, title; } partListEntry; // Init and parse parts.lst void initPartList (); -vector<LDObject*> loadFileContents (FILE* fp, ulong* numWarnings, bool* ok = null); +vector<LDObject*> loadFileContents (File* f, ulong* numWarnings, bool* ok = null); extern vector<LDOpenFile*> g_loadedFiles; extern vector<partListEntry> g_PartList; @@ -152,7 +152,7 @@ READ_PROPERTY (vector<LDObject*>, objs, setObjects) READ_PROPERTY (bool, done, setDone) READ_PROPERTY (ulong, progress, setProgress) - PROPERTY (FILE*, filePointer, setFilePointer) + PROPERTY (File*, file, setFile) PROPERTY (ulong*, warningsPointer, setWarningsPointer) public:
--- a/src/gui_actions.cpp Fri Jun 14 19:34:30 2013 +0300 +++ b/src/gui_actions.cpp Sat Jun 15 01:20:07 2013 +0300 @@ -302,13 +302,13 @@ if (!fname.length ()) return; - FILE* fp = fopen (qchars (fname), "r"); - if (!fp) { + File f (fname, File::Read); + if (!f) { critical (fmt ("Couldn't open %1 (%2)", fname, strerror (errno))); return; } - vector<LDObject*> objs = loadFileContents (fp, null); + vector<LDObject*> objs = loadFileContents (&f, null); g_win->sel ().clear ();
--- a/src/main.cpp Fri Jun 14 19:34:30 2013 +0300 +++ b/src/main.cpp Sat Jun 15 01:20:07 2013 +0300 @@ -65,11 +65,11 @@ // Load or create the configuration if (!config::load ()) { - printf ("Creating configuration file...\n"); + print ("Creating configuration file...\n"); if (config::save ()) - printf ("Configuration file successfully created.\n"); + print ("Configuration file successfully created.\n"); else - printf ("failed to create configuration file!\n"); + print ("failed to create configuration file!\n"); } LDPaths::initPaths ();
--- a/src/types.cpp Fri Jun 14 19:34:30 2013 +0300 +++ b/src/types.cpp Sat Jun 15 01:20:07 2013 +0300 @@ -25,7 +25,7 @@ #include "types.h" #include "misc.h" -const File nullfile (null); +const File nullfile; str DoFormat (vector<StringFormatArg> args) { assert (args.size () >= 1); @@ -276,7 +276,7 @@ } // ============================================================================= -File::File (const std::nullptr_t&) { +File::File () { // Make a null file m_file = null; m_textstream = null; @@ -348,12 +348,19 @@ m_file->write (msg.toUtf8 (), msg.length ()); } -str File::readLine () { - return m_textstream->readLine (); +bool File::readLine (str& line) { + if (!m_textstream || m_textstream->atEnd ()) + return false; + + line = m_textstream->readLine (); + return true; } bool File::atEnd () const { - return m_textstream->atEnd (); + if (!m_textstream) + fatal ("cannot use atEnd on a null file"); + + return m_textstream->atEnd (); } bool File::isNull () const { @@ -381,16 +388,29 @@ return m_file->flush (); } -void File::iterator::operator++() { - m_text = m_file->readLine (); +File::operator bool () const { + return !isNull (); +} + +void File::rewind () { + m_file->seek (0); } -str File::iterator::operator*() { +File::iterator::iterator (File* f) : m_file (f) { + operator++ (); +} + +void File::iterator::operator++ () { + m_gotdata = m_file->readLine (m_text); +} + +str File::iterator::operator* () { return m_text; } +// The prime contestant for the weirdest operator== 2013 award? bool File::iterator::operator== (File::iterator& other) { - return (other.m_file == null && m_file->atEnd ()); + return (other.m_file == null && !m_gotdata); } bool File::iterator::operator!= (File::iterator& other) {
--- a/src/types.h Fri Jun 14 19:34:30 2013 +0300 +++ b/src/types.h Sat Jun 15 01:20:07 2013 +0300 @@ -402,7 +402,7 @@ class iterator { public: iterator () : m_file (null) {} // end iterator has m_file == null - iterator (File* f) : m_file (f), m_text (m_file->readLine ()) {} + iterator (File* f); void operator++ (); str operator* (); bool operator== (iterator& other); @@ -411,6 +411,7 @@ private: File* m_file; str m_text; + bool m_gotdata = false; }; enum OpenType { @@ -419,7 +420,7 @@ Append }; - File (const std::nullptr_t&); + File (); File (str path, File::OpenType rtype); File (FILE* fp, File::OpenType rtype); ~File (); @@ -430,11 +431,14 @@ iterator& end (); bool flush (); bool isNull () const; - str readLine (); + bool readLine (str& line); + void rewind (); bool open (FILE* fp, OpenType rtype); bool open (str path, OpenType rtype, FILE* fp = null); + void write (str msg); + bool operator! () const; - void write (str msg); + operator bool () const; private: QFile* m_file;