From 252a2ec8b0f0f9cf20c947737087b24a8185b588 Mon Sep 17 00:00:00 2001 From: Michele Calgaro Date: Wed, 10 Jul 2024 18:56:16 +0900 Subject: Rename IO and network class nt* related files to equivalent tq* Signed-off-by: Michele Calgaro --- src/tools/ntqbuffer.h | 103 -- src/tools/ntqdatastream.h | 193 ---- src/tools/ntqdir.h | 250 ----- src/tools/ntqfile.h | 131 --- src/tools/ntqfileinfo.h | 151 --- src/tools/ntqglobal.h | 2 +- src/tools/ntqiodevice.h | 160 --- src/tools/ntqsettings.h | 159 --- src/tools/qbuffer.cpp | 494 --------- src/tools/qcomlibrary.cpp | 4 +- src/tools/qcomponentfactory.cpp | 4 +- src/tools/qdatastream.cpp | 1180 ---------------------- src/tools/qdir.cpp | 1390 ------------------------- src/tools/qdir_p.h | 82 -- src/tools/qdir_unix.cpp | 329 ------ src/tools/qfeatures.txt | 8 +- src/tools/qfile.cpp | 747 -------------- src/tools/qfile_unix.cpp | 734 -------------- src/tools/qfiledefs_p.h | 67 -- src/tools/qfileinfo.cpp | 704 ------------- src/tools/qfileinfo_unix.cpp | 400 -------- src/tools/qgdict.cpp | 2 +- src/tools/qglist.cpp | 2 +- src/tools/qgpluginmanager.cpp | 2 +- src/tools/qgvector.cpp | 2 +- src/tools/qiodevice.cpp | 759 -------------- src/tools/qlibrary.cpp | 2 +- src/tools/qsettings.cpp | 2128 --------------------------------------- src/tools/qsettings_p.h | 148 --- src/tools/qt_tools.pri | 68 +- src/tools/quuid.cpp | 2 +- src/tools/qwinexport.cpp | 4 +- src/tools/tqbitarray.cpp | 2 +- src/tools/tqbuffer.cpp | 494 +++++++++ src/tools/tqbuffer.h | 103 ++ src/tools/tqcstring.cpp | 2 +- src/tools/tqdatastream.cpp | 1180 ++++++++++++++++++++++ src/tools/tqdatastream.h | 193 ++++ src/tools/tqdatetime.cpp | 2 +- src/tools/tqdir.cpp | 1390 +++++++++++++++++++++++++ src/tools/tqdir.h | 250 +++++ src/tools/tqdir_p.h | 82 ++ src/tools/tqdir_unix.cpp | 329 ++++++ src/tools/tqfile.cpp | 747 ++++++++++++++ src/tools/tqfile.h | 131 +++ src/tools/tqfile_unix.cpp | 734 ++++++++++++++ src/tools/tqfiledefs_p.h | 67 ++ src/tools/tqfileinfo.cpp | 704 +++++++++++++ src/tools/tqfileinfo.h | 151 +++ src/tools/tqfileinfo_unix.cpp | 400 ++++++++ src/tools/tqiodevice.cpp | 759 ++++++++++++++ src/tools/tqiodevice.h | 160 +++ src/tools/tqmap.h | 2 +- src/tools/tqpair.h | 2 +- src/tools/tqsettings.cpp | 2128 +++++++++++++++++++++++++++++++++++++++ src/tools/tqsettings.h | 159 +++ src/tools/tqsettings_p.h | 148 +++ src/tools/tqstring.cpp | 2 +- src/tools/tqstringlist.cpp | 2 +- src/tools/tqstrlist.h | 2 +- src/tools/tqstrvec.h | 2 +- src/tools/tqtextstream.cpp | 4 +- src/tools/tqtextstream.h | 2 +- src/tools/tqvaluelist.h | 2 +- src/tools/tqvaluevector.h | 2 +- 65 files changed, 10374 insertions(+), 10374 deletions(-) delete mode 100644 src/tools/ntqbuffer.h delete mode 100644 src/tools/ntqdatastream.h delete mode 100644 src/tools/ntqdir.h delete mode 100644 src/tools/ntqfile.h delete mode 100644 src/tools/ntqfileinfo.h delete mode 100644 src/tools/ntqiodevice.h delete mode 100644 src/tools/ntqsettings.h delete mode 100644 src/tools/qbuffer.cpp delete mode 100644 src/tools/qdatastream.cpp delete mode 100644 src/tools/qdir.cpp delete mode 100644 src/tools/qdir_p.h delete mode 100644 src/tools/qdir_unix.cpp delete mode 100644 src/tools/qfile.cpp delete mode 100644 src/tools/qfile_unix.cpp delete mode 100644 src/tools/qfiledefs_p.h delete mode 100644 src/tools/qfileinfo.cpp delete mode 100644 src/tools/qfileinfo_unix.cpp delete mode 100644 src/tools/qiodevice.cpp delete mode 100644 src/tools/qsettings.cpp delete mode 100644 src/tools/qsettings_p.h create mode 100644 src/tools/tqbuffer.cpp create mode 100644 src/tools/tqbuffer.h create mode 100644 src/tools/tqdatastream.cpp create mode 100644 src/tools/tqdatastream.h create mode 100644 src/tools/tqdir.cpp create mode 100644 src/tools/tqdir.h create mode 100644 src/tools/tqdir_p.h create mode 100644 src/tools/tqdir_unix.cpp create mode 100644 src/tools/tqfile.cpp create mode 100644 src/tools/tqfile.h create mode 100644 src/tools/tqfile_unix.cpp create mode 100644 src/tools/tqfiledefs_p.h create mode 100644 src/tools/tqfileinfo.cpp create mode 100644 src/tools/tqfileinfo.h create mode 100644 src/tools/tqfileinfo_unix.cpp create mode 100644 src/tools/tqiodevice.cpp create mode 100644 src/tools/tqiodevice.h create mode 100644 src/tools/tqsettings.cpp create mode 100644 src/tools/tqsettings.h create mode 100644 src/tools/tqsettings_p.h (limited to 'src/tools') diff --git a/src/tools/ntqbuffer.h b/src/tools/ntqbuffer.h deleted file mode 100644 index 66f84e86f..000000000 --- a/src/tools/ntqbuffer.h +++ /dev/null @@ -1,103 +0,0 @@ -/**************************************************************************** -** -** Definition of TQBuffer class -** -** Created : 930812 -** -** Copyright (C) 1992-2008 Trolltech ASA. All rights reserved. -** -** This file is part of the tools module of the TQt GUI Toolkit. -** -** This file may be used under the terms of the GNU General -** Public License versions 2.0 or 3.0 as published by the Free -** Software Foundation and appearing in the files LICENSE.GPL2 -** and LICENSE.GPL3 included in the packaging of this file. -** Alternatively you may (at your option) use any later version -** of the GNU General Public License if such license has been -** publicly approved by Trolltech ASA (or its successors, if any) -** and the KDE Free TQt Foundation. -** -** Please review the following information to ensure GNU General -** Public Licensing requirements will be met: -** http://trolltech.com/products/qt/licenses/licensing/opensource/. -** If you are unsure which license is appropriate for your use, please -** review the following information: -** http://trolltech.com/products/qt/licenses/licensing/licensingoverview -** or contact the sales department at sales@trolltech.com. -** -** This file may be used under the terms of the Q Public License as -** defined by Trolltech ASA and appearing in the file LICENSE.TQPL -** included in the packaging of this file. Licensees holding valid TQt -** Commercial licenses may use this file in accordance with the TQt -** Commercial License Agreement provided with the Software. -** -** This file is provided "AS IS" with NO WARRANTY OF ANY KIND, -** INCLUDING THE WARRANTIES OF DESIGN, MERCHANTABILITY AND FITNESS FOR -** A PARTICULAR PURPOSE. Trolltech reserves all rights not granted -** herein. -** -**********************************************************************/ - -#ifndef TQBUFFER_H -#define TQBUFFER_H - -#ifndef QT_H -#include "ntqiodevice.h" -#include "tqstring.h" -#endif // QT_H - - -class TQ_EXPORT TQBuffer : public TQIODevice -{ -public: - TQBuffer(); - TQBuffer( TQByteArray ); - ~TQBuffer(); - - TQByteArray buffer() const; - bool setBuffer( TQByteArray ); - - bool open( int ); - void close(); - void flush(); - - Offset size() const; - Offset at() const; - bool at( Offset ); - - TQ_LONG readBlock( char *p, TQ_ULONG ); - TQ_LONG writeBlock( const char *p, TQ_ULONG ); - TQ_LONG writeBlock( const TQByteArray& data ) - { return TQIODevice::writeBlock(data); } - TQ_LONG readLine( char *p, TQ_ULONG ); - - int getch(); - int putch( int ); - int ungetch( int ); - -protected: - TQByteArray a; - -private: - uint a_len; - uint a_inc; - -private: // Disabled copy constructor and operator= -#if defined(TQ_DISABLE_COPY) - TQBuffer( const TQBuffer & ); - TQBuffer &operator=( const TQBuffer & ); -#endif -}; - - -inline TQByteArray TQBuffer::buffer() const -{ return a; } - -inline TQIODevice::Offset TQBuffer::size() const -{ return (Offset)a.size(); } - -inline TQIODevice::Offset TQBuffer::at() const -{ return ioIndex; } - - -#endif // TQBUFFER_H diff --git a/src/tools/ntqdatastream.h b/src/tools/ntqdatastream.h deleted file mode 100644 index 2d4063475..000000000 --- a/src/tools/ntqdatastream.h +++ /dev/null @@ -1,193 +0,0 @@ -/**************************************************************************** -** -** Definition of TQDataStream class -** -** Created : 930831 -** -** Copyright (C) 1992-2008 Trolltech ASA. All rights reserved. -** -** This file is part of the tools module of the TQt GUI Toolkit. -** -** This file may be used under the terms of the GNU General -** Public License versions 2.0 or 3.0 as published by the Free -** Software Foundation and appearing in the files LICENSE.GPL2 -** and LICENSE.GPL3 included in the packaging of this file. -** Alternatively you may (at your option) use any later version -** of the GNU General Public License if such license has been -** publicly approved by Trolltech ASA (or its successors, if any) -** and the KDE Free TQt Foundation. -** -** Please review the following information to ensure GNU General -** Public Licensing requirements will be met: -** http://trolltech.com/products/qt/licenses/licensing/opensource/. -** If you are unsure which license is appropriate for your use, please -** review the following information: -** http://trolltech.com/products/qt/licenses/licensing/licensingoverview -** or contact the sales department at sales@trolltech.com. -** -** This file may be used under the terms of the Q Public License as -** defined by Trolltech ASA and appearing in the file LICENSE.TQPL -** included in the packaging of this file. Licensees holding valid TQt -** Commercial licenses may use this file in accordance with the TQt -** Commercial License Agreement provided with the Software. -** -** This file is provided "AS IS" with NO WARRANTY OF ANY KIND, -** INCLUDING THE WARRANTIES OF DESIGN, MERCHANTABILITY AND FITNESS FOR -** A PARTICULAR PURPOSE. Trolltech reserves all rights not granted -** herein. -** -**********************************************************************/ - -#ifndef TQDATASTREAM_H -#define TQDATASTREAM_H - -#ifndef QT_H -#include "ntqiodevice.h" -#include "tqstring.h" -#endif // QT_H - -#ifndef TQT_NO_DATASTREAM -class TQ_EXPORT TQDataStream // data stream class -{ -public: - TQDataStream(); - TQDataStream( TQIODevice * ); - TQDataStream( TQByteArray, int mode ); - virtual ~TQDataStream(); - - TQIODevice *device() const; - void setDevice( TQIODevice * ); - void unsetDevice(); - - bool atEnd() const; - bool eof() const; - - enum ByteOrder { BigEndian, LittleEndian }; - int byteOrder() const; - void setByteOrder( int ); - - bool isPrintableData() const; - void setPrintableData( bool ); - - int version() const; - void setVersion( int ); - - TQDataStream &operator>>( TQ_INT8 &i ); - TQDataStream &operator>>( TQ_UINT8 &i ); - TQDataStream &operator>>( TQ_INT16 &i ); - TQDataStream &operator>>( TQ_UINT16 &i ); - TQDataStream &operator>>( TQ_INT32 &i ); - TQDataStream &operator>>( TQ_UINT32 &i ); - TQDataStream &operator>>( TQ_INT64 &i ); - TQDataStream &operator>>( TQ_UINT64 &i ); -#if !defined(Q_OS_WIN64) - TQDataStream &operator>>( TQ_LONG &i ); - TQDataStream &operator>>( TQ_ULONG &i ); -#endif - - TQDataStream &operator>>( float &f ); - TQDataStream &operator>>( double &f ); - TQDataStream &operator>>( char *&str ); - - TQDataStream &operator<<( TQ_INT8 i ); - TQDataStream &operator<<( TQ_UINT8 i ); - TQDataStream &operator<<( TQ_INT16 i ); - TQDataStream &operator<<( TQ_UINT16 i ); - TQDataStream &operator<<( TQ_INT32 i ); - TQDataStream &operator<<( TQ_UINT32 i ); - TQDataStream &operator<<( TQ_INT64 i ); - TQDataStream &operator<<( TQ_UINT64 i ); -#if !defined(Q_OS_WIN64) - TQDataStream &operator<<( TQ_LONG i ); - TQDataStream &operator<<( TQ_ULONG i ); -#endif - TQDataStream &operator<<( float f ); - TQDataStream &operator<<( double f ); - TQDataStream &operator<<( const char *str ); - - TQDataStream &readBytes( char *&, uint &len ); - TQDataStream &readRawBytes( char *, uint len ); - - TQDataStream &writeBytes( const char *, uint len ); - TQDataStream &writeRawBytes( const char *, uint len ); - -private: - TQIODevice *dev; - bool owndev; - int byteorder; - bool printable; - bool noswap; - int ver; - -private: // Disabled copy constructor and operator= -#if defined(TQ_DISABLE_COPY) - TQDataStream( const TQDataStream & ); - TQDataStream &operator=( const TQDataStream & ); -#endif -}; - - -/***************************************************************************** - TQDataStream inline functions - *****************************************************************************/ - -inline TQIODevice *TQDataStream::device() const -{ return dev; } - -inline bool TQDataStream::atEnd() const -{ return dev ? dev->atEnd() : TRUE; } - -inline bool TQDataStream::eof() const -{ return atEnd(); } - -inline int TQDataStream::byteOrder() const -{ return byteorder; } - -inline bool TQDataStream::isPrintableData() const -{ return printable; } - -inline void TQDataStream::setPrintableData( bool p ) -{ printable = p; } - -inline int TQDataStream::version() const -{ return ver; } - -inline void TQDataStream::setVersion( int v ) -{ ver = v; } - -inline TQDataStream &TQDataStream::operator>>( TQ_UINT8 &i ) -{ return *this >> (TQ_INT8&)i; } - -inline TQDataStream &TQDataStream::operator>>( TQ_UINT16 &i ) -{ return *this >> (TQ_INT16&)i; } - -inline TQDataStream &TQDataStream::operator>>( TQ_UINT32 &i ) -{ return *this >> (TQ_INT32&)i; } - -inline TQDataStream &TQDataStream::operator>>( TQ_UINT64 &i ) -{ return *this >> (TQ_INT64&)i; } - -#if !defined(Q_OS_WIN64) -inline TQDataStream &TQDataStream::operator>>( TQ_ULONG &i ) -{ return *this >> (TQ_LONG&)i; } -#endif - -inline TQDataStream &TQDataStream::operator<<( TQ_UINT8 i ) -{ return *this << (TQ_INT8)i; } - -inline TQDataStream &TQDataStream::operator<<( TQ_UINT16 i ) -{ return *this << (TQ_INT16)i; } - -inline TQDataStream &TQDataStream::operator<<( TQ_UINT32 i ) -{ return *this << (TQ_INT32)i; } - -inline TQDataStream &TQDataStream::operator<<( TQ_UINT64 i ) -{ return *this << (TQ_INT64)i; } - -#if !defined(Q_OS_WIN64) -inline TQDataStream &TQDataStream::operator<<( TQ_ULONG i ) -{ return *this << (TQ_LONG)i; } -#endif - -#endif // TQT_NO_DATASTREAM -#endif // TQDATASTREAM_H diff --git a/src/tools/ntqdir.h b/src/tools/ntqdir.h deleted file mode 100644 index 04bd409ea..000000000 --- a/src/tools/ntqdir.h +++ /dev/null @@ -1,250 +0,0 @@ -/**************************************************************************** -** -** Definition of TQDir class -** -** Created : 950427 -** -** Copyright (C) 1992-2008 Trolltech ASA. All rights reserved. -** -** This file is part of the tools module of the TQt GUI Toolkit. -** -** This file may be used under the terms of the GNU General -** Public License versions 2.0 or 3.0 as published by the Free -** Software Foundation and appearing in the files LICENSE.GPL2 -** and LICENSE.GPL3 included in the packaging of this file. -** Alternatively you may (at your option) use any later version -** of the GNU General Public License if such license has been -** publicly approved by Trolltech ASA (or its successors, if any) -** and the KDE Free TQt Foundation. -** -** Please review the following information to ensure GNU General -** Public Licensing requirements will be met: -** http://trolltech.com/products/qt/licenses/licensing/opensource/. -** If you are unsure which license is appropriate for your use, please -** review the following information: -** http://trolltech.com/products/qt/licenses/licensing/licensingoverview -** or contact the sales department at sales@trolltech.com. -** -** This file may be used under the terms of the Q Public License as -** defined by Trolltech ASA and appearing in the file LICENSE.TQPL -** included in the packaging of this file. Licensees holding valid TQt -** Commercial licenses may use this file in accordance with the TQt -** Commercial License Agreement provided with the Software. -** -** This file is provided "AS IS" with NO WARRANTY OF ANY KIND, -** INCLUDING THE WARRANTIES OF DESIGN, MERCHANTABILITY AND FITNESS FOR -** A PARTICULAR PURPOSE. Trolltech reserves all rights not granted -** herein. -** -**********************************************************************/ - -#ifndef TQDIR_H -#define TQDIR_H - -#ifndef QT_H -#include "ntqglobal.h" -#include "tqstrlist.h" -#include "ntqfileinfo.h" -#endif // QT_H - - -#ifndef TQT_NO_DIR -typedef TQPtrList TQFileInfoList; -typedef TQPtrListIterator TQFileInfoListIterator; -class TQStringList; -template class TQDeepCopy; - - -class TQ_EXPORT TQDir -{ -public: - enum FilterSpec { Dirs = 0x001, - Files = 0x002, - Drives = 0x004, - NoSymLinks = 0x008, - All = 0x007, - TypeMask = 0x00F, - - Readable = 0x010, - Writable = 0x020, - Executable = 0x040, - RWEMask = 0x070, - - Modified = 0x080, - Hidden = 0x100, - System = 0x200, - AccessMask = 0x3F0, - - DefaultFilter = -1 }; - - enum SortSpec { Name = 0x00, - Time = 0x01, - Size = 0x02, - Unsorted = 0x03, - SortByMask = 0x03, - - DirsFirst = 0x04, - Reversed = 0x08, - IgnoreCase = 0x10, - LocaleAware = 0x20, - DefaultSort = -1 }; - - TQDir(); - TQDir( const TQString &path, const TQString &nameFilter = TQString::null, - int sortSpec = Name | IgnoreCase, int filterSpec = All ); - TQDir( const TQDir & ); - - virtual ~TQDir(); - - TQDir &operator=( const TQDir & ); - TQDir &operator=( const TQString &path ); - - virtual void setPath( const TQString &path ); - virtual TQString path() const; - virtual TQString absPath() const; - virtual TQString canonicalPath() const; - - virtual TQString dirName() const; - virtual TQString filePath( const TQString &fileName, - bool acceptAbsPath = TRUE ) const; - virtual TQString absFilePath( const TQString &fileName, - bool acceptAbsPath = TRUE ) const; - - static TQString convertSeparators( const TQString &pathName ); - - virtual bool cd( const TQString &dirName, bool acceptAbsPath = TRUE ); - virtual bool cdUp(); - - TQString nameFilter() const; - virtual void setNameFilter( const TQString &nameFilter ); - FilterSpec filter() const; - virtual void setFilter( int filterSpec ); - SortSpec sorting() const; - virtual void setSorting( int sortSpec ); - - bool matchAllDirs() const; - virtual void setMatchAllDirs( bool ); - - uint count() const; - TQString operator[]( int ) const; - - virtual TQStrList encodedEntryList( int filterSpec = DefaultFilter, - int sortSpec = DefaultSort ) const; - virtual TQStrList encodedEntryList( const TQString &nameFilter, - int filterSpec = DefaultFilter, - int sortSpec = DefaultSort ) const; - virtual TQStringList entryList( int filterSpec = DefaultFilter, - int sortSpec = DefaultSort ) const; - virtual TQStringList entryList( const TQString &nameFilter, - int filterSpec = DefaultFilter, - int sortSpec = DefaultSort ) const; - - virtual const TQFileInfoList *entryInfoList( int filterSpec = DefaultFilter, - int sortSpec = DefaultSort ) const; - virtual const TQFileInfoList *entryInfoList( const TQString &nameFilter, - int filterSpec = DefaultFilter, - int sortSpec = DefaultSort ) const; - - static const TQFileInfoList *drives(); - - virtual bool mkdir( const TQString &dirName, - bool acceptAbsPath = TRUE ) const; - virtual bool rmdir( const TQString &dirName, - bool acceptAbsPath = TRUE ) const; - - virtual bool isReadable() const; - virtual bool exists() const; - virtual bool isRoot() const; - - virtual bool isRelative() const; - virtual void convertToAbs(); - - virtual bool operator==( const TQDir & ) const; - virtual bool operator!=( const TQDir & ) const; - - virtual bool remove( const TQString &fileName, - bool acceptAbsPath = TRUE ); - virtual bool rename( const TQString &name, const TQString &newName, - bool acceptAbsPaths = TRUE ); - virtual bool exists( const TQString &name, - bool acceptAbsPath = TRUE ); - - static char separator(); - - static bool setCurrent( const TQString &path ); - static TQDir current(); - static TQDir home(); - static TQDir root(); - static TQString currentDirPath(); - static TQString homeDirPath(); - static TQString rootDirPath(); - - static bool match( const TQStringList &filters, const TQString &fileName ); - static bool match( const TQString &filter, const TQString &fileName ); - static TQString cleanDirPath( const TQString &dirPath ); - static bool isRelativePath( const TQString &path ); - void refresh() const; - -private: -#ifdef Q_OS_MAC - typedef struct FSSpec FSSpec; - static FSSpec *make_spec(const TQString &); -#endif - void init(); - virtual bool readDirEntries( const TQString &nameFilter, - int FilterSpec, int SortSpec ); - - static void slashify( TQString & ); - - TQString dPath; - TQStringList *fList; - TQFileInfoList *fiList; - TQString nameFilt; - FilterSpec filtS; - SortSpec sortS; - uint dirty : 1; - uint allDirs : 1; - - void detach(); - friend class TQDeepCopy< TQDir >; -}; - - -inline TQString TQDir::path() const -{ - return dPath; -} - -inline TQString TQDir::nameFilter() const -{ - return nameFilt; -} - -inline TQDir::FilterSpec TQDir::filter() const -{ - return filtS; -} - -inline TQDir::SortSpec TQDir::sorting() const -{ - return sortS; -} - -inline bool TQDir::matchAllDirs() const -{ - return allDirs; -} - -inline bool TQDir::operator!=( const TQDir &d ) const -{ - return !(*this == d); -} - - -struct TQDirSortItem { - TQString filename_cache; - TQFileInfo* item; -}; - -#endif // TQT_NO_DIR -#endif // TQDIR_H diff --git a/src/tools/ntqfile.h b/src/tools/ntqfile.h deleted file mode 100644 index ba2d9e103..000000000 --- a/src/tools/ntqfile.h +++ /dev/null @@ -1,131 +0,0 @@ -/**************************************************************************** -** -** Definition of TQFile class -** -** Created : 930831 -** -** Copyright (C) 1992-2008 Trolltech ASA. All rights reserved. -** -** This file is part of the tools module of the TQt GUI Toolkit. -** -** This file may be used under the terms of the GNU General -** Public License versions 2.0 or 3.0 as published by the Free -** Software Foundation and appearing in the files LICENSE.GPL2 -** and LICENSE.GPL3 included in the packaging of this file. -** Alternatively you may (at your option) use any later version -** of the GNU General Public License if such license has been -** publicly approved by Trolltech ASA (or its successors, if any) -** and the KDE Free TQt Foundation. -** -** Please review the following information to ensure GNU General -** Public Licensing requirements will be met: -** http://trolltech.com/products/qt/licenses/licensing/opensource/. -** If you are unsure which license is appropriate for your use, please -** review the following information: -** http://trolltech.com/products/qt/licenses/licensing/licensingoverview -** or contact the sales department at sales@trolltech.com. -** -** This file may be used under the terms of the Q Public License as -** defined by Trolltech ASA and appearing in the file LICENSE.TQPL -** included in the packaging of this file. Licensees holding valid TQt -** Commercial licenses may use this file in accordance with the TQt -** Commercial License Agreement provided with the Software. -** -** This file is provided "AS IS" with NO WARRANTY OF ANY KIND, -** INCLUDING THE WARRANTIES OF DESIGN, MERCHANTABILITY AND FITNESS FOR -** A PARTICULAR PURPOSE. Trolltech reserves all rights not granted -** herein. -** -**********************************************************************/ - -#ifndef TQFILE_H -#define TQFILE_H - -#ifndef QT_H -#include "ntqiodevice.h" -#include "tqstring.h" -#include -#endif // QT_H - -class TQDir; -class TQFilePrivate; - -class TQ_EXPORT TQFile : public TQIODevice // file I/O device class -{ -public: - TQFile(); - TQFile( const TQString &name ); - ~TQFile(); - - TQString name() const; - void setName( const TQString &name ); - - typedef TQCString (*EncoderFn)( const TQString &fileName ); - typedef TQString (*DecoderFn)( const TQCString &localfileName ); - static TQCString encodeName( const TQString &fileName ); - static TQString decodeName( const TQCString &localFileName ); - static void setEncodingFunction( EncoderFn ); - static void setDecodingFunction( DecoderFn ); - - bool exists() const; - static bool exists( const TQString &fileName ); - - bool remove(); - static bool remove( const TQString &fileName ); - - bool open( int ); - bool open( int, FILE * ); - bool open( int, int ); - void close(); - void flush(); - - Offset size() const; - Offset at() const; - bool at( Offset ); - bool atEnd() const; - - TQ_LONG readBlock( char *data, TQ_ULONG len ); - TQ_LONG writeBlock( const char *data, TQ_ULONG len ); - TQ_LONG writeBlock( const TQByteArray& data ) - { return TQIODevice::writeBlock(data); } - TQ_LONG readLine( char *data, TQ_ULONG maxlen ); - TQ_LONG readLine( TQString &, TQ_ULONG maxlen ); - - int getch(); - int putch( int ); - int ungetch( int ); - - int handle() const; - - TQString errorString() const; // ### TQt 4: move into TQIODevice - -protected: - void setErrorString( const TQString& ); // ### TQt 4: move into TQIODevice - TQString fn; - FILE *fh; - int fd; - Offset length; - bool ext_f; - TQFilePrivate *d; // ### TQt 4: make private - -private: - void init(); - void setErrorStringErrno( int ); - TQCString ungetchBuffer; - -private: // Disabled copy constructor and operator= -#if defined(TQ_DISABLE_COPY) - TQFile( const TQFile & ); - TQFile &operator=( const TQFile & ); -#endif -}; - - -inline TQString TQFile::name() const -{ return fn; } - -inline TQIODevice::Offset TQFile::at() const -{ return ioIndex; } - - -#endif // TQFILE_H diff --git a/src/tools/ntqfileinfo.h b/src/tools/ntqfileinfo.h deleted file mode 100644 index 3c4e3b3a3..000000000 --- a/src/tools/ntqfileinfo.h +++ /dev/null @@ -1,151 +0,0 @@ -/**************************************************************************** -** -** Definition of TQFileInfo class -** -** Created : 950628 -** -** Copyright (C) 1992-2008 Trolltech ASA. All rights reserved. -** -** This file is part of the tools module of the TQt GUI Toolkit. -** -** This file may be used under the terms of the GNU General -** Public License versions 2.0 or 3.0 as published by the Free -** Software Foundation and appearing in the files LICENSE.GPL2 -** and LICENSE.GPL3 included in the packaging of this file. -** Alternatively you may (at your option) use any later version -** of the GNU General Public License if such license has been -** publicly approved by Trolltech ASA (or its successors, if any) -** and the KDE Free TQt Foundation. -** -** Please review the following information to ensure GNU General -** Public Licensing requirements will be met: -** http://trolltech.com/products/qt/licenses/licensing/opensource/. -** If you are unsure which license is appropriate for your use, please -** review the following information: -** http://trolltech.com/products/qt/licenses/licensing/licensingoverview -** or contact the sales department at sales@trolltech.com. -** -** This file may be used under the terms of the Q Public License as -** defined by Trolltech ASA and appearing in the file LICENSE.TQPL -** included in the packaging of this file. Licensees holding valid TQt -** Commercial licenses may use this file in accordance with the TQt -** Commercial License Agreement provided with the Software. -** -** This file is provided "AS IS" with NO WARRANTY OF ANY KIND, -** INCLUDING THE WARRANTIES OF DESIGN, MERCHANTABILITY AND FITNESS FOR -** A PARTICULAR PURPOSE. Trolltech reserves all rights not granted -** herein. -** -**********************************************************************/ - -#ifndef TQFILEINFO_H -#define TQFILEINFO_H - -#ifndef QT_H -#include "ntqfile.h" -#include "tqdatetime.h" -#endif // QT_H - - -class TQDir; -struct TQFileInfoCache; -template class TQDeepCopy; - - -class TQ_EXPORT TQFileInfo -{ -public: - enum PermissionSpec { - ReadOwner = 04000, WriteOwner = 02000, ExeOwner = 01000, - ReadUser = 00400, WriteUser = 00200, ExeUser = 00100, - ReadGroup = 00040, WriteGroup = 00020, ExeGroup = 00010, - ReadOther = 00004, WriteOther = 00002, ExeOther = 00001 }; - - TQFileInfo(); - TQFileInfo( const TQString &file ); - TQFileInfo( const TQFile & ); -#ifndef TQT_NO_DIR - TQFileInfo( const TQDir &, const TQString &fileName ); -#endif - TQFileInfo( const TQFileInfo & ); - ~TQFileInfo(); - - TQFileInfo &operator=( const TQFileInfo & ); - - void setFile( const TQString &file ); - void setFile( const TQFile & ); -#ifndef TQT_NO_DIR - void setFile( const TQDir &, const TQString &fileName ); -#endif - bool exists() const; - void refresh() const; - bool caching() const; - void setCaching( bool ); - - TQString filePath() const; - TQString fileName() const; -#ifndef TQT_NO_DIR //### - TQString absFilePath() const; -#endif - TQString baseName( bool complete = FALSE ) const; - TQString extension( bool complete = TRUE ) const; - -#ifndef TQT_NO_DIR //### - TQString dirPath( bool absPath = FALSE ) const; -#endif -#ifndef TQT_NO_DIR - TQDir dir( bool absPath = FALSE ) const; -#endif - bool isReadable() const; - bool isWritable() const; - bool isExecutable() const; - bool isHidden() const; - -#ifndef TQT_NO_DIR //### - bool isRelative() const; - bool convertToAbs(); -#endif - - bool isFile() const; - bool isDir() const; - bool isSymLink() const; - - TQString readLink() const; - - TQString owner() const; - uint ownerId() const; - TQString group() const; - uint groupId() const; - - bool permission( int permissionSpec ) const; - - uint size() const; - - TQDateTime created() const; - TQDateTime lastModified() const; - TQDateTime lastRead() const; - -private: - void doStat() const; - static void slashify( TQString & ); - static void makeAbs( TQString & ); - - TQString fn; - TQFileInfoCache *fic; - bool cache; -#if defined(Q_OS_UNIX) - bool symLink; -#endif - - void detach(); - friend class TQDeepCopy< TQFileInfo >; -}; - - -inline bool TQFileInfo::caching() const -{ - return cache; -} - - -#endif // TQFILEINFO_H diff --git a/src/tools/ntqglobal.h b/src/tools/ntqglobal.h index 2d449fd9c..64115edf3 100644 --- a/src/tools/ntqglobal.h +++ b/src/tools/ntqglobal.h @@ -718,7 +718,7 @@ typedef TQ_UINT64 TQ_ULLONG; // unsigned long long // -// Data stream functions is provided by many classes (defined in ntqdatastream.h) +// Data stream functions is provided by many classes (defined in tqdatastream.h) // class TQCString; diff --git a/src/tools/ntqiodevice.h b/src/tools/ntqiodevice.h deleted file mode 100644 index 712288d8e..000000000 --- a/src/tools/ntqiodevice.h +++ /dev/null @@ -1,160 +0,0 @@ -/**************************************************************************** -** -** Definition of TQIODevice class -** -** Created : 940913 -** -** Copyright (C) 1992-2008 Trolltech ASA. All rights reserved. -** -** This file is part of the tools module of the TQt GUI Toolkit. -** -** This file may be used under the terms of the GNU General -** Public License versions 2.0 or 3.0 as published by the Free -** Software Foundation and appearing in the files LICENSE.GPL2 -** and LICENSE.GPL3 included in the packaging of this file. -** Alternatively you may (at your option) use any later version -** of the GNU General Public License if such license has been -** publicly approved by Trolltech ASA (or its successors, if any) -** and the KDE Free TQt Foundation. -** -** Please review the following information to ensure GNU General -** Public Licensing requirements will be met: -** http://trolltech.com/products/qt/licenses/licensing/opensource/. -** If you are unsure which license is appropriate for your use, please -** review the following information: -** http://trolltech.com/products/qt/licenses/licensing/licensingoverview -** or contact the sales department at sales@trolltech.com. -** -** This file may be used under the terms of the Q Public License as -** defined by Trolltech ASA and appearing in the file LICENSE.TQPL -** included in the packaging of this file. Licensees holding valid TQt -** Commercial licenses may use this file in accordance with the TQt -** Commercial License Agreement provided with the Software. -** -** This file is provided "AS IS" with NO WARRANTY OF ANY KIND, -** INCLUDING THE WARRANTIES OF DESIGN, MERCHANTABILITY AND FITNESS FOR -** A PARTICULAR PURPOSE. Trolltech reserves all rights not granted -** herein. -** -**********************************************************************/ - -#ifndef TQIODEVICE_H -#define TQIODEVICE_H - -#ifndef QT_H -#include "ntqglobal.h" -#include "tqcstring.h" -#endif // QT_H - - -// IO device access types - -#define IO_Direct 0x0100 // direct access device -#define IO_Sequential 0x0200 // sequential access device -#define IO_Combined 0x0300 // combined direct/sequential -#define IO_TypeMask 0x0f00 - -// IO handling modes - -#define IO_Raw 0x0040 // raw access (not buffered) -#define IO_Async 0x0080 // asynchronous mode - -// IO device open modes - -#define IO_ReadOnly 0x0001 // readable device -#define IO_WriteOnly 0x0002 // writable device -#define IO_ReadWrite 0x0003 // read+write device -#define IO_Append 0x0004 // append -#define IO_Truncate 0x0008 // truncate device -#define IO_Translate 0x0010 // translate CR+LF -#define IO_ModeMask 0x00ff - -// IO device state - -#define IO_Open 0x1000 // device is open -#define IO_StateMask 0xf000 - -// IO device status - -#define IO_Ok 0 -#define IO_ReadError 1 // read error -#define IO_WriteError 2 // write error -#define IO_FatalError 3 // fatal unrecoverable error -#define IO_ResourceError 4 // resource limitation -#define IO_OpenError 5 // cannot open device -#define IO_ConnectError 5 // cannot connect to device -#define IO_AbortError 6 // abort error -#define IO_TimeOutError 7 // time out -#define IO_UnspecifiedError 8 // unspecified error - - -class TQ_EXPORT TQIODevice -{ -public: - typedef TQ_ULONG Offset; - - TQIODevice(); - virtual ~TQIODevice(); - - int flags() const { return ioMode; } - int mode() const { return ioMode & IO_ModeMask; } - int state() const { return ioMode & IO_StateMask; } - - bool isDirectAccess() const { return ((ioMode & IO_Direct) == IO_Direct); } - bool isSequentialAccess() const { return ((ioMode & IO_Sequential) == IO_Sequential); } - bool isCombinedAccess() const { return ((ioMode & IO_Combined) == IO_Combined); } - bool isBuffered() const { return ((ioMode & IO_Raw) != IO_Raw); } - bool isRaw() const { return ((ioMode & IO_Raw) == IO_Raw); } - bool isSynchronous() const { return ((ioMode & IO_Async) != IO_Async); } - bool isAsynchronous() const { return ((ioMode & IO_Async) == IO_Async); } - bool isTranslated() const { return ((ioMode & IO_Translate) == IO_Translate); } - bool isReadable() const { return ((ioMode & IO_ReadOnly) == IO_ReadOnly); } - bool isWritable() const { return ((ioMode & IO_WriteOnly) == IO_WriteOnly); } - bool isReadWrite() const { return ((ioMode & IO_ReadWrite) == IO_ReadWrite); } - bool isInactive() const { return state() == 0; } - bool isOpen() const { return state() == IO_Open; } - - int status() const { return ioSt; } - void resetStatus() { ioSt = IO_Ok; } - - virtual bool open( int mode ) = 0; - virtual void close() = 0; - virtual void flush() = 0; - - virtual Offset size() const = 0; - virtual Offset at() const; - virtual bool at( Offset ); - virtual bool atEnd() const; - bool reset() { return at(0); } - - virtual TQ_LONG readBlock( char *data, TQ_ULONG maxlen ) = 0; - virtual TQ_LONG writeBlock( const char *data, TQ_ULONG len ) = 0; - virtual TQ_LONG readLine( char *data, TQ_ULONG maxlen ); - TQ_LONG writeBlock( const TQByteArray& data ); - virtual TQByteArray readAll(); - - virtual int getch() = 0; - virtual int putch( int ) = 0; - virtual int ungetch( int ) = 0; - -protected: - void setFlags( int f ) { ioMode = f; } - void setType( int ); - void setMode( int ); - void setState( int ); - void setStatus( int ); - Offset ioIndex; - -private: - int ioMode; - int ioSt; - -private: // Disabled copy constructor and operator= -#if defined(TQ_DISABLE_COPY) - TQIODevice( const TQIODevice & ); - TQIODevice &operator=( const TQIODevice & ); -#endif -}; - - -#endif // TQIODEVICE_H diff --git a/src/tools/ntqsettings.h b/src/tools/ntqsettings.h deleted file mode 100644 index ee8e8e3b2..000000000 --- a/src/tools/ntqsettings.h +++ /dev/null @@ -1,159 +0,0 @@ -/**************************************************************************** -** -** Definition of TQSettings class -** -** Created : 000626 -** -** Copyright (C) 2000-2008 Trolltech ASA. All rights reserved. -** -** This file is part of the tools module of the TQt GUI Toolkit. -** -** This file may be used under the terms of the GNU General -** Public License versions 2.0 or 3.0 as published by the Free -** Software Foundation and appearing in the files LICENSE.GPL2 -** and LICENSE.GPL3 included in the packaging of this file. -** Alternatively you may (at your option) use any later version -** of the GNU General Public License if such license has been -** publicly approved by Trolltech ASA (or its successors, if any) -** and the KDE Free TQt Foundation. -** -** Please review the following information to ensure GNU General -** Public Licensing requirements will be met: -** http://trolltech.com/products/qt/licenses/licensing/opensource/. -** If you are unsure which license is appropriate for your use, please -** review the following information: -** http://trolltech.com/products/qt/licenses/licensing/licensingoverview -** or contact the sales department at sales@trolltech.com. -** -** This file may be used under the terms of the Q Public License as -** defined by Trolltech ASA and appearing in the file LICENSE.TQPL -** included in the packaging of this file. Licensees holding valid TQt -** Commercial licenses may use this file in accordance with the TQt -** Commercial License Agreement provided with the Software. -** -** This file is provided "AS IS" with NO WARRANTY OF ANY KIND, -** INCLUDING THE WARRANTIES OF DESIGN, MERCHANTABILITY AND FITNESS FOR -** A PARTICULAR PURPOSE. Trolltech reserves all rights not granted -** herein. -** -**********************************************************************/ - -#ifndef TQSETTINGS_H -#define TQSETTINGS_H - -#ifndef QT_H -#include "tqdatetime.h" -#include "tqstringlist.h" -#endif // QT_H - -#ifndef TQT_NO_SETTINGS - -class TQSettingsPrivate; - - -class TQ_EXPORT TQSettings -{ -public: - enum Format { - Native = 0, - Ini - }; - enum System { - Unix = 0, - Windows, - Mac - }; - enum Scope { - User, - Global - }; - - TQSettings(); - TQSettings( Format format ); - - ~TQSettings(); - -#if !defined(Q_NO_BOOL_TYPE) - bool writeEntry( const TQString &, bool ); -#endif - bool writeEntry( const TQString &, double ); - bool writeEntry( const TQString &, int ); - bool writeEntry( const TQString &, const char * ); - bool writeEntry( const TQString &, const TQString & ); - bool writeEntry( const TQString &, const TQStringList & ); - bool writeEntry( const TQString &, const TQStringList &, const TQChar& sep ); - - TQStringList entryList(const TQString &) const; - TQStringList subkeyList(const TQString &) const; - - //### remove non const versions in 4.0 - TQStringList readListEntry( const TQString &, bool * = 0 ); - TQStringList readListEntry( const TQString &, const TQChar& sep, bool * = 0 ); - TQString readEntry( const TQString &, const TQString &def = TQString::null, bool * = 0 ); - int readNumEntry( const TQString &, int def = 0, bool * = 0 ); - double readDoubleEntry( const TQString &, double def = 0, bool * = 0 ); - bool readBoolEntry( const TQString &, bool def = FALSE, bool * = 0 ); - - //### make those non-inlined in 4.0 - TQStringList readListEntry( const TQString &key, bool *ok = 0 ) const - { - TQSettings *that = (TQSettings*)this; - return that->readListEntry( key, ok ); - } - TQStringList readListEntry( const TQString &key, const TQChar& sep, bool *ok = 0 ) const - { - TQSettings *that = (TQSettings*)this; - return that->readListEntry( key, sep, ok ); - } - TQString readEntry( const TQString &key, const TQString &def = TQString::null, - bool *ok = 0 ) const - { - TQSettings *that = (TQSettings*)this; - return that->readEntry( key, def, ok ); - } - int readNumEntry( const TQString &key, int def = 0, bool *ok = 0 ) const - { - TQSettings *that = (TQSettings*)this; - return that->readNumEntry( key, def, ok ); - } - - double readDoubleEntry( const TQString &key, double def = 0, bool *ok = 0 ) const - { - TQSettings *that = (TQSettings*)this; - return that->readDoubleEntry( key, def, ok ); - } - bool readBoolEntry( const TQString &key, bool def = FALSE, bool *ok = 0 ) const - { - TQSettings *that = (TQSettings*)this; - return that->readBoolEntry( key, def, ok ); - } - - bool removeEntry( const TQString & ); - - void insertSearchPath( System, const TQString & ); - void removeSearchPath( System, const TQString & ); - - void setPath( const TQString &domain, const TQString &product, Scope = Global ); - - void beginGroup( const TQString &group ); - void endGroup(); - void resetGroup(); - TQString group() const; - - bool sync(); - -private: - TQSettingsPrivate *d; - -#if defined(TQ_DISABLE_COPY) - TQSettings(const TQSettings &); - TQSettings &operator=(const TQSettings &); -#endif - - TQDateTime lastModificationTime( const TQString & ); - - friend class TQApplication; -}; - -#endif // TQT_NO_SETTINGS -#endif // TQSETTINGS_H diff --git a/src/tools/qbuffer.cpp b/src/tools/qbuffer.cpp deleted file mode 100644 index b1707d78d..000000000 --- a/src/tools/qbuffer.cpp +++ /dev/null @@ -1,494 +0,0 @@ -/**************************************************************************** -** -** Implementation of TQBuffer class -** -** Created : 930812 -** -** Copyright (C) 1992-2008 Trolltech ASA. All rights reserved. -** -** This file is part of the tools module of the TQt GUI Toolkit. -** -** This file may be used under the terms of the GNU General -** Public License versions 2.0 or 3.0 as published by the Free -** Software Foundation and appearing in the files LICENSE.GPL2 -** and LICENSE.GPL3 included in the packaging of this file. -** Alternatively you may (at your option) use any later version -** of the GNU General Public License if such license has been -** publicly approved by Trolltech ASA (or its successors, if any) -** and the KDE Free TQt Foundation. -** -** Please review the following information to ensure GNU General -** Public Licensing requirements will be met: -** http://trolltech.com/products/qt/licenses/licensing/opensource/. -** If you are unsure which license is appropriate for your use, please -** review the following information: -** http://trolltech.com/products/qt/licenses/licensing/licensingoverview -** or contact the sales department at sales@trolltech.com. -** -** This file may be used under the terms of the Q Public License as -** defined by Trolltech ASA and appearing in the file LICENSE.TQPL -** included in the packaging of this file. Licensees holding valid TQt -** Commercial licenses may use this file in accordance with the TQt -** Commercial License Agreement provided with the Software. -** -** This file is provided "AS IS" with NO WARRANTY OF ANY KIND, -** INCLUDING THE WARRANTIES OF DESIGN, MERCHANTABILITY AND FITNESS FOR -** A PARTICULAR PURPOSE. Trolltech reserves all rights not granted -** herein. -** -**********************************************************************/ - -#include "ntqbuffer.h" -#include - -/*! - \class TQBuffer ntqbuffer.h - \reentrant - \brief The TQBuffer class is an I/O device that operates on a TQByteArray. - - \ingroup io - \ingroup collection - - TQBuffer is used to read and write to a memory buffer. It is - normally used with a TQTextStream or a TQDataStream. TQBuffer has an - associated TQByteArray which holds the buffer data. The size() of - the buffer is automatically adjusted as data is written. - - The constructor \c TQBuffer(TQByteArray) creates a TQBuffer using an - existing byte array. The byte array can also be set with - setBuffer(). Writing to the TQBuffer will modify the original byte - array because TQByteArray is \link shclass.html explicitly - shared.\endlink - - Use open() to open the buffer before use and to set the mode - (read-only, write-only, etc.). close() closes the buffer. The - buffer must be closed before reopening or calling setBuffer(). - - A common way to use TQBuffer is through \l TQDataStream or \l - TQTextStream, which have constructors that take a TQBuffer - parameter. For convenience, there are also TQDataStream and - TQTextStream constructors that take a TQByteArray parameter. These - constructors create and open an internal TQBuffer. - - Note that TQTextStream can also operate on a TQString (a Unicode - string); a TQBuffer cannot. - - You can also use TQBuffer directly through the standard TQIODevice - functions readBlock(), writeBlock() readLine(), at(), getch(), - putch() and ungetch(). - - \sa TQFile, TQDataStream, TQTextStream, TQByteArray, \link shclass.html Shared Classes\endlink -*/ - - -/*! - Constructs an empty buffer. -*/ - -TQBuffer::TQBuffer() -{ - setFlags( IO_Direct ); - a_inc = 16; // initial increment - a_len = 0; - ioIndex = 0; -} - - -/*! - Constructs a buffer that operates on \a buf. - - If you open the buffer in write mode (\c IO_WriteOnly or - \c IO_ReadWrite) and write something into the buffer, \a buf - will be modified. - - Example: - \code - TQCString str = "abc"; - TQBuffer b( str ); - b.open( IO_WriteOnly ); - b.at( 3 ); // position at the 4th character (the terminating \0) - b.writeBlock( "def", 4 ); // write "def" including the terminating \0 - b.close(); - // Now, str == "abcdef" with a terminating \0 - \endcode - - \sa setBuffer() -*/ - -TQBuffer::TQBuffer( TQByteArray buf ) : a(buf) -{ - setFlags( IO_Direct ); - a_len = a.size(); - a_inc = (a_len > 512) ? 512 : a_len; // initial increment - if ( a_inc < 16 ) - a_inc = 16; - ioIndex = 0; -} - -/*! - Destroys the buffer. -*/ - -TQBuffer::~TQBuffer() -{ -} - - -/*! - Replaces the buffer's contents with \a buf and returns TRUE. - - Does nothing (and returns FALSE) if isOpen() is TRUE. - - Note that if you open the buffer in write mode (\c IO_WriteOnly or - IO_ReadWrite) and write something into the buffer, \a buf is also - modified because TQByteArray is an explicitly shared class. - - \sa buffer(), open(), close() -*/ - -bool TQBuffer::setBuffer( TQByteArray buf ) -{ - if ( isOpen() ) { -#if defined(QT_CHECK_STATE) - tqWarning( "TQBuffer::setBuffer: Buffer is open" ); -#endif - return FALSE; - } - a = buf; - a_len = a.size(); - a_inc = (a_len > 512) ? 512 : a_len; // initial increment - if ( a_inc < 16 ) - a_inc = 16; - ioIndex = 0; - return TRUE; -} - -/*! - \fn TQByteArray TQBuffer::buffer() const - - Returns this buffer's byte array. - - \sa setBuffer() -*/ - -/*! - \reimp - - Opens the buffer in mode \a m. Returns TRUE if successful; - otherwise returns FALSE. The buffer must be opened before use. - - The mode parameter \a m must be a combination of the following flags. - \list - \i \c IO_ReadOnly opens the buffer in read-only mode. - \i \c IO_WriteOnly opens the buffer in write-only mode. - \i \c IO_ReadWrite opens the buffer in read/write mode. - \i \c IO_Append sets the buffer index to the end of the buffer. - \i \c IO_Truncate truncates the buffer. - \endlist - - \sa close(), isOpen() -*/ - -bool TQBuffer::open( int m ) -{ - if ( isOpen() ) { // buffer already open -#if defined(QT_CHECK_STATE) - tqWarning( "TQBuffer::open: Buffer already open" ); -#endif - return FALSE; - } - setMode( m ); - if ( m & IO_Truncate ) { // truncate buffer - a.resize( 0 ); - a_len = 0; - } - if ( m & IO_Append ) { // append to end of buffer - ioIndex = a.size(); - } else { - ioIndex = 0; - } - a_inc = 16; - setState( IO_Open ); - resetStatus(); - return TRUE; -} - -/*! - \reimp - - Closes an open buffer. - - \sa open() -*/ - -void TQBuffer::close() -{ - if ( isOpen() ) { - setFlags( IO_Direct ); - ioIndex = 0; - a_inc = 16; - } -} - -/*! - \reimp - - The flush function does nothing for a TQBuffer. -*/ - -void TQBuffer::flush() -{ - return; -} - - -/*! - \fn TQIODevice::Offset TQBuffer::at() const - - \reimp -*/ - -/*! - \fn TQIODevice::Offset TQBuffer::size() const - - \reimp -*/ - -/*! - \reimp -*/ - -bool TQBuffer::at( Offset pos ) -{ -#if defined(QT_CHECK_STATE) - if ( !isOpen() ) { - tqWarning( "TQBuffer::at: Buffer is not open" ); - return FALSE; - } -#endif - if ( pos > a_len ) { -#if defined(QT_CHECK_RANGE) - tqWarning( "TQBuffer::at: Index %lu out of range", pos ); -#endif - return FALSE; - } - ioIndex = pos; - return TRUE; -} - - -/*! - \reimp -*/ - -TQ_LONG TQBuffer::readBlock( char *p, TQ_ULONG len ) -{ -#if defined(QT_CHECK_STATE) - if ( !p ) { - tqWarning( "TQBuffer::readBlock: Null pointer error" ); - return -1; - } - if ( !isOpen() ) { // buffer not open - tqWarning( "TQBuffer::readBlock: Buffer not open" ); - return -1; - } - if ( !isReadable() ) { // reading not permitted - tqWarning( "TQBuffer::readBlock: Read operation not permitted" ); - return -1; - } -#endif - if ( ioIndex + len > a.size() ) { // overflow - if ( ioIndex >= a.size() ) { - return 0; - } else { - len = a.size() - ioIndex; - } - } - memcpy(p, a.data() + ioIndex, len); - ioIndex += len; - return len; -} - -/*! - \overload TQ_LONG TQBuffer::writeBlock( const TQByteArray& data ) - - This convenience function is the same as calling - \c{writeBlock( data.data(), data.size() )} with \a data. -*/ - -/*! - Writes \a len bytes from \a p into the buffer at the current - index position, overwriting any characters there and extending the - buffer if necessary. Returns the number of bytes actually written. - - Returns -1 if an error occurred. - - \sa readBlock() -*/ - -TQ_LONG TQBuffer::writeBlock( const char *p, TQ_ULONG len ) -{ - if ( len == 0 ) - return 0; - -#if defined(QT_CHECK_NULL) - if ( p == 0 ) { - tqWarning( "TQBuffer::writeBlock: Null pointer error" ); - return -1; - } -#endif -#if defined(QT_CHECK_STATE) - if ( !isOpen() ) { // buffer not open - tqWarning( "TQBuffer::writeBlock: Buffer not open" ); - return -1; - } - if ( !isWritable() ) { // writing not permitted - tqWarning( "TQBuffer::writeBlock: Write operation not permitted" ); - return -1; - } -#endif - if ( ioIndex + len > a_len ) { // overflow - TQ_ULONG new_len = a_len + a_inc*((ioIndex+len-a_len)/a_inc+1); - if ( !a.resize( new_len ) ) { // could not resize -#if defined(QT_CHECK_NULL) - tqWarning( "TQBuffer::writeBlock: Memory allocation error" ); -#endif - setStatus( IO_ResourceError ); - return -1; - } - a_inc *= 2; // double increment - a_len = new_len; - a.shd->len = ioIndex + len; - } - memcpy( a.data()+ioIndex, p, len ); - ioIndex += len; - if ( a.shd->len < ioIndex ) - a.shd->len = ioIndex; // fake (not alloc'd) length - return len; -} - - -/*! - \reimp -*/ - -TQ_LONG TQBuffer::readLine( char *p, TQ_ULONG maxlen ) -{ -#if defined(QT_CHECK_NULL) - if ( p == 0 ) { - tqWarning( "TQBuffer::readLine: Null pointer error" ); - return -1; - } -#endif -#if defined(QT_CHECK_STATE) - if ( !isOpen() ) { // buffer not open - tqWarning( "TQBuffer::readLine: Buffer not open" ); - return -1; - } - if ( !isReadable() ) { // reading not permitted - tqWarning( "TQBuffer::readLine: Read operation not permitted" ); - return -1; - } -#endif - if ( maxlen == 0 ) - return 0; - TQ_ULONG start = ioIndex; - char *d = a.data() + ioIndex; - maxlen--; // make room for 0-terminator - if ( a.size() - ioIndex < maxlen ) - maxlen = a.size() - ioIndex; - while ( maxlen-- ) { - if ( (*p++ = *d++) == '\n' ) - break; - } - *p = '\0'; - ioIndex = d - a.data(); - return ioIndex - start; -} - - -/*! - \reimp -*/ - -int TQBuffer::getch() -{ -#if defined(QT_CHECK_STATE) - if ( !isOpen() ) { // buffer not open - tqWarning( "TQBuffer::getch: Buffer not open" ); - return -1; - } - if ( !isReadable() ) { // reading not permitted - tqWarning( "TQBuffer::getch: Read operation not permitted" ); - return -1; - } -#endif - if ( ioIndex+1 > a.size() ) { // overflow - setStatus( IO_ReadError ); - return -1; - } - return uchar(*(a.data()+ioIndex++)); -} - -/*! - \reimp - - Writes the character \a ch into the buffer at the current index - position, overwriting any existing character and extending the - buffer if necessary. - - Returns \a ch, or -1 if an error occurred. - - \sa getch(), ungetch() -*/ - -int TQBuffer::putch( int ch ) -{ -#if defined(QT_CHECK_STATE) - if ( !isOpen() ) { // buffer not open - tqWarning( "TQBuffer::putch: Buffer not open" ); - return -1; - } - if ( !isWritable() ) { // writing not permitted - tqWarning( "TQBuffer::putch: Write operation not permitted" ); - return -1; - } -#endif - if ( ioIndex + 1 > a_len ) { // overflow - char buf[1]; - buf[0] = (char)ch; - if ( writeBlock(buf,1) != 1 ) - return -1; // write error - } else { - *(a.data() + ioIndex++) = (char)ch; - if ( a.shd->len < ioIndex ) - a.shd->len = ioIndex; - } - return ch; -} - -/*! - \reimp -*/ - -int TQBuffer::ungetch( int ch ) -{ -#if defined(QT_CHECK_STATE) - if ( !isOpen() ) { // buffer not open - tqWarning( "TQBuffer::ungetch: Buffer not open" ); - return -1; - } - if ( !isReadable() ) { // reading not permitted - tqWarning( "TQBuffer::ungetch: Read operation not permitted" ); - return -1; - } -#endif - if ( ch != -1 ) { - if ( ioIndex ) - ioIndex--; - else - ch = -1; - } - return ch; -} - diff --git a/src/tools/qcomlibrary.cpp b/src/tools/qcomlibrary.cpp index cc7647da9..2d95ce54a 100644 --- a/src/tools/qcomlibrary.cpp +++ b/src/tools/qcomlibrary.cpp @@ -40,8 +40,8 @@ #ifndef TQT_NO_COMPONENT #include -#include -#include +#include +#include #include #include #ifndef NO_ERRNO_H diff --git a/src/tools/qcomponentfactory.cpp b/src/tools/qcomponentfactory.cpp index 12fe33e10..0186e7843 100644 --- a/src/tools/qcomponentfactory.cpp +++ b/src/tools/qcomponentfactory.cpp @@ -41,9 +41,9 @@ #include "qcomponentfactory_p.h" #ifndef TQT_NO_COMPONENT -#include "ntqsettings.h" +#include "tqsettings.h" #include -#include "ntqdir.h" +#include "tqdir.h" #include "ntqapplication.h" /*! diff --git a/src/tools/qdatastream.cpp b/src/tools/qdatastream.cpp deleted file mode 100644 index d5b7162f7..000000000 --- a/src/tools/qdatastream.cpp +++ /dev/null @@ -1,1180 +0,0 @@ -/**************************************************************************** -** -** Implementation of TQDataStream class -** -** Created : 930831 -** -** Copyright (C) 1992-2008 Trolltech ASA. All rights reserved. -** -** This file is part of the tools module of the TQt GUI Toolkit. -** -** This file may be used under the terms of the GNU General -** Public License versions 2.0 or 3.0 as published by the Free -** Software Foundation and appearing in the files LICENSE.GPL2 -** and LICENSE.GPL3 included in the packaging of this file. -** Alternatively you may (at your option) use any later version -** of the GNU General Public License if such license has been -** publicly approved by Trolltech ASA (or its successors, if any) -** and the KDE Free TQt Foundation. -** -** Please review the following information to ensure GNU General -** Public Licensing requirements will be met: -** http://trolltech.com/products/qt/licenses/licensing/opensource/. -** If you are unsure which license is appropriate for your use, please -** review the following information: -** http://trolltech.com/products/qt/licenses/licensing/licensingoverview -** or contact the sales department at sales@trolltech.com. -** -** This file may be used under the terms of the Q Public License as -** defined by Trolltech ASA and appearing in the file LICENSE.TQPL -** included in the packaging of this file. Licensees holding valid TQt -** Commercial licenses may use this file in accordance with the TQt -** Commercial License Agreement provided with the Software. -** -** This file is provided "AS IS" with NO WARRANTY OF ANY KIND, -** INCLUDING THE WARRANTIES OF DESIGN, MERCHANTABILITY AND FITNESS FOR -** A PARTICULAR PURPOSE. Trolltech reserves all rights not granted -** herein. -** -**********************************************************************/ - -#include "ntqdatastream.h" - -#ifndef TQT_NO_DATASTREAM -#include "ntqbuffer.h" -#include -#include -#include -#ifndef Q_OS_TEMP -#include -#else -#include "qt_windows.h" -#endif - -/*! - \class TQDataStream ntqdatastream.h - \reentrant - \brief The TQDataStream class provides serialization of binary data - to a TQIODevice. - - \ingroup io - - A data stream is a binary stream of encoded information which is - 100% independent of the host computer's operating system, CPU or - byte order. For example, a data stream that is written by a PC - under Windows can be read by a Sun SPARC running Solaris. - - You can also use a data stream to read/write \link #raw raw - unencoded binary data\endlink. If you want a "parsing" input - stream, see TQTextStream. - - The TQDataStream class implements the serialization of C++'s basic - data types, like \c char, \c short, \c int, \c char*, etc. - Serialization of more complex data is accomplished by breaking up - the data into primitive units. - - A data stream cooperates closely with a TQIODevice. A TQIODevice - represents an input/output medium one can read data from and write - data to. The TQFile class is an example of an IO device. - - Example (write binary data to a stream): - \code - TQFile file( "file.dat" ); - file.open( IO_WriteOnly ); - TQDataStream stream( &file ); // we will serialize the data into the file - stream << "the answer is"; // serialize a string - stream << (TQ_INT32)42; // serialize an integer - \endcode - - Example (read binary data from a stream): - \code - TQFile file( "file.dat" ); - file.open( IO_ReadOnly ); - TQDataStream stream( &file ); // read the data serialized from the file - TQString str; - TQ_INT32 a; - stream >> str >> a; // extract "the answer is" and 42 - \endcode - - Each item written to the stream is written in a predefined binary - format that varies depending on the item's type. Supported TQt - types include TQBrush, TQColor, TQDateTime, TQFont, TQPixmap, TQString, - TQVariant and many others. For the complete list of all TQt types - supporting data streaming see the \link datastreamformat.html - Format of the TQDataStream operators \endlink. - - For integers it is best to always cast to a TQt integer type for - writing, and to read back into the same TQt integer type. This - ensures that you get integers of the size you want and insulates - you from compiler and platform differences. - - To take one example, a \c char* string is written as a 32-bit - integer equal to the length of the string including the NUL byte - ('\0'), followed by all the characters of the string including the - NUL byte. When reading a \c char* string, 4 bytes are read to - create the 32-bit length value, then that many characters for the - \c char* string including the NUL are read. - - The initial IODevice is usually set in the constructor, but can be - changed with setDevice(). If you've reached the end of the data - (or if there is no IODevice set) atEnd() will return TRUE. - - If you want the data to be compatible with an earlier version of - TQt use setVersion(). - - If you want the data to be human-readable, e.g. for debugging, you - can set the data stream into printable data mode with - setPrintableData(). The data is then written slower, in a bloated - but human readable format. - - If you are producing a new binary data format, such as a file - format for documents created by your application, you could use a - TQDataStream to write the data in a portable format. Typically, you - would write a brief header containing a magic string and a version - number to give yourself room for future expansion. For example: - - \code - TQFile file( "file.xxx" ); - file.open( IO_WriteOnly ); - TQDataStream stream( &file ); - - // Write a header with a "magic number" and a version - stream << (TQ_UINT32)0xA0B0C0D0; - stream << (TQ_INT32)123; - - // Write the data - stream << [lots of interesting data] - \endcode - - Then read it in with: - - \code - TQFile file( "file.xxx" ); - file.open( IO_ReadOnly ); - TQDataStream stream( &file ); - - // Read and check the header - TQ_UINT32 magic; - stream >> magic; - if ( magic != 0xA0B0C0D0 ) - return XXX_BAD_FILE_FORMAT; - - // Read the version - TQ_INT32 version; - stream >> version; - if ( version < 100 ) - return XXX_BAD_FILE_TOO_OLD; - if ( version > 123 ) - return XXX_BAD_FILE_TOO_NEW; - if ( version <= 110 ) - stream.setVersion(1); - - // Read the data - stream >> [lots of interesting data]; - if ( version > 120 ) - stream >> [data new in XXX version 1.2]; - stream >> [other interesting data]; - \endcode - - You can select which byte order to use when serializing data. The - default setting is big endian (MSB first). Changing it to little - endian breaks the portability (unless the reader also changes to - little endian). We recommend keeping this setting unless you have - special requirements. - - \target raw - \section1 Reading and writing raw binary data - - You may wish to read/write your own raw binary data to/from the - data stream directly. Data may be read from the stream into a - preallocated char* using readRawBytes(). Similarly data can be - written to the stream using writeRawBytes(). Notice that any - encoding/decoding of the data must be done by you. - - A similar pair of functions is readBytes() and writeBytes(). These - differ from their \e raw counterparts as follows: readBytes() - reads a TQ_UINT32 which is taken to be the length of the data to be - read, then that number of bytes is read into the preallocated - char*; writeBytes() writes a TQ_UINT32 containing the length of the - data, followed by the data. Notice that any encoding/decoding of - the data (apart from the length TQ_UINT32) must be done by you. - - \sa TQTextStream TQVariant -*/ - -/*! - \enum TQDataStream::ByteOrder - - The byte order used for reading/writing the data. - - \value BigEndian the default - \value LittleEndian -*/ - - -/***************************************************************************** - TQDataStream member functions - *****************************************************************************/ - -#if defined(QT_CHECK_STATE) -#undef CHECK_STREAM_PRECOND -#define CHECK_STREAM_PRECOND if ( !dev ) { \ - tqWarning( "TQDataStream: No device" ); \ - return *this; } -#else -#define CHECK_STREAM_PRECOND -#endif - -static int systemWordSize = 0; -static bool systemBigEndian; - -static const int DefaultStreamVersion = 6; -// ### On next version bump, TQPen::width() should not be restricted to 8-bit values. -// ### On next version bump, when streaming invalid TQVariants, just the type should -// be written, no "data" after it -// 6 is default in TQt 3.3 -// 5 is default in TQt 3.1 -// 4 is default in TQt 3.0 -// 3 is default in TQt 2.1 -// 2 is the TQt 2.0.x format -// 1 is the TQt 1.x format - -/*! - Constructs a data stream that has no IO device. - - \sa setDevice() -*/ - -TQDataStream::TQDataStream() -{ - if ( systemWordSize == 0 ) // get system features - tqSysInfo( &systemWordSize, &systemBigEndian ); - dev = 0; // no device set - owndev = FALSE; - byteorder = BigEndian; // default byte order - printable = FALSE; - ver = DefaultStreamVersion; - noswap = systemBigEndian; -} - -/*! - Constructs a data stream that uses the IO device \a d. - - \warning If you use TQSocket or TQSocketDevice as the IO device \a d - for reading data, you must make sure that enough data is available - on the socket for the operation to successfully proceed; - TQDataStream does not have any means to handle or recover from - short-reads. - - \sa setDevice(), device() -*/ - -TQDataStream::TQDataStream( TQIODevice *d ) -{ - if ( systemWordSize == 0 ) // get system features - tqSysInfo( &systemWordSize, &systemBigEndian ); - dev = d; // set device - owndev = FALSE; - byteorder = BigEndian; // default byte order - printable = FALSE; - ver = DefaultStreamVersion; - noswap = systemBigEndian; -} - -/*! - Constructs a data stream that operates on a byte array, \a a, - through an internal TQBuffer device. The \a mode is a - TQIODevice::mode(), usually either \c IO_ReadOnly or \c - IO_WriteOnly. - - Example: - \code - static char bindata[] = { 231, 1, 44, ... }; - TQByteArray a; - a.setRawData( bindata, sizeof(bindata) ); // a points to bindata - TQDataStream stream( a, IO_ReadOnly ); // open on a's data - stream >> [something]; // read raw bindata - a.resetRawData( bindata, sizeof(bindata) ); // finished - \endcode - - The TQByteArray::setRawData() function is not for the inexperienced. -*/ - -TQDataStream::TQDataStream( TQByteArray a, int mode ) -{ - if ( systemWordSize == 0 ) // get system features - tqSysInfo( &systemWordSize, &systemBigEndian ); - dev = new TQBuffer( a ); // create device - ((TQBuffer *)dev)->open( mode ); // open device - owndev = TRUE; - byteorder = BigEndian; // default byte order - printable = FALSE; - ver = DefaultStreamVersion; - noswap = systemBigEndian; -} - -/*! - Destroys the data stream. - - The destructor will not affect the current IO device, unless it is - an internal IO device processing a TQByteArray passed in the \e - constructor, in which case the internal IO device is destroyed. -*/ - -TQDataStream::~TQDataStream() -{ - if ( owndev ) - delete dev; -} - - -/*! - \fn TQIODevice *TQDataStream::device() const - - Returns the IO device currently set. - - \sa setDevice(), unsetDevice() -*/ - -/*! - void TQDataStream::setDevice(TQIODevice *d ) - - Sets the IO device to \a d. - - \sa device(), unsetDevice() -*/ - -void TQDataStream::setDevice(TQIODevice *d ) -{ - if ( owndev ) { - delete dev; - owndev = FALSE; - } - dev = d; -} - -/*! - Unsets the IO device. This is the same as calling setDevice( 0 ). - - \sa device(), setDevice() -*/ - -void TQDataStream::unsetDevice() -{ - setDevice( 0 ); -} - - -/*! - \fn bool TQDataStream::atEnd() const - - Returns TRUE if the IO device has reached the end position (end of - the stream or file) or if there is no IO device set; otherwise - returns FALSE, i.e. if the current position of the IO device is - before the end position. - - \sa TQIODevice::atEnd() -*/ - -/*!\fn bool TQDataStream::eof() const - - \obsolete - - Returns TRUE if the IO device has reached the end position (end of - stream or file) or if there is no IO device set. - - Returns FALSE if the current position of the read/write head of the IO - device is somewhere before the end position. - - \sa TQIODevice::atEnd() -*/ - -/*! - \fn int TQDataStream::byteOrder() const - - Returns the current byte order setting -- either \c BigEndian or - \c LittleEndian. - - \sa setByteOrder() -*/ - -/*! - Sets the serialization byte order to \a bo. - - The \a bo parameter can be \c TQDataStream::BigEndian or \c - TQDataStream::LittleEndian. - - The default setting is big endian. We recommend leaving this - setting unless you have special requirements. - - \sa byteOrder() -*/ - -void TQDataStream::setByteOrder( int bo ) -{ - byteorder = bo; - if ( systemBigEndian ) - noswap = byteorder == BigEndian; - else - noswap = byteorder == LittleEndian; -} - - -/*! - \fn bool TQDataStream::isPrintableData() const - - Returns TRUE if the printable data flag has been set; otherwise - returns FALSE. - - \sa setPrintableData() -*/ - -/*! - \fn void TQDataStream::setPrintableData( bool enable ) - - If \a enable is TRUE, data will be output in a human readable - format. If \a enable is FALSE, data will be output in a binary - format. - - If \a enable is TRUE, the write functions will generate output - that consists of printable characters (7 bit ASCII). This output - will typically be a lot larger than the default binary output, and - consequently slower to write. - - We recommend only enabling printable data for debugging purposes. -*/ - - -/*! - \fn int TQDataStream::version() const - - Returns the version number of the data serialization format. In TQt - 3.1, this number is 5. - - \sa setVersion() -*/ - -/*! - \fn void TQDataStream::setVersion( int v ) - - Sets the version number of the data serialization format to \a v. - - You don't need to set a version if you are using the current - version of TQt. - - In order to accommodate new functionality, the datastream - serialization format of some TQt classes has changed in some - versions of TQt. If you want to read data that was created by an - earlier version of TQt, or write data that can be read by a program - that was compiled with an earlier version of TQt, use this function - to modify the serialization format of TQDataStream. - - \table - \header \i TQt Version \i TQDataStream Version - \row \i TQt 3.3 \i11 6 - \row \i TQt 3.2 \i11 5 - \row \i TQt 3.1 \i11 5 - \row \i TQt 3.0 \i11 4 - \row \i TQt 2.1.x and TQt 2.2.x \i11 3 - \row \i TQt 2.0.x \i11 2 - \row \i TQt 1.x \i11 1 - \endtable - - \sa version() -*/ - -/***************************************************************************** - TQDataStream read functions - *****************************************************************************/ - -#if defined(Q_OS_HPUX) && !defined(__LP64__) -extern "C" long long __strtoll( const char *, char**, int ); -#endif - -static TQ_INT64 read_int_ascii( TQDataStream *s ) -{ - int n = 0; - char buf[40]; - for ( ;; ) { - buf[n] = s->device()->getch(); - if ( buf[n] == '\n' || n > 38 ) // $-terminator - break; - n++; - } - buf[n] = '\0'; - -#if defined(__LP64__) || defined(Q_OS_OSF) - // sizeof(long) == 8 - return strtol(buf, (char **)0, 10); -#else -# if defined(Q_OS_TEMP) - return strtol( buf, (char**)0, 10 ); -# elif defined(Q_OS_WIN) - return _atoi64( buf ); -# elif defined(Q_OS_HPUX) - return __strtoll( buf, (char**)0, 10 ); -# elif defined(Q_OS_MACX) && defined(QT_MACOSX_VERSION) && QT_MACOSX_VERSION < 0x1020 - return strtoq( buf, (char**)0, 10 ); -# else - return strtoll( buf, (char**)0, 10 ); // C99 function -# endif -#endif -} - -/*! - \overload TQDataStream &TQDataStream::operator>>( TQ_UINT8 &i ) - - Reads an unsigned byte from the stream into \a i, and returns a - reference to the stream. -*/ - -/*! - Reads a signed byte from the stream into \a i, and returns a - reference to the stream. -*/ - -TQDataStream &TQDataStream::operator>>( TQ_INT8 &i ) -{ - CHECK_STREAM_PRECOND - if ( printable ) { // printable data - i = (TQ_INT8)dev->getch(); - if ( i == '\\' ) { // read octal code - char buf[4]; - dev->readBlock( buf, 3 ); - i = (buf[2] & 0x07)+((buf[1] & 0x07) << 3)+((buf[0] & 0x07) << 6); - } - } else { // data or text - int ret = dev->getch(); - if (ret >= 0) { - i = (TQ_INT8)ret; - } - } - return *this; -} - - -/*! - \overload TQDataStream &TQDataStream::operator>>( TQ_UINT16 &i ) - - Reads an unsigned 16-bit integer from the stream into \a i, and - returns a reference to the stream. -*/ - -/*! - \overload - - Reads a signed 16-bit integer from the stream into \a i, and - returns a reference to the stream. -*/ - -TQDataStream &TQDataStream::operator>>( TQ_INT16 &i ) -{ - CHECK_STREAM_PRECOND - if ( printable ) { // printable data - i = (TQ_INT16)read_int_ascii( this ); - } else if ( noswap ) { // no conversion needed - dev->readBlock( (char *)&i, sizeof(TQ_INT16) ); - } else { // swap bytes - uchar *p = (uchar *)(&i); - char b[2]; - if (dev->readBlock( b, 2 ) >= 2) { - *p++ = b[1]; - *p = b[0]; - } - } - return *this; -} - - -/*! - \overload TQDataStream &TQDataStream::operator>>( TQ_UINT32 &i ) - - Reads an unsigned 32-bit integer from the stream into \a i, and - returns a reference to the stream. -*/ - -/*! - \overload - - Reads a signed 32-bit integer from the stream into \a i, and - returns a reference to the stream. -*/ - -TQDataStream &TQDataStream::operator>>( TQ_INT32 &i ) -{ - CHECK_STREAM_PRECOND - if ( printable ) { // printable data - i = (TQ_INT32)read_int_ascii( this ); - } else if ( noswap ) { // no conversion needed - dev->readBlock( (char *)&i, sizeof(TQ_INT32) ); - } else { // swap bytes - uchar *p = (uchar *)(&i); - char b[4]; - if (dev->readBlock( b, 4 ) >= 4) { - *p++ = b[3]; - *p++ = b[2]; - *p++ = b[1]; - *p = b[0]; - } - } - return *this; -} - -/*! - \overload TQDataStream &TQDataStream::operator>>( TQ_UINT64 &i ) - - Reads an unsigned 64-bit integer from the stream, into \a i, and - returns a reference to the stream. -*/ - -/*! - \overload - - Reads a signed 64-bit integer from the stream into \a i, and - returns a reference to the stream. -*/ - -TQDataStream &TQDataStream::operator>>( TQ_INT64 &i ) -{ - CHECK_STREAM_PRECOND - if ( printable ) { // printable data - i = read_int_ascii( this ); - } else if ( version() < 6 ) { - TQ_UINT32 i1, i2; - *this >> i2 >> i1; - i = ((TQ_UINT64)i1 << 32) + i2; - } else if ( noswap ) { // no conversion needed - dev->readBlock( (char *)&i, sizeof(TQ_INT64) ); - } else { // swap bytes - uchar *p = (uchar *)(&i); - char b[8]; - if (dev->readBlock( b, 8 ) >= 8) { - *p++ = b[7]; - *p++ = b[6]; - *p++ = b[5]; - *p++ = b[4]; - *p++ = b[3]; - *p++ = b[2]; - *p++ = b[1]; - *p = b[0]; - } - } - return *this; -} - - -/*! - \overload TQDataStream &TQDataStream::operator>>( TQ_ULONG &i ) - - Reads an unsigned integer of the system's word length from the - stream, into \a i, and returns a reference to the stream. -*/ - -#if !defined(Q_OS_WIN64) -/*! - \overload - - Reads a signed integer of the system's word length from the stream - into \a i, and returns a reference to the stream. - -*/ - -TQDataStream &TQDataStream::operator>>( TQ_LONG &i ) -{ - CHECK_STREAM_PRECOND - if ( printable ) { // printable data - i = (TQ_LONG)read_int_ascii( this ); - } else if ( noswap ) { // no conversion needed - dev->readBlock( (char *)&i, sizeof(TQ_LONG) ); - } else { // swap bytes - uchar *p = (uchar *)(&i); - char b[sizeof(TQ_LONG)]; - if (dev->readBlock( b, sizeof(TQ_LONG) ) >= (int)sizeof(TQ_LONG)) { - for ( int j = sizeof(TQ_LONG); j; ) { - *p++ = b[--j]; - } - } - } - return *this; -} -#endif - -static double read_double_ascii( TQDataStream *s ) -{ - int n = 0; - char buf[80]; - for ( ;; ) { - buf[n] = s->device()->getch(); - if ( buf[n] == '\n' || n > 78 ) // $-terminator - break; - n++; - } - buf[n] = '\0'; - return atof( buf ); -} - - -/*! - \overload - - Reads a 32-bit floating point number from the stream into \a f, - using the standard IEEE754 format. Returns a reference to the - stream. -*/ - -TQDataStream &TQDataStream::operator>>( float &f ) -{ - CHECK_STREAM_PRECOND - if ( printable ) { // printable data - f = (float)read_double_ascii( this ); - } else if ( noswap ) { // no conversion needed - dev->readBlock( (char *)&f, sizeof(float) ); - } else { // swap bytes - uchar *p = (uchar *)(&f); - char b[4]; - if (dev->readBlock( b, 4 ) >= 4) { - *p++ = b[3]; - *p++ = b[2]; - *p++ = b[1]; - *p = b[0]; - } - } - return *this; -} - - -/*! - \overload - - Reads a 64-bit floating point number from the stream into \a f, - using the standard IEEE754 format. Returns a reference to the - stream. -*/ - -TQDataStream &TQDataStream::operator>>( double &f ) -{ - CHECK_STREAM_PRECOND - if ( printable ) { // printable data - f = read_double_ascii( this ); - } else if ( noswap ) { // no conversion needed - dev->readBlock( (char *)&f, sizeof(double) ); - } else { // swap bytes - uchar *p = (uchar *)(&f); - char b[8]; - if (dev->readBlock( b, 8 ) >= 8) { - *p++ = b[7]; - *p++ = b[6]; - *p++ = b[5]; - *p++ = b[4]; - *p++ = b[3]; - *p++ = b[2]; - *p++ = b[1]; - *p = b[0]; - } - } - return *this; -} - - -/*! - \overload - - Reads the '\0'-terminated string \a s from the stream and returns - a reference to the stream. - - Space for the string is allocated using \c new -- the caller must - destroy it with delete[]. -*/ - -TQDataStream &TQDataStream::operator>>( char *&s ) -{ - uint len = 0; - return readBytes( s, len ); -} - - -/*! - Reads the buffer \a s from the stream and returns a reference to - the stream. - - The buffer \a s is allocated using \c new. Destroy it with the \c - delete[] operator. If the length is zero or \a s cannot be - allocated, \a s is set to 0. - - The \a l parameter will be set to the length of the buffer. - - The serialization format is a TQ_UINT32 length specifier first, - then \a l bytes of data. Note that the data is \e not encoded. - - \sa readRawBytes(), writeBytes() -*/ - -TQDataStream &TQDataStream::readBytes( char *&s, uint &l ) -{ - CHECK_STREAM_PRECOND - TQ_UINT32 len; - *this >> len; // first read length spec - l = (uint)len; - if ( len == 0 || eof() ) { - s = 0; - return *this; - } else { - s = new char[len]; // create char array - TQ_CHECK_PTR( s ); - if ( !s ) // no memory - return *this; - return readRawBytes( s, (uint)len ); - } -} - - -/*! - Reads \a len bytes from the stream into \a s and returns a - reference to the stream. - - The buffer \a s must be preallocated. The data is \e not encoded. - - \sa readBytes(), TQIODevice::readBlock(), writeRawBytes() -*/ - -TQDataStream &TQDataStream::readRawBytes( char *s, uint len ) -{ - CHECK_STREAM_PRECOND - if ( printable ) { // printable data - TQ_INT8 *p = (TQ_INT8*)s; - if ( version() < 4 ) { - while ( len-- ) { - TQ_INT32 tmp; - *this >> tmp; - *p++ = tmp; - } - } else { - while ( len-- ) - *this >> *p++; - } - } else { // read data char array - dev->readBlock( s, len ); - } - return *this; -} - - -/***************************************************************************** - TQDataStream write functions - *****************************************************************************/ - - -/*! - \overload TQDataStream &TQDataStream::operator<<( TQ_UINT8 i ) - - Writes an unsigned byte, \a i, to the stream and returns a - reference to the stream. -*/ - -/*! - Writes a signed byte, \a i, to the stream and returns a reference - to the stream. -*/ - -TQDataStream &TQDataStream::operator<<( TQ_INT8 i ) -{ - CHECK_STREAM_PRECOND - if ( printable && (i == '\\' || !isprint((uchar) i)) ) { - char buf[6]; // write octal code - buf[0] = '\\'; - buf[1] = '0' + ((i >> 6) & 0x07); - buf[2] = '0' + ((i >> 3) & 0x07); - buf[3] = '0' + (i & 0x07); - buf[4] = '\0'; - dev->writeBlock( buf, 4 ); - } else { - dev->putch( i ); - } - return *this; -} - - -/*! - \overload TQDataStream &TQDataStream::operator<<( TQ_UINT16 i ) - - Writes an unsigned 16-bit integer, \a i, to the stream and returns - a reference to the stream. -*/ - -/*! - \overload - - Writes a signed 16-bit integer, \a i, to the stream and returns a - reference to the stream. -*/ - -TQDataStream &TQDataStream::operator<<( TQ_INT16 i ) -{ - CHECK_STREAM_PRECOND - if ( printable ) { // printable data - char buf[16]; - sprintf( buf, "%d\n", i ); - dev->writeBlock( buf, strlen(buf) ); - } else if ( noswap ) { // no conversion needed - dev->writeBlock( (char *)&i, sizeof(TQ_INT16) ); - } else { // swap bytes - uchar *p = (uchar *)(&i); - char b[2]; - b[1] = *p++; - b[0] = *p; - dev->writeBlock( b, 2 ); - } - return *this; -} - -/*! - \overload - - Writes a signed 32-bit integer, \a i, to the stream and returns a - reference to the stream. -*/ - -TQDataStream &TQDataStream::operator<<( TQ_INT32 i ) -{ - CHECK_STREAM_PRECOND - if ( printable ) { // printable data - char buf[16]; - sprintf( buf, "%d\n", i ); - dev->writeBlock( buf, strlen(buf) ); - } else if ( noswap ) { // no conversion needed - dev->writeBlock( (char *)&i, sizeof(TQ_INT32) ); - } else { // swap bytes - uchar *p = (uchar *)(&i); - char b[4]; - b[3] = *p++; - b[2] = *p++; - b[1] = *p++; - b[0] = *p; - dev->writeBlock( b, 4 ); - } - return *this; -} - -/*! - \overload TQDataStream &TQDataStream::operator<<( TQ_UINT64 i ) - - Writes an unsigned 64-bit integer, \a i, to the stream and returns a - reference to the stream. -*/ - -/*! - \overload - - Writes a signed 64-bit integer, \a i, to the stream and returns a - reference to the stream. -*/ - -TQDataStream &TQDataStream::operator<<( TQ_INT64 i ) -{ - CHECK_STREAM_PRECOND - if ( printable ) { // printable data - char buf[16]; -#ifdef Q_OS_WIN - sprintf( buf, "%I64d\n", i ); -#else - sprintf( buf, "%lld\n", i ); -#endif - dev->writeBlock( buf, strlen(buf) ); - } else if ( version() < 6 ) { - TQ_UINT32 i1 = i & 0xffffffff; - TQ_UINT32 i2 = i >> 32; - *this << i2 << i1; - } else if ( noswap ) { // no conversion needed - dev->writeBlock( (char *)&i, sizeof(TQ_INT64) ); - } else { // swap bytes - uchar *p = (uchar *)(&i); - char b[8]; - b[7] = *p++; - b[6] = *p++; - b[5] = *p++; - b[4] = *p++; - b[3] = *p++; - b[2] = *p++; - b[1] = *p++; - b[0] = *p; - dev->writeBlock( b, 8 ); - } - return *this; -} - -/*! - \overload TQDataStream &TQDataStream::operator<<( TQ_ULONG i ) - - Writes an unsigned integer \a i, of the system's word length, to - the stream and returns a reference to the stream. -*/ - -#if !defined(Q_OS_WIN64) -/*! - \overload - - Writes a signed integer \a i, of the system's word length, to the - stream and returns a reference to the stream. -*/ - -TQDataStream &TQDataStream::operator<<( TQ_LONG i ) -{ - CHECK_STREAM_PRECOND - if ( printable ) { // printable data - char buf[20]; - sprintf( buf, "%ld\n", i ); - dev->writeBlock( buf, strlen(buf) ); - } else if ( noswap ) { // no conversion needed - dev->writeBlock( (char *)&i, sizeof(TQ_LONG) ); - } else { // swap bytes - uchar *p = (uchar *)(&i); - char b[sizeof(TQ_LONG)]; - for ( int j = sizeof(TQ_LONG); j; ) - b[--j] = *p++; - dev->writeBlock( b, sizeof(TQ_LONG) ); - } - return *this; -} -#endif - - -/*! - \overload TQDataStream &TQDataStream::operator<<( TQ_UINT32 i ) - - Writes an unsigned integer, \a i, to the stream as a 32-bit - unsigned integer (TQ_UINT32). Returns a reference to the stream. -*/ - -/*! - \overload - - Writes a 32-bit floating point number, \a f, to the stream using - the standard IEEE754 format. Returns a reference to the stream. -*/ - -TQDataStream &TQDataStream::operator<<( float f ) -{ - CHECK_STREAM_PRECOND - if ( printable ) { // printable data - TQString num = TQString::number((double)f); - dev->writeBlock(num.latin1(), num.length()); - dev->putch('\n'); - } else { - float g = f; // fixes float-on-stack problem - if ( noswap ) { // no conversion needed - dev->writeBlock( (char *)&g, sizeof(float) ); - } else { // swap bytes - uchar *p = (uchar *)(&g); - char b[4]; - b[3] = *p++; - b[2] = *p++; - b[1] = *p++; - b[0] = *p; - dev->writeBlock( b, 4 ); - } - } - return *this; -} - - -/*! - \overload - - Writes a 64-bit floating point number, \a f, to the stream using - the standard IEEE754 format. Returns a reference to the stream. -*/ - -TQDataStream &TQDataStream::operator<<( double f ) -{ - CHECK_STREAM_PRECOND - if ( printable ) { // printable data - TQString num = TQString::number((double)f); - dev->writeBlock(num.latin1(), num.length()); - dev->putch('\n'); - } else if ( noswap ) { // no conversion needed - dev->writeBlock( (char *)&f, sizeof(double) ); - } else { // swap bytes - uchar *p = (uchar *)(&f); - char b[8]; - b[7] = *p++; - b[6] = *p++; - b[5] = *p++; - b[4] = *p++; - b[3] = *p++; - b[2] = *p++; - b[1] = *p++; - b[0] = *p; - dev->writeBlock( b, 8 ); - } - return *this; -} - - -/*! - \overload - - Writes the '\0'-terminated string \a s to the stream and returns a - reference to the stream. - - The string is serialized using writeBytes(). -*/ - -TQDataStream &TQDataStream::operator<<( const char *s ) -{ - if ( !s ) { - *this << (TQ_UINT32)0; - return *this; - } - uint len = tqstrlen( s ) + 1; // also write null terminator - *this << (TQ_UINT32)len; // write length specifier - return writeRawBytes( s, len ); -} - - -/*! - Writes the length specifier \a len and the buffer \a s to the - stream and returns a reference to the stream. - - The \a len is serialized as a TQ_UINT32, followed by \a len bytes - from \a s. Note that the data is \e not encoded. - - \sa writeRawBytes(), readBytes() -*/ - -TQDataStream &TQDataStream::writeBytes(const char *s, uint len) -{ - CHECK_STREAM_PRECOND - *this << (TQ_UINT32)len; // write length specifier - if ( len ) - writeRawBytes( s, len ); - return *this; -} - - -/*! - Writes \a len bytes from \a s to the stream and returns a - reference to the stream. The data is \e not encoded. - - \sa writeBytes(), TQIODevice::writeBlock(), readRawBytes() -*/ - -TQDataStream &TQDataStream::writeRawBytes( const char *s, uint len ) -{ - CHECK_STREAM_PRECOND - if ( printable ) { // write printable - if ( version() < 4 ) { - char *p = (char *)s; - while ( len-- ) - *this << *p++; - } else { - TQ_INT8 *p = (TQ_INT8*)s; - while ( len-- ) - *this << *p++; - } - } else { // write data char array - dev->writeBlock( s, len ); - } - return *this; -} - -#endif // TQT_NO_DATASTREAM diff --git a/src/tools/qdir.cpp b/src/tools/qdir.cpp deleted file mode 100644 index 4ca6be4aa..000000000 --- a/src/tools/qdir.cpp +++ /dev/null @@ -1,1390 +0,0 @@ -/**************************************************************************** -** -** Implementation of TQDir class -** -** Created : 950427 -** -** Copyright (C) 1992-2008 Trolltech ASA. All rights reserved. -** -** This file is part of the tools module of the TQt GUI Toolkit. -** -** This file may be used under the terms of the GNU General -** Public License versions 2.0 or 3.0 as published by the Free -** Software Foundation and appearing in the files LICENSE.GPL2 -** and LICENSE.GPL3 included in the packaging of this file. -** Alternatively you may (at your option) use any later version -** of the GNU General Public License if such license has been -** publicly approved by Trolltech ASA (or its successors, if any) -** and the KDE Free TQt Foundation. -** -** Please review the following information to ensure GNU General -** Public Licensing requirements will be met: -** http://trolltech.com/products/qt/licenses/licensing/opensource/. -** If you are unsure which license is appropriate for your use, please -** review the following information: -** http://trolltech.com/products/qt/licenses/licensing/licensingoverview -** or contact the sales department at sales@trolltech.com. -** -** This file may be used under the terms of the Q Public License as -** defined by Trolltech ASA and appearing in the file LICENSE.TQPL -** included in the packaging of this file. Licensees holding valid TQt -** Commercial licenses may use this file in accordance with the TQt -** Commercial License Agreement provided with the Software. -** -** This file is provided "AS IS" with NO WARRANTY OF ANY KIND, -** INCLUDING THE WARRANTIES OF DESIGN, MERCHANTABILITY AND FITNESS FOR -** A PARTICULAR PURPOSE. Trolltech reserves all rights not granted -** herein. -** -**********************************************************************/ - -#include "qplatformdefs.h" -#include "ntqdir.h" - -#ifndef TQT_NO_DIR -#include -#include "ntqfileinfo.h" -#include "tqregexp.h" -#include "tqstringlist.h" -#include "tqdeepcopy.h" -#include - -#if defined(Q_FS_FAT) && !defined(Q_OS_UNIX) -const bool CaseSensitiveFS = FALSE; -#else -const bool CaseSensitiveFS = TRUE; -#endif - - -/*! - \class TQDir - \reentrant - \brief The TQDir class provides access to directory structures and their contents in a platform-independent way. - - \ingroup io - \mainclass - - A TQDir is used to manipulate path names, access information - regarding paths and files, and manipulate the underlying file - system. - - A TQDir can point to a file using either a relative or an absolute - path. Absolute paths begin with the directory separator "/" - (optionally preceded by a drive specification under Windows). If - you always use "/" as a directory separator, TQt will translate - your paths to conform to the underlying operating system. Relative - file names begin with a directory name or a file name and specify - a path relative to the current directory. - - The "current" path refers to the application's working directory. - A TQDir's own path is set and retrieved with setPath() and path(). - - An example of an absolute path is the string "/tmp/quartz", a - relative path might look like "src/fatlib". You can use the - function isRelative() to check if a TQDir is using a relative or an - absolute file path. Call convertToAbs() to convert a relative TQDir - to an absolute one. For a simplified path use cleanDirPath(). To - obtain a path which has no symbolic links or redundant ".." - elements use canonicalPath(). The path can be set with setPath(), - and changed with cd() and cdUp(). - - TQDir provides several static functions, for example, setCurrent() - to set the application's working directory and currentDirPath() to - retrieve the application's working directory. Access to some - common paths is provided with the static functions, current(), - home() and root() which return TQDir objects or currentDirPath(), - homeDirPath() and rootDirPath() which return the path as a string. - If you want to know about your application's path use - \l{TQApplication::applicationDirPath()}. - - The number of entries in a directory is returned by count(). - Obtain a string list of the names of all the files and directories - in a directory with entryList(). If you prefer a list of TQFileInfo - pointers use entryInfoList(). Both these functions can apply a - name filter, an attributes filter (e.g. read-only, files not - directories, etc.), and a sort order. The filters and sort may be - set with calls to setNameFilter(), setFilter() and setSorting(). - They may also be specified in the entryList() and - entryInfoList()'s arguments. - - Create a new directory with mkdir(), rename a directory with - rename() and remove an existing directory with rmdir(). Remove a - file with remove(). You can interrogate a directory with exists(), - isReadable() and isRoot(). - - To get a path with a filename use filePath(), and to get a - directory name use dirName(); neither of these functions checks - for the existence of the file or directory. - - The list of root directories is provided by drives(); on Unix - systems this returns a list containing one root directory, "/"; on - Windows the list will usually contain "C:/", and possibly "D:/", - etc. - - It is easiest to work with "/" separators in TQt code. If you need - to present a path to the user or need a path in a form suitable - for a function in the underlying operating system use - convertSeparators(). - - Examples: - - See if a directory exists. - \code - TQDir d( "example" ); // "./example" - if ( !d.exists() ) - tqWarning( "Cannot find the example directory" ); - \endcode - - Traversing directories and reading a file. - \code - TQDir d = TQDir::root(); // "/" - if ( !d.cd("tmp") ) { // "/tmp" - tqWarning( "Cannot find the \"/tmp\" directory" ); - } else { - TQFile f( d.filePath("ex1.txt") ); // "/tmp/ex1.txt" - if ( !f.open(IO_ReadWrite) ) - tqWarning( "Cannot create the file %s", f.name() ); - } - \endcode - - A program that lists all the files in the current directory - (excluding symbolic links), sorted by size, smallest first: - \code - #include - #include - - int main( int argc, char **argv ) - { - TQDir d; - d.setFilter( TQDir::Files | TQDir::Hidden | TQDir::NoSymLinks ); - d.setSorting( TQDir::Size | TQDir::Reversed ); - - const TQFileInfoList *list = d.entryInfoList(); - TQFileInfoListIterator it( *list ); - TQFileInfo *fi; - - printf( " Bytes Filename\n" ); - while ( (fi = it.current()) != 0 ) { - printf( "%10li %s\n", fi->size(), fi->fileName().latin1() ); - ++it; - } - return 0; - } - \endcode - - \sa TQApplication::applicationDirPath() -*/ - -/*! - Constructs a TQDir pointing to the current directory ("."). - - \sa currentDirPath() -*/ - -TQDir::TQDir() -{ - dPath = TQString::fromLatin1("."); - init(); -} - -/*! - Constructs a TQDir with path \a path, that filters its entries by - name using \a nameFilter and by attributes using \a filterSpec. It - also sorts the names using \a sortSpec. - - The default \a nameFilter is an empty string, which excludes - nothing; the default \a filterSpec is \c All, which also means - exclude nothing. The default \a sortSpec is \c Name|IgnoreCase, - i.e. sort by name case-insensitively. - - Example that lists all the files in "/tmp": - \code - TQDir d( "/tmp" ); - for ( int i = 0; i < d.count(); i++ ) - printf( "%s\n", d[i] ); - \endcode - - If \a path is "" or TQString::null, TQDir uses "." (the current - directory). If \a nameFilter is "" or TQString::null, TQDir uses the - name filter "*" (all files). - - Note that \a path need not exist. - - \sa exists(), setPath(), setNameFilter(), setFilter(), setSorting() -*/ - -TQDir::TQDir( const TQString &path, const TQString &nameFilter, - int sortSpec, int filterSpec ) -{ - init(); - dPath = cleanDirPath( path ); - if ( dPath.isEmpty() ) - dPath = TQString::fromLatin1("."); - nameFilt = nameFilter; - if ( nameFilt.isEmpty() ) - nameFilt = TQString::fromLatin1("*"); - filtS = (FilterSpec)filterSpec; - sortS = (SortSpec)sortSpec; -} - -/*! - Constructs a TQDir that is a copy of the directory \a d. - - \sa operator=() -*/ - -TQDir::TQDir( const TQDir &d ) -{ - dPath = d.dPath; - fList = 0; - fiList = 0; - nameFilt = d.nameFilt; - dirty = TRUE; - allDirs = d.allDirs; - filtS = d.filtS; - sortS = d.sortS; -} - -/*! - Refreshes the directory information. -*/ -void TQDir::refresh() const -{ - TQDir* that = (TQDir*) this; - that->dirty = TRUE; -} - -void TQDir::init() -{ - fList = 0; - fiList = 0; - nameFilt = TQString::fromLatin1("*"); - dirty = TRUE; - allDirs = FALSE; - filtS = All; - sortS = SortSpec(Name | IgnoreCase); -} - -/*! - Destroys the TQDir frees up its resources. -*/ - -TQDir::~TQDir() -{ - delete fList; - delete fiList; -} - - -/*! - Sets the path of the directory to \a path. The path is cleaned of - redundant ".", ".." and of multiple separators. No check is made - to ensure that a directory with this path exists. - - The path can be either absolute or relative. Absolute paths begin - with the directory separator "/" (optionally preceded by a drive - specification under Windows). Relative file names begin with a - directory name or a file name and specify a path relative to the - current directory. An example of an absolute path is the string - "/tmp/quartz", a relative path might look like "src/fatlib". - - \sa path(), absPath(), exists(), cleanDirPath(), dirName(), - absFilePath(), isRelative(), convertToAbs() -*/ - -void TQDir::setPath( const TQString &path ) -{ - dPath = cleanDirPath( path ); - if ( dPath.isEmpty() ) - dPath = TQString::fromLatin1("."); - dirty = TRUE; -} - -/*! - \fn TQString TQDir::path() const - - Returns the path, this may contain symbolic links, but never - contains redundant ".", ".." or multiple separators. - - The returned path can be either absolute or relative (see - setPath()). - - \sa setPath(), absPath(), exists(), cleanDirPath(), dirName(), - absFilePath(), convertSeparators() -*/ - -/*! - Returns the absolute path (a path that starts with "/" or with a - drive specification), which may contain symbolic links, but never - contains redundant ".", ".." or multiple separators. - - \sa setPath(), canonicalPath(), exists(), cleanDirPath(), - dirName(), absFilePath() -*/ - -TQString TQDir::absPath() const -{ - if ( TQDir::isRelativePath(dPath) ) { - TQString tmp = currentDirPath(); - if ( tmp.right(1) != TQString::fromLatin1("/") ) - tmp += '/'; - tmp += dPath; - return cleanDirPath( tmp ); - } else { - return cleanDirPath( dPath ); - } -} - -/*! - Returns the name of the directory; this is \e not the same as the - path, e.g. a directory with the name "mail", might have the path - "/var/spool/mail". If the directory has no name (e.g. it is the - root directory) TQString::null is returned. - - No check is made to ensure that a directory with this name - actually exists. - - \sa path(), absPath(), absFilePath(), exists(), TQString::isNull() -*/ - -TQString TQDir::dirName() const -{ - int pos = dPath.findRev( '/' ); - if ( pos == -1 ) - return dPath; - return dPath.right( dPath.length() - pos - 1 ); -} - -/*! - Returns the path name of a file in the directory. Does \e not - check if the file actually exists in the directory. If the TQDir is - relative the returned path name will also be relative. Redundant - multiple separators or "." and ".." directories in \a fileName - will not be removed (see cleanDirPath()). - - If \a acceptAbsPath is TRUE a \a fileName starting with a - separator "/" will be returned without change. If \a acceptAbsPath - is FALSE an absolute path will be prepended to the fileName and - the resultant string returned. - - \sa absFilePath(), isRelative(), canonicalPath() -*/ - -TQString TQDir::filePath( const TQString &fileName, - bool acceptAbsPath ) const -{ - if ( acceptAbsPath && !isRelativePath(fileName) ) - return TQString(fileName); - - TQString tmp = dPath; - if ( tmp.isEmpty() || (tmp[(int)tmp.length()-1] != '/' && !!fileName && - fileName[0] != '/') ) - tmp += '/'; - tmp += fileName; - return tmp; -} - -/*! - Returns the absolute path name of a file in the directory. Does \e - not check if the file actually exists in the directory. Redundant - multiple separators or "." and ".." directories in \a fileName - will not be removed (see cleanDirPath()). - - If \a acceptAbsPath is TRUE a \a fileName starting with a - separator "/" will be returned without change. If \a acceptAbsPath - is FALSE an absolute path will be prepended to the fileName and - the resultant string returned. - - \sa filePath() -*/ - -TQString TQDir::absFilePath( const TQString &fileName, - bool acceptAbsPath ) const -{ - if ( acceptAbsPath && !isRelativePath( fileName ) ) - return fileName; - - TQString tmp = absPath(); -#ifdef Q_OS_WIN32 - if ( fileName[0].isLetter() && fileName[1] == ':' ) { - int drv = fileName.upper()[0].latin1() - 'A' + 1; - if ( _getdrive() != drv ) { - QT_WA( { - TCHAR buf[PATH_MAX]; - ::_wgetdcwd( drv, buf, PATH_MAX ); - tmp.setUnicodeCodes( (ushort*)buf, (uint)::wcslen(buf) ); - }, { - char buf[PATH_MAX]; - ::_getdcwd( drv, buf, PATH_MAX ); - tmp = buf; - } ); - if ( !tmp.endsWith("\\") ) - tmp += "\\"; - tmp += fileName.right( fileName.length() - 2 ); - int x; - for ( x = 0; x < (int) tmp.length(); x++ ) { - if ( tmp[x] == '\\' ) - tmp[x] = '/'; - } - } - } else -#endif - { - if ( tmp.isEmpty() || (tmp[(int)tmp.length()-1] != '/' && !!fileName && - fileName[0] != '/') ) - tmp += '/'; - tmp += fileName; - } - return tmp; -} - - -/*! - Returns \a pathName with the '/' separators converted to - separators that are appropriate for the underlying operating - system. - - On Windows, convertSeparators("c:/winnt/system32") returns - "c:\winnt\system32". - - The returned string may be the same as the argument on some - operating systems, for example on Unix. -*/ - -TQString TQDir::convertSeparators( const TQString &pathName ) -{ - TQString n( pathName ); -#if defined(Q_FS_FAT) || defined(Q_OS_OS2EMX) - for ( int i=0; i<(int)n.length(); i++ ) { - if ( n[i] == '/' ) - n[i] = '\\'; - } -#elif defined(Q_OS_MAC9) - while(n.length() && n[0] == '/' ) n = n.right(n.length()-1); - for ( int i=0; i<(int)n.length(); i++ ) { - if ( n[i] == '/' ) - n[i] = ':'; - } - if(n.contains(':') && n.left(1) != ':') - n.prepend(':'); -#endif - return n; -} - - -/*! - Changes the TQDir's directory to \a dirName. - - If \a acceptAbsPath is TRUE a path starting with separator "/" - will cause the function to change to the absolute directory. If \a - acceptAbsPath is FALSE any number of separators at the beginning - of \a dirName will be removed and the function will descend into - \a dirName. - - Returns TRUE if the new directory exists and is readable; - otherwise returns FALSE. Note that the logical cd() operation is - not performed if the new directory does not exist. - - Calling cd( ".." ) is equivalent to calling cdUp(). - - \sa cdUp(), isReadable(), exists(), path() -*/ - -bool TQDir::cd( const TQString &dirName, bool acceptAbsPath ) -{ - if ( dirName.isEmpty() || dirName == TQString::fromLatin1(".") ) - return TRUE; - TQString old = dPath; - if ( acceptAbsPath && !isRelativePath(dirName) ) { - dPath = cleanDirPath( dirName ); - } else { - if ( isRoot() ) { - if ( dirName == ".." ) { - dPath = old; - return FALSE; - } - } else { - dPath += '/'; - } - - dPath += dirName; - if ( dirName.find('/') >= 0 - || old == TQString::fromLatin1(".") - || dirName == TQString::fromLatin1("..") ) { - dPath = cleanDirPath( dPath ); - - /* - If dPath starts with .., we convert it to absolute to - avoid infinite looping on - - TQDir dir( "." ); - while ( dir.cdUp() ) - ; - */ - if ( dPath[0] == TQChar('.') && dPath[1] == TQChar('.') && - (dPath.length() == 2 || dPath[2] == TQChar('/')) ) - convertToAbs(); - } - } - if ( !exists() ) { - dPath = old; // regret - return FALSE; - } - dirty = TRUE; - return TRUE; -} - -/*! - Changes directory by moving one directory up from the TQDir's - current directory. - - Returns TRUE if the new directory exists and is readable; - otherwise returns FALSE. Note that the logical cdUp() operation is - not performed if the new directory does not exist. - - \sa cd(), isReadable(), exists(), path() -*/ - -bool TQDir::cdUp() -{ - return cd( TQString::fromLatin1("..") ); -} - -/*! - \fn TQString TQDir::nameFilter() const - - Returns the string set by setNameFilter() -*/ - -/*! - Sets the name filter used by entryList() and entryInfoList() to \a - nameFilter. - - The \a nameFilter is a wildcard (globbing) filter that understands - "*" and "?" wildcards. (See \link tqregexp.html#wildcard-matching - TQRegExp wildcard matching\endlink.) You may specify several filter - entries all separated by a single space " " or by a semi-colon - ";". - - For example, if you want entryList() and entryInfoList() to list - all files ending with either ".cpp" or ".h", you would use either - dir.setNameFilter("*.cpp *.h") or dir.setNameFilter("*.cpp;*.h"). - - \sa nameFilter(), setFilter() -*/ - -void TQDir::setNameFilter( const TQString &nameFilter ) -{ - nameFilt = nameFilter; - if ( nameFilt.isEmpty() ) - nameFilt = TQString::fromLatin1("*"); - dirty = TRUE; -} - -/*! - \fn TQDir::FilterSpec TQDir::filter() const - - Returns the value set by setFilter() -*/ - -/*! - \enum TQDir::FilterSpec - - This enum describes the filtering options available to TQDir, e.g. - for entryList() and entryInfoList(). The filter value is specified - by OR-ing together values from the following list: - - \value Dirs List directories only. - \value Files List files only. - \value Drives List disk drives (ignored under Unix). - \value NoSymLinks Do not list symbolic links (ignored by operating - systems that don't support symbolic links). - \value All List directories, files, drives and symlinks (this does not list - broken symlinks unless you specify System). - \value TypeMask A mask for the the Dirs, Files, Drives and - NoSymLinks flags. - \value Readable List files for which the application has read access. - \value Writable List files for which the application has write access. - \value Executable List files for which the application has execute - access. Executables needs to be combined with Dirs or Files. - \value RWEMask A mask for the Readable, Writable and Executable flags. - \value Modified Only list files that have been modified (ignored - under Unix). - \value Hidden List hidden files (on Unix, files starting with a .). - \value System List system files (on Unix, FIFOs, sockets and - device files) - \value AccessMask A mask for the Readable, Writable, Executable - Modified, Hidden and System flags - \value DefaultFilter Internal flag. - - If you do not set any of \c Readable, \c Writable or \c - Executable, TQDir will set all three of them. This makes the - default easy to write and at the same time useful. - - Examples: \c Readable|Writable means list all files for which the - application has read access, write access or both. \c Dirs|Drives - means list drives, directories, all files that the application can - read, write or execute, and also symlinks to such - files/directories. -*/ - - -/*! - Sets the filter used by entryList() and entryInfoList() to \a - filterSpec. The filter is used to specify the kind of files that - should be returned by entryList() and entryInfoList(). See - \l{TQDir::FilterSpec}. - - \sa filter(), setNameFilter() -*/ - -void TQDir::setFilter( int filterSpec ) -{ - if ( filtS == (FilterSpec) filterSpec ) - return; - filtS = (FilterSpec) filterSpec; - dirty = TRUE; -} - -/*! - \fn TQDir::SortSpec TQDir::sorting() const - - Returns the value set by setSorting() - - \sa setSorting() SortSpec -*/ - -/*! - \enum TQDir::SortSpec - - This enum describes the sort options available to TQDir, e.g. for - entryList() and entryInfoList(). The sort value is specified by - OR-ing together values from the following list: - - \value Name Sort by name. - \value Time Sort by time (modification time). - \value Size Sort by file size. - \value Unsorted Do not sort. - \value SortByMask A mask for Name, Time and Size. - - \value DirsFirst Put the directories first, then the files. - \value Reversed Reverse the sort order. - \value IgnoreCase Sort case-insensitively. - \value LocaleAware Sort names using locale aware compares - \value DefaultSort Internal flag. - - You can only specify one of the first four. - - If you specify both \c DirsFirst and \c Reversed, directories are - still put first, but in reverse order; the files will be listed - after the directories, again in reverse order. -*/ - -// ### Unsorted+DirsFirst ? Unsorted+Reversed? - -/*! - Sets the sort order used by entryList() and entryInfoList(). - - The \a sortSpec is specified by OR-ing values from the enum - \l{TQDir::SortSpec}. - - \sa sorting() SortSpec -*/ - -void TQDir::setSorting( int sortSpec ) -{ - if ( sortS == (SortSpec) sortSpec ) - return; - sortS = (SortSpec) sortSpec; - dirty = TRUE; -} - -/*! - \fn bool TQDir::matchAllDirs() const - - Returns the value set by setMatchAllDirs() - - \sa setMatchAllDirs() -*/ - -/*! - If \a enable is TRUE then all directories are included (e.g. in - entryList()), and the nameFilter() is only applied to the files. - If \a enable is FALSE then the nameFilter() is applied to both - directories and files. - - \sa matchAllDirs() -*/ - -void TQDir::setMatchAllDirs( bool enable ) -{ - if ( (bool)allDirs == enable ) - return; - allDirs = enable; - dirty = TRUE; -} - - -/*! - Returns the total number of directories and files that were found. - - Equivalent to entryList().count(). - - \sa operator[](), entryList() -*/ - -uint TQDir::count() const -{ - return (uint)entryList().count(); -} - -/*! - Returns the file name at position \a index in the list of file - names. Equivalent to entryList().at(index). - - Returns a TQString::null if the \a index is out of range or if the - entryList() function failed. - - \sa count(), entryList() -*/ - -TQString TQDir::operator[]( int index ) const -{ - entryList(); - return fList && index >= 0 && index < (int)fList->count() ? - (*fList)[index] : TQString::null; -} - - -/*! - \obsolete - This function is included to easy porting from TQt 1.x to TQt 2.0, - it is the same as entryList(), but encodes the filenames as 8-bit - strings using TQFile::encodedName(). - - It is more efficient to use entryList(). -*/ -TQStrList TQDir::encodedEntryList( int filterSpec, int sortSpec ) const -{ - TQStrList r; - TQStringList l = entryList(filterSpec,sortSpec); - for ( TQStringList::Iterator it = l.begin(); it != l.end(); ++it ) { - r.append( TQFile::encodeName(*it) ); - } - return r; -} - -/*! - \obsolete - \overload - This function is included to easy porting from TQt 1.x to TQt 2.0, - it is the same as entryList(), but encodes the filenames as 8-bit - strings using TQFile::encodedName(). - - It is more efficient to use entryList(). -*/ -TQStrList TQDir::encodedEntryList( const TQString &nameFilter, - int filterSpec, - int sortSpec ) const -{ - TQStrList r; - TQStringList l = entryList(nameFilter,filterSpec,sortSpec); - for ( TQStringList::Iterator it = l.begin(); it != l.end(); ++it ) { - r.append( TQFile::encodeName(*it) ); - } - return r; -} - - - -/*! - \overload - - Returns a list of the names of all the files and directories in - the directory, ordered in accordance with setSorting() and - filtered in accordance with setFilter() and setNameFilter(). - - The filter and sorting specifications can be overridden using the - \a filterSpec and \a sortSpec arguments. - - Returns an empty list if the directory is unreadable or does not - exist. - - \sa entryInfoList(), setNameFilter(), setSorting(), setFilter() -*/ - -TQStringList TQDir::entryList( int filterSpec, int sortSpec ) const -{ - if ( !dirty && filterSpec == (int)DefaultFilter && - sortSpec == (int)DefaultSort ) - return *fList; - return entryList( nameFilt, filterSpec, sortSpec ); -} - -/*! - Returns a list of the names of all the files and directories in - the directory, ordered in accordance with setSorting() and - filtered in accordance with setFilter() and setNameFilter(). - - The filter and sorting specifications can be overridden using the - \a nameFilter, \a filterSpec and \a sortSpec arguments. - - Returns an empty list if the directory is unreadable or does not - exist. - - \sa entryInfoList(), setNameFilter(), setSorting(), setFilter() -*/ - -TQStringList TQDir::entryList( const TQString &nameFilter, - int filterSpec, int sortSpec ) const -{ - if ( filterSpec == (int)DefaultFilter ) - filterSpec = filtS; - if ( sortSpec == (int)DefaultSort ) - sortSpec = sortS; - TQDir *that = (TQDir*)this; // mutable function - if ( that->readDirEntries(nameFilter, filterSpec, sortSpec) ) { - if ( that->fList ) - return *that->fList; - } - return TQStringList(); -} - -/*! - \overload - - Returns a list of TQFileInfo objects for all the files and - directories in the directory, ordered in accordance with - setSorting() and filtered in accordance with setFilter() and - setNameFilter(). - - The filter and sorting specifications can be overridden using the - \a filterSpec and \a sortSpec arguments. - - Returns 0 if the directory is unreadable or does not exist. - - The returned pointer is a const pointer to a TQFileInfoList. The - list is owned by the TQDir object and will be reused on the next - call to entryInfoList() for the same TQDir instance. If you want to - keep the entries of the list after a subsequent call to this - function you must copy them. - - Note: TQFileInfoList is really a TQPtrList. - - \sa entryList(), setNameFilter(), setSorting(), setFilter() -*/ - -const TQFileInfoList *TQDir::entryInfoList( int filterSpec, int sortSpec ) const -{ - if ( !dirty && filterSpec == (int)DefaultFilter && - sortSpec == (int)DefaultSort ) - return fiList; - return entryInfoList( nameFilt, filterSpec, sortSpec ); -} - -/*! - Returns a list of TQFileInfo objects for all the files and - directories in the directory, ordered in accordance with - setSorting() and filtered in accordance with setFilter() and - setNameFilter(). - - The filter and sorting specifications can be overridden using the - \a nameFilter, \a filterSpec and \a sortSpec arguments. - - Returns 0 if the directory is unreadable or does not exist. - - The returned pointer is a const pointer to a TQFileInfoList. The - list is owned by the TQDir object and will be reused on the next - call to entryInfoList() for the same TQDir instance. If you want to - keep the entries of the list after a subsequent call to this - function you must copy them. - - Note: TQFileInfoList is really a TQPtrList. - - \sa entryList(), setNameFilter(), setSorting(), setFilter() -*/ - -const TQFileInfoList *TQDir::entryInfoList( const TQString &nameFilter, - int filterSpec, int sortSpec ) const -{ - if ( filterSpec == (int)DefaultFilter ) - filterSpec = filtS; - if ( sortSpec == (int)DefaultSort ) - sortSpec = sortS; - TQDir *that = (TQDir*)this; // mutable function - if ( that->readDirEntries(nameFilter, filterSpec, sortSpec) ) - return that->fiList; - else - return 0; -} - -/*! - \overload - - Returns TRUE if the \e directory exists; otherwise returns FALSE. - (If a file with the same name is found this function will return - FALSE). - - \sa TQFileInfo::exists(), TQFile::exists() -*/ - -bool TQDir::exists() const -{ - TQFileInfo fi( dPath ); - return fi.exists() && fi.isDir(); -} - -/*! - Returns TRUE if the directory path is relative to the current - directory and returns FALSE if the path is absolute (e.g. under - UNIX a path is relative if it does not start with a "/"). - - \sa convertToAbs() -*/ - -bool TQDir::isRelative() const -{ - return isRelativePath( dPath ); -} - -/*! - Converts the directory path to an absolute path. If it is already - absolute nothing is done. - - \sa isRelative() -*/ - -void TQDir::convertToAbs() -{ - dPath = absPath(); -} - -/*! - Makes a copy of TQDir \a d and assigns it to this TQDir. -*/ - -TQDir &TQDir::operator=( const TQDir &d ) -{ - dPath = d.dPath; - delete fList; - fList = 0; - delete fiList; - fiList = 0; - nameFilt = d.nameFilt; - dirty = TRUE; - allDirs = d.allDirs; - filtS = d.filtS; - sortS = d.sortS; - return *this; -} - -/*! - \overload - - Sets the directory path to be the given \a path. -*/ - -TQDir &TQDir::operator=( const TQString &path ) -{ - dPath = cleanDirPath( path ); - dirty = TRUE; - return *this; -} - - -/*! - \fn bool TQDir::operator!=( const TQDir &d ) const - - Returns TRUE if directory \a d and this directory have different - paths or different sort or filter settings; otherwise returns - FALSE. - - Example: - \code - // The current directory is "/usr/local" - TQDir d1( "/usr/local/bin" ); - TQDir d2( "bin" ); - if ( d1 != d2 ) - tqDebug( "They differ" ); - \endcode -*/ - -/*! - Returns TRUE if directory \a d and this directory have the same - path and their sort and filter settings are the same; otherwise - returns FALSE. - - Example: - \code - // The current directory is "/usr/local" - TQDir d1( "/usr/local/bin" ); - TQDir d2( "bin" ); - d2.convertToAbs(); - if ( d1 == d2 ) - tqDebug( "They're the same" ); - \endcode -*/ - -bool TQDir::operator==( const TQDir &d ) const -{ - return dPath == d.dPath && - nameFilt == d.nameFilt && - allDirs == d.allDirs && - filtS == d.filtS && - sortS == d.sortS; -} - - -/*! - Removes the file, \a fileName. - - If \a acceptAbsPath is TRUE a path starting with separator "/" - will remove the file with the absolute path. If \a acceptAbsPath - is FALSE any number of separators at the beginning of \a fileName - will be removed and the resultant file name will be removed. - - Returns TRUE if the file is removed successfully; otherwise - returns FALSE. -*/ - -bool TQDir::remove( const TQString &fileName, bool acceptAbsPath ) -{ - if ( fileName.isEmpty() ) { -#if defined(QT_CHECK_NULL) - tqWarning( "TQDir::remove: Empty or null file name" ); -#endif - return FALSE; - } - TQString p = filePath( fileName, acceptAbsPath ); - return TQFile::remove( p ); -} - -/*! - Checks for the existence of the file \a name. - - If \a acceptAbsPath is TRUE a path starting with separator "/" - will check the file with the absolute path. If \a acceptAbsPath is - FALSE any number of separators at the beginning of \a name will be - removed and the resultant file name will be checked. - - Returns TRUE if the file exists; otherwise returns FALSE. - - \sa TQFileInfo::exists(), TQFile::exists() -*/ - -bool TQDir::exists( const TQString &name, bool acceptAbsPath ) //### const in 4.0 -{ - if ( name.isEmpty() ) { -#if defined(QT_CHECK_NULL) - tqWarning( "TQDir::exists: Empty or null file name" ); -#endif - return FALSE; - } - TQString tmp = filePath( name, acceptAbsPath ); - return TQFile::exists( tmp ); -} - -/*! - Returns the native directory separator; "/" under UNIX (including - Mac OS X) and "\" under Windows. - - You do not need to use this function to build file paths. If you - always use "/", TQt will translate your paths to conform to the - underlying operating system. -*/ - -char TQDir::separator() -{ -#if defined(Q_OS_UNIX) - return '/'; -#elif defined (Q_FS_FAT) || defined(TQ_WS_WIN) - return '\\'; -#elif defined (Q_OS_MAC) - return ':'; -#else - return '/'; -#endif -} - -/*! - Returns the application's current directory. - - Use path() to access a TQDir object's path. - - \sa currentDirPath(), TQDir::TQDir() -*/ - -TQDir TQDir::current() -{ - return TQDir( currentDirPath() ); -} - -/*! - Returns the home directory. - - Under Windows the \c HOME environment variable is used. If this - does not exist the \c USERPROFILE environment variable is used. If - that does not exist the path is formed by concatenating the \c - HOMEDRIVE and \c HOMEPATH environment variables. If they don't - exist the rootDirPath() is used (this uses the \c SystemDrive - environment variable). If none of these exist "C:\" is used. - - Under non-Windows operating systems the \c HOME environment - variable is used if it exists, otherwise rootDirPath() is used. - - \sa homeDirPath() -*/ - -TQDir TQDir::home() -{ - return TQDir( homeDirPath() ); -} - -/*! - Returns the root directory. - - \sa rootDirPath() drives() -*/ - -TQDir TQDir::root() -{ - return TQDir( rootDirPath() ); -} - -/*! - \fn TQString TQDir::homeDirPath() - - Returns the absolute path of the user's home directory. - - \sa home() -*/ - -TQValueList qt_makeFilterList( const TQString &filter ) -{ - TQValueList regExps; - if ( filter.isEmpty() ) - return regExps; - - TQChar sep( ';' ); - int i = filter.find( sep, 0 ); - if ( i == -1 && filter.find( ' ', 0 ) != -1 ) - sep = TQChar( ' ' ); - - TQStringList list = TQStringList::split( sep, filter ); - TQStringList::Iterator it = list.begin(); - while ( it != list.end() ) { - regExps << TQRegExp( (*it).stripWhiteSpace(), CaseSensitiveFS, TRUE ); - ++it; - } - return regExps; -} - -bool qt_matchFilterList( const TQValueList& filters, - const TQString &fileName ) -{ - TQValueList::ConstIterator rit = filters.begin(); - while ( rit != filters.end() ) { - if ( (*rit).exactMatch(fileName) ) - return TRUE; - ++rit; - } - return FALSE; -} - - -/*! - \overload - - Returns TRUE if the \a fileName matches any of the wildcard (glob) - patterns in the list of \a filters; otherwise returns FALSE. - - (See \link tqregexp.html#wildcard-matching TQRegExp wildcard - matching.\endlink) - \sa TQRegExp::match() -*/ - -bool TQDir::match( const TQStringList &filters, const TQString &fileName ) -{ - TQStringList::ConstIterator sit = filters.begin(); - while ( sit != filters.end() ) { - TQRegExp rx( *sit, CaseSensitiveFS, TRUE ); - if ( rx.exactMatch(fileName) ) - return TRUE; - ++sit; - } - return FALSE; -} - -/*! - Returns TRUE if the \a fileName matches the wildcard (glob) - pattern \a filter; otherwise returns FALSE. The \a filter may - contain multiple patterns separated by spaces or semicolons. - - (See \link tqregexp.html#wildcard-matching TQRegExp wildcard - matching.\endlink) - \sa TQRegExp::match() -*/ - -bool TQDir::match( const TQString &filter, const TQString &fileName ) -{ - return qt_matchFilterList( qt_makeFilterList(filter), fileName ); -} - - -/*! - Removes all multiple directory separators "/" and resolves any - "."s or ".."s found in the path, \a filePath. - - Symbolic links are kept. This function does not return the - canonical path, but rather the simplest version of the input. - For example, "./local" becomes "local", "local/../bin" becomes - "bin" and "/local/usr/../bin" becomes "/local/bin". - - \sa absPath() canonicalPath() -*/ - -TQString TQDir::cleanDirPath( const TQString &filePath ) -{ - TQString name = filePath; - TQString newPath; - - if ( name.isEmpty() ) - return name; - - slashify( name ); - - bool addedSeparator = isRelativePath( name ); - if ( addedSeparator ) - name.insert( 0, '/' ); - - int ePos, pos, upLevel; - - pos = ePos = name.length(); - upLevel = 0; - int len; - - while ( pos && (pos = name.findRev('/', pos - 1)) != -1 ) { - len = ePos - pos - 1; - if ( len == 2 && name.at(pos + 1) == '.' - && name.at(pos + 2) == '.' ) { - upLevel++; - } else { - if ( len != 0 && (len != 1 || name.at(pos + 1) != '.') ) { - if ( !upLevel ) - newPath = TQString::fromLatin1("/") - + name.mid(pos + 1, len) + newPath; - else - upLevel--; - } - } - ePos = pos; - } - if ( addedSeparator ) { - while ( upLevel-- ) - newPath.insert( 0, TQString::fromLatin1("/..") ); - if ( !newPath.isEmpty() ) - newPath.remove( (uint)0, (uint)1 ); - else - newPath = TQString::fromLatin1("."); - } else { - if ( newPath.isEmpty() ) - newPath = TQString::fromLatin1("/"); -#if defined(Q_FS_FAT) || defined(Q_OS_OS2EMX) - if ( name[0] == '/' ) { - if ( name[1] == '/' ) // "\\machine\x\ ..." - newPath.insert( 0, '/' ); - } else { - newPath = name.left(2) + newPath; - } -#endif - } - return newPath; -} - -int qt_cmp_si_sortSpec; - -#if defined(Q_C_CALLBACKS) -extern "C" { -#endif - -#ifdef Q_OS_TEMP -int __cdecl qt_cmp_si( const void *n1, const void *n2 ) -#else -int qt_cmp_si( const void *n1, const void *n2 ) -#endif -{ - if ( !n1 || !n2 ) - return 0; - - TQDirSortItem* f1 = (TQDirSortItem*)n1; - TQDirSortItem* f2 = (TQDirSortItem*)n2; - - if ( qt_cmp_si_sortSpec & TQDir::DirsFirst ) - if ( f1->item->isDir() != f2->item->isDir() ) - return f1->item->isDir() ? -1 : 1; - - int r = 0; - int sortBy = qt_cmp_si_sortSpec & TQDir::SortByMask; - - switch ( sortBy ) { - case TQDir::Time: - r = f1->item->lastModified().secsTo(f2->item->lastModified()); - break; - case TQDir::Size: - r = f2->item->size() - f1->item->size(); - break; - default: - ; - } - - if ( r == 0 && sortBy != TQDir::Unsorted ) { - // Still not sorted - sort by name - bool ic = qt_cmp_si_sortSpec & TQDir::IgnoreCase; - - if ( f1->filename_cache.isNull() ) - f1->filename_cache = ic ? f1->item->fileName().lower() - : f1->item->fileName(); - if ( f2->filename_cache.isNull() ) - f2->filename_cache = ic ? f2->item->fileName().lower() - : f2->item->fileName(); - - r = qt_cmp_si_sortSpec & TQDir::LocaleAware - ? f1->filename_cache.localeAwareCompare(f2->filename_cache) - : f1->filename_cache.compare(f2->filename_cache); - } - - if ( r == 0 ) { - // Enforce an order - the order the items appear in the array - r = (char*)n1 - (char*)n2; - } - - if ( qt_cmp_si_sortSpec & TQDir::Reversed ) - return -r; - else - return r; -} - -#if defined(Q_C_CALLBACKS) -} -#endif - -/*! \internal - Detaches all internal data. -*/ -void TQDir::detach() -{ - // deepcopy - dPath = TQDeepCopy(dPath); - nameFilt = TQDeepCopy(nameFilt); - - if ( fList ) - *fList = TQDeepCopy( *fList ); - - if ( fiList ) { - TQFileInfoList *newlist = new TQFileInfoList( *fiList ); - delete fiList; - fiList = newlist; - } -} - -#endif // TQT_NO_DIR diff --git a/src/tools/qdir_p.h b/src/tools/qdir_p.h deleted file mode 100644 index a0309648b..000000000 --- a/src/tools/qdir_p.h +++ /dev/null @@ -1,82 +0,0 @@ -/**************************************************************************** -** -** Definition of some private TQDir functions. -** -** Created : 001106 -** -** Copyright (C) 2005-2008 Trolltech ASA. All rights reserved. -** -** This file is part of the tools module of the TQt GUI Toolkit. -** -** This file may be used under the terms of the GNU General -** Public License versions 2.0 or 3.0 as published by the Free -** Software Foundation and appearing in the files LICENSE.GPL2 -** and LICENSE.GPL3 included in the packaging of this file. -** Alternatively you may (at your option) use any later version -** of the GNU General Public License if such license has been -** publicly approved by Trolltech ASA (or its successors, if any) -** and the KDE Free TQt Foundation. -** -** Please review the following information to ensure GNU General -** Public Licensing requirements will be met: -** http://trolltech.com/products/qt/licenses/licensing/opensource/. -** If you are unsure which license is appropriate for your use, please -** review the following information: -** http://trolltech.com/products/qt/licenses/licensing/licensingoverview -** or contact the sales department at sales@trolltech.com. -** -** This file may be used under the terms of the Q Public License as -** defined by Trolltech ASA and appearing in the file LICENSE.TQPL -** included in the packaging of this file. Licensees holding valid TQt -** Commercial licenses may use this file in accordance with the TQt -** Commercial License Agreement provided with the Software. -** -** This file is provided "AS IS" with NO WARRANTY OF ANY KIND, -** INCLUDING THE WARRANTIES OF DESIGN, MERCHANTABILITY AND FITNESS FOR -** A PARTICULAR PURPOSE. Trolltech reserves all rights not granted -** herein. -** -**********************************************************************/ - -#ifndef TQDIR_P_H -#define TQDIR_P_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the TQt API. It exists for the convenience -// of qdir.cpp and qdir_*.cpp. -// This header file may change from version to version without notice, -// or even be removed. -// -// We mean it. -// -// - -#ifndef QT_H -#include "tqregexp.h" -#include "tqvaluelist.h" -#endif // QT_H - -extern TQValueList qt_makeFilterList( const TQString & ); -extern bool qt_matchFilterList( const TQValueList &, const TQString & ); - -extern int qt_cmp_si_sortSpec; - -#if defined(Q_C_CALLBACKS) -extern "C" { -#endif - -#ifdef Q_OS_TEMP -extern int __cdecl qt_cmp_si( const void *, const void * ); -#else -extern int qt_cmp_si( const void *, const void * ); -#endif - -#if defined(Q_C_CALLBACKS) -} -#endif - - -#endif // TQDIR_P_H diff --git a/src/tools/qdir_unix.cpp b/src/tools/qdir_unix.cpp deleted file mode 100644 index e4418f8e6..000000000 --- a/src/tools/qdir_unix.cpp +++ /dev/null @@ -1,329 +0,0 @@ -/**************************************************************************** -** -** Implementation of TQDir class -** -** Created : 950628 -** -** Copyright (C) 1992-2008 Trolltech ASA. All rights reserved. -** -** This file is part of the tools module of the TQt GUI Toolkit. -** -** This file may be used under the terms of the GNU General -** Public License versions 2.0 or 3.0 as published by the Free -** Software Foundation and appearing in the files LICENSE.GPL2 -** and LICENSE.GPL3 included in the packaging of this file. -** Alternatively you may (at your option) use any later version -** of the GNU General Public License if such license has been -** publicly approved by Trolltech ASA (or its successors, if any) -** and the KDE Free TQt Foundation. -** -** Please review the following information to ensure GNU General -** Public Licensing requirements will be met: -** http://trolltech.com/products/qt/licenses/licensing/opensource/. -** If you are unsure which license is appropriate for your use, please -** review the following information: -** http://trolltech.com/products/qt/licenses/licensing/licensingoverview -** or contact the sales department at sales@trolltech.com. -** -** This file may be used under the terms of the Q Public License as -** defined by Trolltech ASA and appearing in the file LICENSE.TQPL -** included in the packaging of this file. Licensees holding valid TQt -** Commercial licenses may use this file in accordance with the TQt -** Commercial License Agreement provided with the Software. -** -** This file is provided "AS IS" with NO WARRANTY OF ANY KIND, -** INCLUDING THE WARRANTIES OF DESIGN, MERCHANTABILITY AND FITNESS FOR -** A PARTICULAR PURPOSE. Trolltech reserves all rights not granted -** herein. -** -**********************************************************************/ - -#include "qplatformdefs.h" -#include "ntqdir.h" - -#ifndef TQT_NO_DIR - -#include "qdir_p.h" -#include "ntqfileinfo.h" -#include "tqregexp.h" -#include "tqstringlist.h" - -#ifdef TQT_THREAD_SUPPORT -# include -#endif // TQT_THREAD_SUPPORT - -#include -#include -#include -#include - - -void TQDir::slashify( TQString& ) -{ -} - -TQString TQDir::homeDirPath() -{ - TQString d; - d = TQFile::decodeName(getenv("HOME")); - slashify( d ); - if ( d.isNull() ) - d = rootDirPath(); - return d; -} - -TQString TQDir::canonicalPath() const -{ - TQString r; -#if !defined(PATH_MAX) - char *cur = ::get_current_dir_name(); - if ( cur ) { - char *tmp = canonicalize_file_name( TQFile::encodeName( dPath ).data() ); - if ( tmp ) { - r = TQFile::decodeName( tmp ); - free( tmp ); - } - slashify( r ); - // always make sure we go back to the current dir - ::chdir( cur ); - free( cur ); - } -#else - char cur[PATH_MAX+1]; - if ( ::getcwd( cur, PATH_MAX ) ) { - char tmp[PATH_MAX+1]; - // need the cast for old solaris versions of realpath that doesn't take - // a const char*. - if( ::realpath( (char*)TQFile::encodeName( dPath ).data(), tmp ) ) - r = TQFile::decodeName( tmp ); - slashify( r ); - - // always make sure we go back to the current dir - if (::chdir( cur ) < 0) { - // Error! - // FIXME - } - } -#endif /* !PATH_MAX */ - return r; -} - -bool TQDir::mkdir( const TQString &dirName, bool acceptAbsPath ) const -{ -#if defined(Q_OS_MACX) // Mac X doesn't support trailing /'s - TQString name = dirName; - if (dirName[dirName.length() - 1] == "/") - name = dirName.left( dirName.length() - 1 ); - int status = - ::mkdir( TQFile::encodeName(filePath(name,acceptAbsPath)), 0777 ); -#else - int status = - ::mkdir( TQFile::encodeName(filePath(dirName,acceptAbsPath)), 0777 ); -#endif - return status == 0; -} - -bool TQDir::rmdir( const TQString &dirName, bool acceptAbsPath ) const -{ - return ::rmdir( TQFile::encodeName(filePath(dirName,acceptAbsPath)) ) == 0; -} - -bool TQDir::isReadable() const -{ - return ::access( TQFile::encodeName(dPath), R_OK | X_OK ) == 0; -} - -bool TQDir::isRoot() const -{ - return dPath == TQString::fromLatin1("/"); -} - -bool TQDir::rename( const TQString &name, const TQString &newName, - bool acceptAbsPaths ) -{ - if ( name.isEmpty() || newName.isEmpty() ) { -#if defined(QT_CHECK_NULL) - tqWarning( "TQDir::rename: Empty or null file name(s)" ); -#endif - return FALSE; - } - TQString fn1 = filePath( name, acceptAbsPaths ); - TQString fn2 = filePath( newName, acceptAbsPaths ); - return ::rename( TQFile::encodeName(fn1), - TQFile::encodeName(fn2) ) == 0; -} - -bool TQDir::setCurrent( const TQString &path ) -{ - int r; - r = ::chdir( TQFile::encodeName(path) ); - return r >= 0; -} - -TQString TQDir::currentDirPath() -{ - TQString result; - - struct stat st; - if ( ::stat( ".", &st ) == 0 ) { -#if !defined(PATH_MAX) - char *currentName = ::get_current_dir_name(); - if ( currentName ) { - result = TQFile::decodeName(currentName); - free( currentName ); - } -#else - char currentName[PATH_MAX+1]; - if ( ::getcwd( currentName, PATH_MAX ) ) - result = TQFile::decodeName(currentName); -#endif /* !PATH_MAX */ -#if defined(QT_DEBUG) - if ( result.isNull() ) - tqWarning( "TQDir::currentDirPath: getcwd() failed" ); -#endif - } else { -#if defined(QT_DEBUG) - tqWarning( "TQDir::currentDirPath: stat(\".\") failed" ); -#endif - } - slashify( result ); - return result; -} - -TQString TQDir::rootDirPath() -{ - TQString d = TQString::fromLatin1( "/" ); - return d; -} - -bool TQDir::isRelativePath( const TQString &path ) -{ - int len = path.length(); - if ( len == 0 ) - return TRUE; - return path[0] != '/'; -} - -bool TQDir::readDirEntries( const TQString &nameFilter, - int filterSpec, int sortSpec ) -{ - int i; - if ( !fList ) { - fList = new TQStringList; - TQ_CHECK_PTR( fList ); - fiList = new TQFileInfoList; - TQ_CHECK_PTR( fiList ); - fiList->setAutoDelete( TRUE ); - } else { - fList->clear(); - fiList->clear(); - } - - TQValueList filters = qt_makeFilterList( nameFilter ); - - bool doDirs = (filterSpec & Dirs) != 0; - bool doFiles = (filterSpec & Files) != 0; - bool noSymLinks = (filterSpec & NoSymLinks) != 0; - bool doReadable = (filterSpec & Readable) != 0; - bool doWritable = (filterSpec & Writable) != 0; - bool doExecable = (filterSpec & Executable) != 0; - bool doHidden = (filterSpec & Hidden) != 0; - bool doSystem = (filterSpec & System) != 0; - - TQFileInfo fi; - DIR *dir; - dirent *file; - - dir = opendir( TQFile::encodeName(dPath) ); - if ( !dir ) - return FALSE; // cannot read the directory - -#if defined(TQT_THREAD_SUPPORT) && defined(_POSIX_THREAD_SAFE_FUNCTIONS) && !defined(Q_OS_CYGWIN) - union { - struct dirent mt_file; - char b[sizeof(struct dirent) + MAXNAMLEN + 1]; - } u; - while ( readdir_r(dir, &u.mt_file, &file ) == 0 && file ) -#else - while ( (file = readdir(dir)) ) -#endif // TQT_THREAD_SUPPORT && _POSIX_THREAD_SAFE_FUNCTIONS - { - TQString fn = TQFile::decodeName(file->d_name); - fi.setFile( *this, fn ); - if ( !qt_matchFilterList(filters, fn) && !(allDirs && fi.isDir()) ) - continue; - if ( (doDirs && fi.isDir()) || (doFiles && fi.isFile()) || - (doSystem && (!fi.isFile() && !fi.isDir())) ) { - if ( noSymLinks && fi.isSymLink() ) - continue; - if ( (filterSpec & RWEMask) != 0 ) - if ( (doReadable && !fi.isReadable()) || - (doWritable && !fi.isWritable()) || - (doExecable && !fi.isExecutable()) ) - continue; - if ( !doHidden && fn[0] == '.' && - fn != TQString::fromLatin1(".") - && fn != TQString::fromLatin1("..") ) - continue; - fiList->append( new TQFileInfo( fi ) ); - } - } - if ( closedir(dir) != 0 ) { -#if defined(QT_CHECK_NULL) - tqWarning( "TQDir::readDirEntries: Cannot close the directory: %s", - dPath.local8Bit().data() ); -#endif - } - - // Sort... - if(fiList->count()) { - TQDirSortItem* si= new TQDirSortItem[fiList->count()]; - TQFileInfo* itm; - i=0; - for (itm = fiList->first(); itm; itm = fiList->next()) - si[i++].item = itm; - qt_cmp_si_sortSpec = sortSpec; - qsort( si, i, sizeof(si[0]), qt_cmp_si ); - // put them back in the list - fiList->setAutoDelete( FALSE ); - fiList->clear(); - int j; - for ( j=0; jappend( si[j].item ); - fList->append( si[j].item->fileName() ); - } - delete [] si; - fiList->setAutoDelete( TRUE ); - } - - if ( filterSpec == (FilterSpec)filtS && sortSpec == (SortSpec)sortS && - nameFilter == nameFilt ) - dirty = FALSE; - else - dirty = TRUE; - return TRUE; -} - -const TQFileInfoList * TQDir::drives() -{ - // at most one instance of TQFileInfoList is leaked, and this variable - // points to that list - static TQFileInfoList * knownMemoryLeak = 0; - - if ( !knownMemoryLeak ) { - -#ifdef TQT_THREAD_SUPPORT - TQMutexLocker locker( tqt_global_mutexpool ? - tqt_global_mutexpool->get( &knownMemoryLeak ) : 0 ); -#endif // TQT_THREAD_SUPPORT - - if ( !knownMemoryLeak ) { - knownMemoryLeak = new TQFileInfoList; - // non-win32 versions both use just one root directory - knownMemoryLeak->append( new TQFileInfo( rootDirPath() ) ); - } - } - - return knownMemoryLeak; -} -#endif //TQT_NO_DIR diff --git a/src/tools/qfeatures.txt b/src/tools/qfeatures.txt index 6bf19b125..2d4027527 100644 --- a/src/tools/qfeatures.txt +++ b/src/tools/qfeatures.txt @@ -182,7 +182,7 @@ SeeAlso: ??? Feature: DIR Section: File I/O Requires: STRINGLIST REGEXP -Name: QDir +Name: TQDir SeeAlso: ??? Feature: PALETTE @@ -200,7 +200,7 @@ SeeAlso: ??? Feature: DATASTREAM Section: File I/O Requires: -Name: QDataStream +Name: TQDataStream SeeAlso: ??? Feature: LIBRARY @@ -224,7 +224,7 @@ SeeAlso: ??? Feature: SIGNALMAPPER Section: Widgets Requires: -Name: QSignalMapper +Name: TQSignalMapper SeeAlso: ??? Feature: IMAGEIO @@ -1006,7 +1006,7 @@ SeeAlso: ??? Feature: FILEDIALOG Section: Widgets Requires: MESSAGEBOX LISTVIEW NETWORKPROTOCOL COMBOBOX DIALOG REGEXP_CAPTURE TOOLBUTTON BUTTONGROUP VBOX SPLITTER PROGRESSBAR WIDGETSTACK DATESTRING -Name: QFileDialog +Name: TQFileDialog SeeAlso: ??? Feature: FONTDIALOG diff --git a/src/tools/qfile.cpp b/src/tools/qfile.cpp deleted file mode 100644 index d5dae9a7e..000000000 --- a/src/tools/qfile.cpp +++ /dev/null @@ -1,747 +0,0 @@ -/**************************************************************************** -** -** Implementation of TQFile class -** -** Created : 930812 -** -** Copyright (C) 1992-2008 Trolltech ASA. All rights reserved. -** -** This file is part of the tools module of the TQt GUI Toolkit. -** -** This file may be used under the terms of the GNU General -** Public License versions 2.0 or 3.0 as published by the Free -** Software Foundation and appearing in the files LICENSE.GPL2 -** and LICENSE.GPL3 included in the packaging of this file. -** Alternatively you may (at your option) use any later version -** of the GNU General Public License if such license has been -** publicly approved by Trolltech ASA (or its successors, if any) -** and the KDE Free TQt Foundation. -** -** Please review the following information to ensure GNU General -** Public Licensing requirements will be met: -** http://trolltech.com/products/qt/licenses/licensing/opensource/. -** If you are unsure which license is appropriate for your use, please -** review the following information: -** http://trolltech.com/products/qt/licenses/licensing/licensingoverview -** or contact the sales department at sales@trolltech.com. -** -** This file may be used under the terms of the Q Public License as -** defined by Trolltech ASA and appearing in the file LICENSE.TQPL -** included in the packaging of this file. Licensees holding valid TQt -** Commercial licenses may use this file in accordance with the TQt -** Commercial License Agreement provided with the Software. -** -** This file is provided "AS IS" with NO WARRANTY OF ANY KIND, -** INCLUDING THE WARRANTIES OF DESIGN, MERCHANTABILITY AND FITNESS FOR -** A PARTICULAR PURPOSE. Trolltech reserves all rights not granted -** herein. -** -**********************************************************************/ - -#include "qplatformdefs.h" - -// POSIX Large File Support redefines open -> open64 -#if defined(open) -# undef open -#endif - -// POSIX Large File Support redefines truncate -> truncate64 -#if defined(truncate) -# undef truncate -#endif - -#include "ntqfile.h" -#ifndef NO_ERRNO_H -#include -#endif - - -// Duplicated from tqobject.h, but we cannot include tqobject.h here since -// it causes qmake to not build on irix g++ -#define TQT_TRANSLATE_NOOP(scope,x) (x) - -const char* qt_fileerr_unknown = TQT_TRANSLATE_NOOP( "TQFile", "Unknown error" ); -const char* qt_fileerr_read = TQT_TRANSLATE_NOOP( "TQFile", "Could not read from the file" ); -const char* qt_fileerr_write = TQT_TRANSLATE_NOOP( "TQFile", "Could not write to the file" ); - -#define TQFILEERR_EACCES TQT_TRANSLATE_NOOP( "TQFile", "Permission denied" ) -#define TQFILEERR_EMFILE TQT_TRANSLATE_NOOP( "TQFile", "Too many open files" ) -#define TQFILEERR_ENOENT TQT_TRANSLATE_NOOP( "TQFile", "No such file or directory" ) -#define TQFILEERR_ENOSPC TQT_TRANSLATE_NOOP( "TQFile", "No space left on device" ) - -class TQFilePrivate -{ -public: - TQString errorString; -}; - -extern bool qt_file_access( const TQString& fn, int t ); - -/*! - \class TQFile ntqfile.h - \reentrant - \brief The TQFile class is an I/O device that operates on files. - - \ingroup io - \mainclass - - TQFile is an I/O device for reading and writing binary and text - files. A TQFile may be used by itself or more conveniently with a - TQDataStream or TQTextStream. - - The file name is usually passed in the constructor but can be - changed with setName(). You can check for a file's existence with - exists() and remove a file with remove(). - - The file is opened with open(), closed with close() and flushed - with flush(). Data is usually read and written using TQDataStream - or TQTextStream, but you can read with readBlock() and readLine() - and write with writeBlock(). TQFile also supports getch(), - ungetch() and putch(). - - The size of the file is returned by size(). You can get the - current file position or move to a new file position using the - at() functions. If you've reached the end of the file, atEnd() - returns TRUE. The file handle is returned by handle(). - - Here is a code fragment that uses TQTextStream to read a text file - line by line. It prints each line with a line number. - \code - TQStringList lines; - TQFile file( "file.txt" ); - if ( file.open( IO_ReadOnly ) ) { - TQTextStream stream( &file ); - TQString line; - int i = 1; - while ( !stream.atEnd() ) { - line = stream.readLine(); // line of text excluding '\n' - printf( "%3d: %s\n", i++, line.latin1() ); - lines += line; - } - file.close(); - } - \endcode - - Writing text is just as easy. The following example shows how to - write the data we read into the string list from the previous - example: - \code - TQFile file( "file.txt" ); - if ( file.open( IO_WriteOnly ) ) { - TQTextStream stream( &file ); - for ( TQStringList::Iterator it = lines.begin(); it != lines.end(); ++it ) - stream << *it << "\n"; - file.close(); - } - \endcode - - The TQFileInfo class holds detailed information about a file, such - as access permissions, file dates and file types. - - The TQDir class manages directories and lists of file names. - - TQt uses Unicode file names. If you want to do your own I/O on Unix - systems you may want to use encodeName() (and decodeName()) to - convert the file name into the local encoding. - - \important readAll() at() - - \sa TQDataStream, TQTextStream -*/ - -/*! - \fn TQ_LONG TQFile::writeBlock( const TQByteArray& data ) - - \overload -*/ - - -/*! - Constructs a TQFile with no name. -*/ - -TQFile::TQFile() -: d(0) -{ - init(); -} - -/*! - Constructs a TQFile with a file name \a name. - - \sa setName() -*/ - -TQFile::TQFile( const TQString &name ) - : fn(name), d(0) -{ - init(); -} - - -/*! - Destroys a TQFile. Calls close(). -*/ - -TQFile::~TQFile() -{ - close(); - delete d; -} - - -/*! - \internal - Initialize internal data. -*/ - -void TQFile::init() -{ - delete d; - d = new TQFilePrivate; - setFlags( IO_Direct ); - setStatus( IO_Ok ); - setErrorString( qt_fileerr_unknown ); - fh = 0; - fd = 0; - length = 0; - ioIndex = 0; - ext_f = FALSE; // not an external file handle -} - - -/*! - \fn TQString TQFile::name() const - - Returns the name set by setName(). - - \sa setName(), TQFileInfo::fileName() -*/ - -/*! - Sets the name of the file to \a name. The name can have no path, a - relative path or an absolute absolute path. - - Do not call this function if the file has already been opened. - - If the file name has no path or a relative path, the path used - will be whatever the application's current directory path is - \e{at the time of the open()} call. - - Example: - \code - TQFile file; - TQDir::setCurrent( "/tmp" ); - file.setName( "readme.txt" ); - TQDir::setCurrent( "/home" ); - file.open( IO_ReadOnly ); // opens "/home/readme.txt" under Unix - \endcode - - Note that the directory separator "/" works for all operating - systems supported by TQt. - - \sa name(), TQFileInfo, TQDir -*/ - -void TQFile::setName( const TQString &name ) -{ - if ( isOpen() ) { -#if defined(QT_CHECK_STATE) - tqWarning( "TQFile::setName: File is open" ); -#endif - close(); - } - fn = name; -} - -/*! - \overload - - Returns TRUE if this file exists; otherwise returns FALSE. - - \sa name() -*/ - -bool TQFile::exists() const -{ - return qt_file_access( fn, F_OK ); -} - -/*! - Returns TRUE if the file given by \a fileName exists; otherwise - returns FALSE. -*/ - -bool TQFile::exists( const TQString &fileName ) -{ - return qt_file_access( fileName, F_OK ); -} - - -/*! - Removes the file specified by the file name currently set. Returns - TRUE if successful; otherwise returns FALSE. - - The file is closed before it is removed. -*/ - -bool TQFile::remove() -{ - close(); - return remove( fn ); -} - -#if defined(Q_OS_MAC) || defined(Q_OS_MSDOS) || defined(Q_OS_WIN32) || defined(Q_OS_OS2) -# define HAS_TEXT_FILEMODE // has translate/text filemode -#endif -#if defined(O_NONBLOCK) -# define HAS_ASYNC_FILEMODE -# define OPEN_ASYNC O_NONBLOCK -#elif defined(O_NDELAY) -# define HAS_ASYNC_FILEMODE -# define OPEN_ASYNC O_NDELAY -#endif - -/*! - Flushes the file buffer to the disk. - - close() also flushes the file buffer. -*/ - -void TQFile::flush() -{ - if ( isOpen() && fh ) { // can only flush open/buffered file - if ( fflush( fh ) ) { // write error - if ( errno == ENOSPC ) // disk is full - setStatus( IO_ResourceError ); - else - setStatus( IO_WriteError ); - setErrorStringErrno( errno ); - } - } -} - -/*! \reimp - \fn TQIODevice::Offset TQFile::at() const -*/ - -/*! - Returns TRUE if the end of file has been reached; otherwise returns FALSE. - If TQFile has not been open()'d, then the behavior is undefined. - - \sa size() -*/ - -bool TQFile::atEnd() const -{ - if ( !isOpen() ) { -#if defined(QT_CHECK_STATE) - tqWarning( "TQFile::atEnd: File is not open" ); -#endif - return FALSE; - } - if ( isDirectAccess() && !isTranslated() ) { - if ( at() < size() ) - return FALSE; - } - const TQString errorString = d->errorString; - const bool ret = TQIODevice::atEnd(); - if (errorString != d->errorString) - d->errorString = errorString; - return ret; -} - -/*! - Reads a line of text. - - Reads bytes from the file into the char* \a p, until end-of-line - or \a maxlen bytes have been read, whichever occurs first. Returns - the number of bytes read, or -1 if there was an error. Any - terminating newline is not stripped. - - This function is only efficient for buffered files. Avoid - readLine() for files that have been opened with the \c IO_Raw - flag. - - \sa readBlock(), TQTextStream::readLine() -*/ - -TQ_LONG TQFile::readLine( char *p, TQ_ULONG maxlen ) -{ - if ( maxlen == 0 ) // application bug? - return 0; -#if defined(QT_CHECK_STATE) - TQ_CHECK_PTR( p ); - if ( !isOpen() ) { // file not open - tqWarning( "TQFile::readLine: File not open" ); - return -1; - } - if ( !isReadable() ) { // reading not permitted - tqWarning( "TQFile::readLine: Read operation not permitted" ); - return -1; - } -#endif - TQ_LONG nread; // number of bytes read - if ( isRaw() ) { // raw file - nread = TQIODevice::readLine( p, maxlen ); - } else { // buffered file - p = fgets( p, maxlen, fh ); - if ( p ) { - nread = tqstrlen( p ); - if ( !isSequentialAccess() ) - ioIndex += nread; - } else { - nread = -1; - setStatus(IO_ReadError); - setErrorString( qt_fileerr_read ); - } - } - return nread; -} - - -/*! - \overload - - Reads a line of text. - - Reads bytes from the file into string \a s, until end-of-line or - \a maxlen bytes have been read, whichever occurs first. Returns - the number of bytes read, or -1 if there was an error, e.g. end of - file. Any terminating newline is not stripped. - - This function is only efficient for buffered files. Avoid using - readLine() for files that have been opened with the \c IO_Raw - flag. - - Note that the string is read as plain Latin1 bytes, not Unicode. - - \sa readBlock(), TQTextStream::readLine() -*/ - -TQ_LONG TQFile::readLine( TQString& s, TQ_ULONG maxlen ) -{ - TQByteArray ba(maxlen); - TQ_LONG l = readLine(ba.data(),maxlen); - if ( l >= 0 ) { - ba.truncate(l); - s = TQString(ba); - } - return l; -} - - -/*! - Reads a single byte/character from the file. - - Returns the byte/character read, or -1 if the end of the file has - been reached. - - \sa putch(), ungetch() -*/ - -int TQFile::getch() -{ -#if defined(QT_CHECK_STATE) - if ( !isOpen() ) { // file not open - tqWarning( "TQFile::getch: File not open" ); - return EOF; - } - if ( !isReadable() ) { // reading not permitted - tqWarning( "TQFile::getch: Read operation not permitted" ); - return EOF; - } -#endif - - int ch; - - if ( !ungetchBuffer.isEmpty() ) { - int len = ungetchBuffer.length(); - ch = ungetchBuffer[ len-1 ]; - ungetchBuffer.truncate( len - 1 ); - return ch; - } - - if ( isRaw() ) { // raw file (inefficient) - char buf[1]; - ch = readBlock( buf, 1 ) == 1 ? buf[0] : EOF; - } else { // buffered file - if ( (ch = getc( fh )) != EOF ) { - if ( !isSequentialAccess() ) - ioIndex++; - } else { - setStatus(IO_ReadError); - setErrorString( qt_fileerr_read ); - } - } - return ch; -} - -/*! - Writes the character \a ch to the file. - - Returns \a ch, or -1 if some error occurred. - - \sa getch(), ungetch() -*/ - -int TQFile::putch( int ch ) -{ -#if defined(QT_CHECK_STATE) - if ( !isOpen() ) { // file not open - tqWarning( "TQFile::putch: File not open" ); - return EOF; - } - if ( !isWritable() ) { // writing not permitted - tqWarning( "TQFile::putch: Write operation not permitted" ); - return EOF; - } -#endif - if ( isRaw() ) { // raw file (inefficient) - char buf[1]; - buf[0] = ch; - ch = writeBlock( buf, 1 ) == 1 ? ch : EOF; - } else { // buffered file - if ( (ch = putc( ch, fh )) != EOF ) { - if ( !isSequentialAccess() ) - ioIndex++; - if ( ioIndex > length ) // update file length - length = ioIndex; - } else { - setStatus(IO_WriteError); - setErrorString( qt_fileerr_write ); - } - } - return ch; -} - -/*! - Puts the character \a ch back into the file and decrements the - index if it is not zero. - - This function is normally called to "undo" a getch() operation. - - Returns \a ch, or -1 if an error occurred. - - \sa getch(), putch() -*/ - -int TQFile::ungetch( int ch ) -{ -#if defined(QT_CHECK_STATE) - if ( !isOpen() ) { // file not open - tqWarning( "TQFile::ungetch: File not open" ); - return EOF; - } - if ( !isReadable() ) { // reading not permitted - tqWarning( "TQFile::ungetch: Read operation not permitted" ); - return EOF; - } -#endif - if ( ch == EOF ) // cannot unget EOF - return ch; - - if ( isSequentialAccess() && !fh) { - // pipe or similar => we cannot ungetch, so do it manually - ungetchBuffer += TQChar(ch); - return ch; - } - - if ( isRaw() ) { // raw file (very inefficient) - char buf[1]; - at( ioIndex-1 ); - buf[0] = ch; - if ( writeBlock(buf, 1) == 1 ) - at ( ioIndex-1 ); - else - ch = EOF; - } else { // buffered file - if ( (ch = ungetc(ch, fh)) != EOF ) { - if ( !isSequentialAccess() ) - ioIndex--; - } else { - setStatus( IO_ReadError ); - setErrorString( qt_fileerr_read ); - } - } - return ch; -} - - -static TQCString locale_encoder( const TQString &fileName ) -{ - return fileName.local8Bit(); -} - - -static TQFile::EncoderFn encoder = locale_encoder; - -/*! - When you use TQFile, TQFileInfo, and TQDir to access the file system - with TQt, you can use Unicode file names. On Unix, these file names - are converted to an 8-bit encoding. If you want to do your own - file I/O on Unix, you should convert the file name using this - function. On Windows NT/2000, Unicode file names are supported - directly in the file system and this function should be avoided. - On Windows 95, non-Latin1 locales are not supported. - - By default, this function converts \a fileName to the local 8-bit - encoding determined by the user's locale. This is sufficient for - file names that the user chooses. File names hard-coded into the - application should only use 7-bit ASCII filename characters. - - The conversion scheme can be changed using setEncodingFunction(). - This might be useful if you wish to give the user an option to - store file names in UTF-8, etc., but be aware that such file names - would probably then be unrecognizable when seen by other programs. - - \sa decodeName() -*/ - -TQCString TQFile::encodeName( const TQString &fileName ) -{ - return (*encoder)(fileName); -} - -/*! - \enum TQFile::EncoderFn - - This is used by TQFile::setEncodingFunction(). -*/ - -/*! - \nonreentrant - - Sets the function for encoding Unicode file names to \a f. The - default encodes in the locale-specific 8-bit encoding. - - \sa encodeName() -*/ -void TQFile::setEncodingFunction( EncoderFn f ) -{ - encoder = f; -} - -static -TQString locale_decoder( const TQCString &localFileName ) -{ -#ifndef TQ_WS_MAC - return TQString::fromLocal8Bit(localFileName); -#else - extern TQString qt_mac_precomposeFileName(const TQString &); // qglobal.cpp - return qt_mac_precomposeFileName(TQString::fromLocal8Bit(localFileName)); -#endif -} - -static TQFile::DecoderFn decoder = locale_decoder; - -/*! - This does the reverse of TQFile::encodeName() using \a localFileName. - - \sa setDecodingFunction() -*/ -TQString TQFile::decodeName( const TQCString &localFileName ) -{ - return (*decoder)(localFileName); -} - -/*! - \enum TQFile::DecoderFn - - This is used by TQFile::setDecodingFunction(). -*/ - -/*! - \nonreentrant - - Sets the function for decoding 8-bit file names to \a f. The - default uses the locale-specific 8-bit encoding. - - \sa encodeName(), decodeName() -*/ - -void TQFile::setDecodingFunction( DecoderFn f ) -{ - decoder = f; -} - -/*! - Returns a human-readable description of the reason of an error that occurred - on the device. The error described by the string corresponds to changes of - TQIODevice::status(). If the status is reset, the error string is also reset. - - The returned strings are not translated with the TQObject::tr() or - TQApplication::translate() functions. They are marked as translatable - strings in the "TQFile" context. Before you show the string to the user you - should translate it first, for example: - - \code - TQFile f( "address.dat" ); - if ( !f.open( IO_ReadOnly ) { - TQMessageBox::critical( - this, - tr("Open failed"), - tr("Could not open file for reading: %1").arg( tqApp->translate("TQFile",f.errorString()) ) - ); - return; - } - \endcode - - \sa TQIODevice::status(), TQIODevice::resetStatus(), setErrorString() -*/ - -TQString TQFile::errorString() const -{ - if ( status() == IO_Ok ) - return qt_fileerr_unknown; - return d->errorString; -} - -/*! - \nonreentrant - - Sets the error string returned by the errorString() function to \a str. - - \sa errorString(), TQIODevice::status() -*/ - -void TQFile::setErrorString( const TQString& str ) -{ - d->errorString = str; -} - -void TQFile::setErrorStringErrno( int errnum ) -{ - switch ( errnum ) { - case EACCES: - d->errorString = TQFILEERR_EACCES; - break; - case EMFILE: - d->errorString = TQFILEERR_EMFILE; - break; - case ENOENT: - d->errorString = TQFILEERR_ENOENT; - break; - case ENOSPC: - d->errorString = TQFILEERR_ENOSPC; - break; - default: -#ifndef Q_OS_TEMP - d->errorString = TQString::fromLocal8Bit( strerror( errnum ) ); -#else - { - unsigned short *string; - FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_SYSTEM, - NULL, - errnum, - MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), - (LPTSTR)&string, - 0, - NULL ); - d->errorString = TQString::fromUcs2( string ); - LocalFree( (HLOCAL)string ); - } -#endif - break; - } -} diff --git a/src/tools/qfile_unix.cpp b/src/tools/qfile_unix.cpp deleted file mode 100644 index f28899483..000000000 --- a/src/tools/qfile_unix.cpp +++ /dev/null @@ -1,734 +0,0 @@ -/**************************************************************************** -** -** Implementation of TQFile class -** -** Created : 950628 -** -** Copyright (C) 1992-2008 Trolltech ASA. All rights reserved. -** -** This file is part of the tools module of the TQt GUI Toolkit. -** -** This file may be used under the terms of the GNU General -** Public License versions 2.0 or 3.0 as published by the Free -** Software Foundation and appearing in the files LICENSE.GPL2 -** and LICENSE.GPL3 included in the packaging of this file. -** Alternatively you may (at your option) use any later version -** of the GNU General Public License if such license has been -** publicly approved by Trolltech ASA (or its successors, if any) -** and the KDE Free TQt Foundation. -** -** Please review the following information to ensure GNU General -** Public Licensing requirements will be met: -** http://trolltech.com/products/qt/licenses/licensing/opensource/. -** If you are unsure which license is appropriate for your use, please -** review the following information: -** http://trolltech.com/products/qt/licenses/licensing/licensingoverview -** or contact the sales department at sales@trolltech.com. -** -** This file may be used under the terms of the Q Public License as -** defined by Trolltech ASA and appearing in the file LICENSE.TQPL -** included in the packaging of this file. Licensees holding valid TQt -** Commercial licenses may use this file in accordance with the TQt -** Commercial License Agreement provided with the Software. -** -** This file is provided "AS IS" with NO WARRANTY OF ANY KIND, -** INCLUDING THE WARRANTIES OF DESIGN, MERCHANTABILITY AND FITNESS FOR -** A PARTICULAR PURPOSE. Trolltech reserves all rights not granted -** herein. -** -**********************************************************************/ - -#include "qplatformdefs.h" - -// POSIX Large File Support redefines open -> open64 -static inline int qt_open(const char *pathname, int flags, mode_t mode) -{ return ::open(pathname, flags, mode); } -#if defined(open) -# undef open -#endif - -// POSIX Large File Support redefines truncate -> truncate64 -#if defined(truncate) -# undef truncate -#endif - -#include "ntqfile.h" -#include -#include - -extern const char* qt_fileerr_read; - -bool qt_file_access( const TQString& fn, int t ) -{ - if ( fn.isEmpty() ) - return FALSE; - return ::access( TQFile::encodeName(fn), t ) == 0; -} - -/*! - \overload - Removes the file \a fileName. - Returns TRUE if successful, otherwise FALSE. -*/ - -bool TQFile::remove( const TQString &fileName ) -{ - if ( fileName.isEmpty() ) { -#if defined(QT_CHECK_NULL) - tqWarning( "TQFile::remove: Empty or null file name" ); -#endif - return FALSE; - } - return unlink( TQFile::encodeName(fileName) ) == 0; -} - -#if defined(O_NONBLOCK) -# define HAS_ASYNC_FILEMODE -# define OPEN_ASYNC O_NONBLOCK -#elif defined(O_NDELAY) -# define HAS_ASYNC_FILEMODE -# define OPEN_ASYNC O_NDELAY -#endif - -/*! - Opens the file specified by the file name currently set, using the - mode \a m. Returns TRUE if successful, otherwise FALSE. - - \keyword IO_Raw - \keyword IO_ReadOnly - \keyword IO_WriteOnly - \keyword IO_ReadWrite - \keyword IO_Append - \keyword IO_Truncate - \keyword IO_Translate - - The mode parameter \a m must be a combination of the following flags: - \table - \header \i Flag \i Meaning - \row \i IO_Raw - \i Raw (non-buffered) file access. - \row \i IO_ReadOnly - \i Opens the file in read-only mode. - \row \i IO_WriteOnly - \i Opens the file in write-only mode. If this flag is used - with another flag, e.g. \c IO_ReadOnly or \c IO_Raw or \c - IO_Append, the file is \e not truncated; but if used on - its own (or with \c IO_Truncate), the file is truncated. - \row \i IO_ReadWrite - \i Opens the file in read/write mode, equivalent to \c - (IO_ReadOnly | IO_WriteOnly). - \row \i IO_Append - \i Opens the file in append mode. (You must actually use \c - (IO_WriteOnly | IO_Append) to make the file writable and - to go into append mode.) This mode is very useful when you - want to write something to a log file. The file index is - set to the end of the file. Note that the result is - undefined if you position the file index manually using - at() in append mode. - \row \i IO_Truncate - \i Truncates the file. - \row \i IO_Translate - \i Enables carriage returns and linefeed translation for text - files under Windows. - \endtable - - The raw access mode is best when I/O is block-operated using a 4KB - block size or greater. Buffered access works better when reading - small portions of data at a time. - - \warning When working with buffered files, data may not be written - to the file at once. Call flush() to make sure that the data is - really written. - - \warning If you have a buffered file opened for both reading and - writing you must not perform an input operation immediately after - an output operation or vice versa. You should always call flush() - or a file positioning operation, e.g. at(), between input and - output operations, otherwise the buffer may contain garbage. - - If the file does not exist and \c IO_WriteOnly or \c IO_ReadWrite - is specified, it is created. - - Example: - \code - TQFile f1( "/tmp/data.bin" ); - f1.open( IO_Raw | IO_ReadWrite ); - - TQFile f2( "readme.txt" ); - f2.open( IO_ReadOnly | IO_Translate ); - - TQFile f3( "audit.log" ); - f3.open( IO_WriteOnly | IO_Append ); - \endcode - - \sa name(), close(), isOpen(), flush() -*/ - -bool TQFile::open( int m ) -{ - if ( isOpen() ) { // file already open -#if defined(QT_CHECK_STATE) - tqWarning( "TQFile::open: File (%s) already open", fn.latin1() ); -#endif - return FALSE; - } - if ( fn.isEmpty() ) { // no file name defined -#if defined(QT_CHECK_NULL) - tqWarning( "TQFile::open: No file name specified" ); -#endif - return FALSE; - } - init(); // reset params - setMode( m ); - if ( !(isReadable() || isWritable()) ) { -#if defined(QT_CHECK_RANGE) - tqWarning( "TQFile::open: File access (%s) not specified", fn.latin1() ); -#endif - return FALSE; - } - bool ok = TRUE; - struct stat st; - if ( isRaw() ) { - int oflags = O_RDONLY; - if ( isReadable() && isWritable() ) - oflags = O_RDWR; - else if ( isWritable() ) - oflags = O_WRONLY; - if ( flags() & IO_Append ) { // append to end of file? - if ( flags() & IO_Truncate ) - oflags |= (O_CREAT | O_TRUNC); - else - oflags |= (O_APPEND | O_CREAT); - setFlags( flags() | IO_WriteOnly ); // append implies write - } else if ( isWritable() ) { // create/trunc if writable - if ( flags() & IO_Truncate ) - oflags |= (O_CREAT | O_TRUNC); - else - oflags |= O_CREAT; - } -#if defined(HAS_TEXT_FILEMODE) - if ( isTranslated() ) - oflags |= OPEN_TEXT; - else - oflags |= OPEN_BINARY; -#endif -#if defined(HAS_ASYNC_FILEMODE) - if ( isAsynchronous() ) - oflags |= OPEN_ASYNC; -#endif - fd = qt_open( TQFile::encodeName(fn), oflags, 0666 ); - - if ( fd != -1 ) { // open successful - ::fstat( fd, &st ); // get the stat for later usage - } else { - ok = FALSE; - } - } else { // buffered file I/O - TQCString perm; - char perm2[4]; - bool try_create = FALSE; - if ( flags() & IO_Append ) { // append to end of file? - setFlags( flags() | IO_WriteOnly ); // append implies write - perm = isReadable() ? "a+" : "a"; - } else { - if ( isReadWrite() ) { - if ( flags() & IO_Truncate ) { - perm = "w+"; - } else { - perm = "r+"; - try_create = TRUE; // try to create if not exists - } - } else if ( isReadable() ) { - perm = "r"; - } else if ( isWritable() ) { - perm = "w"; - } - } - qstrcpy( perm2, perm ); -#if defined(HAS_TEXT_FILEMODE) - if ( isTranslated() ) - strcat( perm2, "t" ); - else - strcat( perm2, "b" ); -#endif - for (;;) { // At most twice - - fh = fopen( TQFile::encodeName(fn), perm2 ); - - if ( !fh && try_create ) { - perm2[0] = 'w'; // try "w+" instead of "r+" - try_create = FALSE; - } else { - break; - } - } - if ( fh ) { - ::fstat( fileno(fh), &st ); // get the stat for later usage - } else { - ok = FALSE; - } - } - if ( ok ) { - setState( IO_Open ); - // on successful open the file stat was got; now test what type - // of file we have - if ( (st.st_mode & S_IFMT) != S_IFREG ) { - // non-seekable - setType( IO_Sequential ); - length = INT_MAX; - ioIndex = 0; - } else { -#if defined(QT_LARGEFILE_SUPPORT) - length = st.st_size > UINT_MAX ? UINT_MAX : (Offset)st.st_size; -#else - length = (Offset)st.st_size; -#endif - ioIndex = (flags() & IO_Append) == 0 ? 0 : length; - if ( !(flags()&IO_Truncate) && length == 0 && isReadable() ) { - // try if you can read from it (if you can, it's a sequential - // device; e.g. a file in the /proc filesystem) - int c = getch(); - if ( c != -1 ) { - ungetch(c); - setType( IO_Sequential ); - length = INT_MAX; - ioIndex = 0; - } - resetStatus(); - } - } - } else { - init(); - if ( errno == EMFILE ) // no more file handles/descrs - setStatus( IO_ResourceError ); - else - setStatus( IO_OpenError ); - setErrorStringErrno( errno ); - } - return ok; -} - -/*! - \overload - Opens a file in the mode \a m using an existing file handle \a f. - Returns TRUE if successful, otherwise FALSE. - - Example: - \code - #include - - void printError( const char* msg ) - { - TQFile f; - f.open( IO_WriteOnly, stderr ); - f.writeBlock( msg, tqstrlen(msg) ); // write to stderr - f.close(); - } - \endcode - - When a TQFile is opened using this function, close() does not actually - close the file, only flushes it. - - \warning If \a f is \c stdin, \c stdout, \c stderr, you may not - be able to seek. See TQIODevice::isSequentialAccess() for more - information. - - \sa close() -*/ - -bool TQFile::open( int m, FILE *f ) -{ - if ( isOpen() ) { -#if defined(QT_CHECK_RANGE) - tqWarning( "TQFile::open: File (%s) already open", fn.latin1() ); -#endif - return FALSE; - } - init(); - setMode( m &~IO_Raw ); - setState( IO_Open ); - fh = f; - ext_f = TRUE; - struct stat st; - ::fstat( fileno(fh), &st ); -#if defined(QT_LARGEFILE_SUPPORT) - off_t tmp = ftello( fh ); - ioIndex = tmp > UINT_MAX ? UINT_MAX : (Offset)tmp; -#else - ioIndex = (Offset)ftell( fh ); -#endif - if ( (st.st_mode & S_IFMT) != S_IFREG || f == stdin ) { //stdin is non seekable - // non-seekable - setType( IO_Sequential ); - length = INT_MAX; - ioIndex = 0; - } else { -#if defined(QT_LARGEFILE_SUPPORT) - length = st.st_size > UINT_MAX ? UINT_MAX : (Offset)st.st_size; -#else - length = (Offset)st.st_size; -#endif - if ( !(flags()&IO_Truncate) && length == 0 && isReadable() ) { - // try if you can read from it (if you can, it's a sequential - // device; e.g. a file in the /proc filesystem) - int c = getch(); - if ( c != -1 ) { - ungetch(c); - setType( IO_Sequential ); - length = INT_MAX; - ioIndex = 0; - } - resetStatus(); - } - } - return TRUE; -} - -/*! - \overload - Opens a file in the mode \a m using an existing file descriptor \a f. - Returns TRUE if successful, otherwise FALSE. - - When a TQFile is opened using this function, close() does not actually - close the file. - - The TQFile that is opened using this function, is automatically set to be in - raw mode; this means that the file input/output functions are slow. If you - run into performance issues, you should try to use one of the other open - functions. - - \warning If \a f is one of 0 (stdin), 1 (stdout) or 2 (stderr), you may not - be able to seek. size() is set to \c INT_MAX (in limits.h). - - \sa close() -*/ - - -bool TQFile::open( int m, int f ) -{ - if ( isOpen() ) { -#if defined(QT_CHECK_RANGE) - tqWarning( "TQFile::open: File (%s) already open", fn.latin1() ); -#endif - return FALSE; - } - init(); - setMode( m |IO_Raw ); - setState( IO_Open ); - fd = f; - ext_f = TRUE; - struct stat st; - ::fstat( fd, &st ); -#if defined(QT_LARGEFILE_SUPPORT) - off_t tmp = ::lseek(fd, 0, SEEK_CUR); - ioIndex = tmp > UINT_MAX ? UINT_MAX : (Offset)tmp; -#else - ioIndex = (Offset)::lseek(fd, 0, SEEK_CUR); -#endif - if ( (st.st_mode & S_IFMT) != S_IFREG || f == 0 ) { // stdin is not seekable... - // non-seekable - setType( IO_Sequential ); - length = INT_MAX; - ioIndex = 0; - } else { -#if defined(QT_LARGEFILE_SUPPORT) - length = st.st_size > UINT_MAX ? UINT_MAX : (Offset)st.st_size; -#else - length = (Offset)st.st_size; -#endif - if ( length == 0 && isReadable() ) { - // try if you can read from it (if you can, it's a sequential - // device; e.g. a file in the /proc filesystem) - int c = getch(); - if ( c != -1 ) { - ungetch(c); - setType( IO_Sequential ); - length = INT_MAX; - ioIndex = 0; - } - resetStatus(); - } - } - return TRUE; -} - -/*! - Returns the file size. - \sa at() -*/ - -TQIODevice::Offset TQFile::size() const -{ - struct stat st; - int ret = 0; - if ( isOpen() ) { - ret = ::fstat( fh ? fileno(fh) : fd, &st ); - } else { - ret = ::stat( TQFile::encodeName(fn), &st ); - } - if ( ret == -1 ) - return 0; -#if defined(QT_LARGEFILE_SUPPORT) - return (uint)st.st_size > UINT_MAX ? UINT_MAX : (Offset)st.st_size; -#else - return st.st_size; -#endif -} - - -/*! - \overload - - Sets the file index to \a pos. Returns TRUE if successful; - otherwise returns FALSE. - - Example: - \code - TQFile f( "data.bin" ); - f.open( IO_ReadOnly ); // index set to 0 - f.at( 100 ); // set index to 100 - f.at( f.at()+50 ); // set index to 150 - f.at( f.size()-80 ); // set index to 80 before EOF - f.close(); - \endcode - - Use \c at() without arguments to retrieve the file offset. - - \warning The result is undefined if the file was open()'ed using - the \c IO_Append specifier. - - \sa size(), open() -*/ - -bool TQFile::at( Offset pos ) -{ - if ( !isOpen() ) { -#if defined(QT_CHECK_STATE) - tqWarning( "TQFile::at: File (%s) is not open", fn.latin1() ); -#endif - return FALSE; - } - if ( isSequentialAccess() ) - return FALSE; - bool ok; - if ( isRaw() ) { - off_t l = ::lseek( fd, pos, SEEK_SET ); - ok = ( l != -1 ); - pos = (Offset)l; - } else { // buffered file -#if defined(QT_LARGEFILE_SUPPORT) - ok = ( ::fseeko(fh, pos, SEEK_SET) == 0 ); -#else - ok = ( ::fseek(fh, pos, SEEK_SET) == 0 ); -#endif - } - if ( ok ) -#if defined(QT_LARGEFILE_SUPPORT) - ioIndex = pos > UINT_MAX ? UINT_MAX : (Offset)pos; -#else - ioIndex = (Offset)pos; -#endif -#if defined(QT_CHECK_RANGE) - else - tqWarning( "TQFile::at: Cannot set file position %lu", pos ); -#endif - return ok; -} - -/*! - \reimp - - \warning We have experienced problems with some C libraries when a buffered - file is opened for both reading and writing. If a read operation takes place - immediately after a write operation, the read buffer contains garbage data. - Worse, the same garbage is written to the file. Calling flush() before - readBlock() solved this problem. -*/ - -TQ_LONG TQFile::readBlock( char *p, TQ_ULONG len ) -{ - if ( !len ) // nothing to do - return 0; - -#if defined(QT_CHECK_NULL) - if ( !p ) - tqWarning( "TQFile::readBlock: Null pointer error" ); -#endif -#if defined(QT_CHECK_STATE) - if ( !isOpen() ) { - tqWarning( "TQFile::readBlock: File (%s) not open", fn.latin1() ); - return -1; - } - if ( !isReadable() ) { - tqWarning( "TQFile::readBlock: Read operation not permitted in file %s ", fn.latin1() ); - return -1; - } -#endif - TQ_ULONG nread = 0; // number of bytes read - if ( !ungetchBuffer.isEmpty() ) { - // need to add these to the returned string. - uint l = ungetchBuffer.length(); - while( nread < l ) { - *p = ungetchBuffer.at( l - nread - 1 ); - p++; - nread++; - } - ungetchBuffer.truncate( l - nread ); - } - - if ( nread < len ) { - if ( isRaw() ) { // raw file - nread += ::read( fd, p, len-nread ); - if ( len && nread <= 0 ) { - nread = 0; - setStatus(IO_ReadError); - setErrorStringErrno( errno ); - } - } else { // buffered file - nread += fread( p, 1, len-nread, fh ); - if ( (uint)nread != len ) { - if ( ferror( fh ) || nread==0 ) { - setStatus(IO_ReadError); - setErrorString( qt_fileerr_read ); - } - } - } - } - if ( !isSequentialAccess() ) - ioIndex += nread; - return nread; -} - - -/*! \reimp - - Writes \a len bytes from \a p to the file and returns the number of - bytes actually written. - - Returns -1 if a serious error occurred. - - \warning When working with buffered files, data may not be written - to the file at once. Call flush() to make sure the data is really - written. - - \sa readBlock() -*/ - -TQ_LONG TQFile::writeBlock( const char *p, TQ_ULONG len ) -{ - if ( !len ) // nothing to do - return 0; - -#if defined(QT_CHECK_NULL) - if ( p == 0 && len != 0 ) - tqWarning( "TQFile::writeBlock: Null pointer error" ); -#endif -#if defined(QT_CHECK_STATE) - if ( !isOpen() ) { // file not open - tqWarning( "TQFile::writeBlock: File (%s) not open", fn.latin1() ); - return -1; - } - if ( !isWritable() ) { // writing not permitted - tqWarning( "TQFile::writeBlock: Write operation not permitted in file %s ", fn.latin1() ); - return -1; - } -#endif - TQ_ULONG nwritten; // number of bytes written - if ( isRaw() ) // raw file - nwritten = ::write( fd, (void *)p, len ); - else // buffered file - nwritten = fwrite( p, 1, len, fh ); - if ( nwritten != len ) { // write error - if ( errno == ENOSPC ) // disk is full - setStatus( IO_ResourceError ); - else - setStatus( IO_WriteError ); - setErrorStringErrno( errno ); - if ( !isSequentialAccess() ) { - if ( isRaw() ) { // recalc file position -#if defined(QT_LARGEFILE_SUPPORT) - off_t tmp = ::lseek( fd, 0, SEEK_CUR ); - ioIndex = tmp > UINT_MAX ? UINT_MAX : (Offset)tmp; -#else - ioIndex = (Offset)::lseek( fd, 0, SEEK_CUR ); -#endif - } else { -#if defined(QT_LARGEFILE_SUPPORT) - off_t tmp = (Offset)::fseeko( fh, 0, SEEK_CUR ); - ioIndex = tmp > UINT_MAX ? UINT_MAX : (Offset)tmp; -#else - ioIndex = (Offset)::fseek( fh, 0, SEEK_CUR ); -#endif - } - } - } else { - if ( !isSequentialAccess() ) - ioIndex += nwritten; - } - if ( ioIndex > length ) // update file length - length = ioIndex; - return nwritten; -} - -/*! - Returns the file handle of the file. - - This is a small positive integer, suitable for use with C library - functions such as fdopen() and fcntl(). On systems that use file - descriptors for sockets (ie. Unix systems, but not Windows) the handle - can be used with TQSocketNotifier as well. - - If the file is not open or there is an error, handle() returns -1. - - \sa TQSocketNotifier -*/ - -int TQFile::handle() const -{ - if ( !isOpen() ) - return -1; - else if ( fh ) - return fileno( fh ); - else - return fd; -} - -/*! - Closes an open file. - - The file is not closed if it was opened with an existing file handle. - If the existing file handle is a \c FILE*, the file is flushed. - If the existing file handle is an \c int file descriptor, nothing - is done to the file. - - Some "write-behind" filesystems may report an unspecified error on - closing the file. These errors only indicate that something may - have gone wrong since the previous open(). In such a case status() - reports IO_UnspecifiedError after close(), otherwise IO_Ok. - - \sa open(), flush() -*/ - - -void TQFile::close() -{ - bool ok = FALSE; - if ( isOpen() ) { // file is not open - if ( fh ) { // buffered file - if ( ext_f ) - ok = fflush( fh ) != -1; // flush instead of closing - else - ok = fclose( fh ) != -1; - } else { // raw file - if ( ext_f ) - ok = TRUE; // cannot close - else - ok = ::close( fd ) != -1; - } - init(); // restore internal state - } - if (!ok) { - setStatus( IO_UnspecifiedError ); - setErrorStringErrno( errno ); - } -} diff --git a/src/tools/qfiledefs_p.h b/src/tools/qfiledefs_p.h deleted file mode 100644 index 62d55583f..000000000 --- a/src/tools/qfiledefs_p.h +++ /dev/null @@ -1,67 +0,0 @@ -/**************************************************************************** -** -** Common macros and system include files for TQFile, TQFileInfo and TQDir. -** -** Created : 930812 -** -** Copyright (C) 1992-2008 Trolltech ASA. All rights reserved. -** -** This file is part of the tools module of the TQt GUI Toolkit. -** -** This file may be used under the terms of the GNU General -** Public License versions 2.0 or 3.0 as published by the Free -** Software Foundation and appearing in the files LICENSE.GPL2 -** and LICENSE.GPL3 included in the packaging of this file. -** Alternatively you may (at your option) use any later version -** of the GNU General Public License if such license has been -** publicly approved by Trolltech ASA (or its successors, if any) -** and the KDE Free TQt Foundation. -** -** Please review the following information to ensure GNU General -** Public Licensing requirements will be met: -** http://trolltech.com/products/qt/licenses/licensing/opensource/. -** If you are unsure which license is appropriate for your use, please -** review the following information: -** http://trolltech.com/products/qt/licenses/licensing/licensingoverview -** or contact the sales department at sales@trolltech.com. -** -** This file may be used under the terms of the Q Public License as -** defined by Trolltech ASA and appearing in the file LICENSE.TQPL -** included in the packaging of this file. Licensees holding valid TQt -** Commercial licenses may use this file in accordance with the TQt -** Commercial License Agreement provided with the Software. -** -** This file is provided "AS IS" with NO WARRANTY OF ANY KIND, -** INCLUDING THE WARRANTIES OF DESIGN, MERCHANTABILITY AND FITNESS FOR -** A PARTICULAR PURPOSE. Trolltech reserves all rights not granted -** herein. -** -**********************************************************************/ - -#ifndef TQFILEDEFS_P_H -#define TQFILEDEFS_P_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the TQt API. It exists for the convenience -// of qfileinfo*.cpp. This header file may change from version to version -// without notice, or even be removed. -// -// We mean it. -// -// - -// Be sure to include qplatformdefs.h first! -struct TQFileInfoCache -{ -#if defined(TQ_WS_WIN) - QT_STATBUF st; -#else - struct stat st; -#endif -}; - - -#endif diff --git a/src/tools/qfileinfo.cpp b/src/tools/qfileinfo.cpp deleted file mode 100644 index 60a39346a..000000000 --- a/src/tools/qfileinfo.cpp +++ /dev/null @@ -1,704 +0,0 @@ -/**************************************************************************** -** -** Implementation of TQFileInfo class -** -** Created : 950628 -** -** Copyright (C) 1992-2008 Trolltech ASA. All rights reserved. -** -** This file is part of the tools module of the TQt GUI Toolkit. -** -** This file may be used under the terms of the GNU General -** Public License versions 2.0 or 3.0 as published by the Free -** Software Foundation and appearing in the files LICENSE.GPL2 -** and LICENSE.GPL3 included in the packaging of this file. -** Alternatively you may (at your option) use any later version -** of the GNU General Public License if such license has been -** publicly approved by Trolltech ASA (or its successors, if any) -** and the KDE Free TQt Foundation. -** -** Please review the following information to ensure GNU General -** Public Licensing requirements will be met: -** http://trolltech.com/products/qt/licenses/licensing/opensource/. -** If you are unsure which license is appropriate for your use, please -** review the following information: -** http://trolltech.com/products/qt/licenses/licensing/licensingoverview -** or contact the sales department at sales@trolltech.com. -** -** This file may be used under the terms of the Q Public License as -** defined by Trolltech ASA and appearing in the file LICENSE.TQPL -** included in the packaging of this file. Licensees holding valid TQt -** Commercial licenses may use this file in accordance with the TQt -** Commercial License Agreement provided with the Software. -** -** This file is provided "AS IS" with NO WARRANTY OF ANY KIND, -** INCLUDING THE WARRANTIES OF DESIGN, MERCHANTABILITY AND FITNESS FOR -** A PARTICULAR PURPOSE. Trolltech reserves all rights not granted -** herein. -** -**********************************************************************/ - -#include "qplatformdefs.h" - -#include "ntqfileinfo.h" -#include "tqdatetime.h" -#include "ntqdir.h" -#include "qfiledefs_p.h" -#include "tqdeepcopy.h" -#if defined(QT_LARGEFILE_SUPPORT) -#include -#endif - - -extern bool qt_file_access( const TQString& fn, int t ); - -/*! - \class TQFileInfo - \reentrant - \brief The TQFileInfo class provides system-independent file information. - - \ingroup io - - TQFileInfo provides information about a file's name and position - (path) in the file system, its access rights and whether it is a - directory or symbolic link, etc. The file's size and last - modified/read times are also available. - - A TQFileInfo can point to a file with either a relative or an - absolute file path. Absolute file paths begin with the directory - separator "/" (or with a drive specification on Windows). Relative - file names begin with a directory name or a file name and specify - a path relative to the current working directory. An example of an - absolute path is the string "/tmp/quartz". A relative path might - look like "src/fatlib". You can use the function isRelative() to - check whether a TQFileInfo is using a relative or an absolute file - path. You can call the function convertToAbs() to convert a - relative TQFileInfo's path to an absolute path. - - The file that the TQFileInfo works on is set in the constructor or - later with setFile(). Use exists() to see if the file exists and - size() to get its size. - - To speed up performance, TQFileInfo caches information about the - file. Because files can be changed by other users or programs, or - even by other parts of the same program, there is a function that - refreshes the file information: refresh(). If you want to switch - off a TQFileInfo's caching and force it to access the file system - every time you request information from it call setCaching(FALSE). - - The file's type is obtained with isFile(), isDir() and - isSymLink(). The readLink() function provides the name of the file - the symlink points to. - - Elements of the file's name can be extracted with dirPath() and - fileName(). The fileName()'s parts can be extracted with - baseName() and extension(). - - The file's dates are returned by created(), lastModified() and - lastRead(). Information about the file's access permissions is - obtained with isReadable(), isWritable() and isExecutable(). The - file's ownership is available from owner(), ownerId(), group() and - groupId(). You can examine a file's permissions and ownership in a - single statement using the permission() function. - - If you need to read and traverse directories, see the TQDir class. -*/ - -/*! - \enum TQFileInfo::PermissionSpec - - This enum is used by the permission() function to report the - permissions and ownership of a file. The values may be OR-ed - together to test multiple permissions and ownership values. - - \value ReadOwner The file is readable by the owner of the file. - \value WriteOwner The file is writable by the owner of the file. - \value ExeOwner The file is executable by the owner of the file. - \value ReadUser The file is readable by the user. - \value WriteUser The file is writable by the user. - \value ExeUser The file is executable by the user. - \value ReadGroup The file is readable by the group. - \value WriteGroup The file is writable by the group. - \value ExeGroup The file is executable by the group. - \value ReadOther The file is readable by anyone. - \value WriteOther The file is writable by anyone. - \value ExeOther The file is executable by anyone. - - \warning The semantics of \c ReadUser, \c WriteUser and \c ExeUser are - unfortunately not platform independent: on Unix, the rights of the owner of - the file are returned and on Windows the rights of the current user are - returned. This behavior might change in a future TQt version. If you want to - find the rights of the owner of the file, you should use the flags \c - ReadOwner, \c WriteOwner and \c ExeOwner. If you want to find out the - rights of the current user, you should use isReadable(), isWritable() and - isExecutable(). -*/ - - -/*! - Constructs a new empty TQFileInfo. -*/ - -TQFileInfo::TQFileInfo() -{ - fic = 0; - cache = TRUE; -#if defined(Q_OS_UNIX) - symLink = FALSE; -#endif -} - -/*! - Constructs a new TQFileInfo that gives information about the given - file. The \a file can also include an absolute or relative path. - - \warning Some functions might behave in a counter-intuitive way - if \a file has a trailing directory separator. - - \sa setFile(), isRelative(), TQDir::setCurrent(), TQDir::isRelativePath() -*/ - -TQFileInfo::TQFileInfo( const TQString &file ) -{ - fn = file; - slashify( fn ); - fic = 0; - cache = TRUE; -#if defined(Q_OS_UNIX) - symLink = FALSE; -#endif -} - -/*! - Constructs a new TQFileInfo that gives information about file \a - file. - - If the \a file has a relative path, the TQFileInfo will also have a - relative path. - - \sa isRelative() -*/ - -TQFileInfo::TQFileInfo( const TQFile &file ) -{ - fn = file.name(); - slashify( fn ); - fic = 0; - cache = TRUE; -#if defined(Q_OS_UNIX) - symLink = FALSE; -#endif -} - -/*! - Constructs a new TQFileInfo that gives information about the file - called \a fileName in the directory \a d. - - If \a d has a relative path, the TQFileInfo will also have a - relative path. - - \sa isRelative() -*/ -#ifndef TQT_NO_DIR -TQFileInfo::TQFileInfo( const TQDir &d, const TQString &fileName ) -{ - fn = d.filePath( fileName ); - slashify( fn ); - fic = 0; - cache = TRUE; -#if defined(Q_OS_UNIX) - symLink = FALSE; -#endif -} -#endif -/*! - Constructs a new TQFileInfo that is a copy of \a fi. -*/ - -TQFileInfo::TQFileInfo( const TQFileInfo &fi ) -{ - fn = fi.fn; - if ( fi.fic ) { - fic = new TQFileInfoCache; - *fic = *fi.fic; - } else { - fic = 0; - } - cache = fi.cache; -#if defined(Q_OS_UNIX) - symLink = fi.symLink; -#endif -} - -/*! - Destroys the TQFileInfo and frees its resources. -*/ - -TQFileInfo::~TQFileInfo() -{ - delete fic; -} - - -/*! - Makes a copy of \a fi and assigns it to this TQFileInfo. -*/ - -TQFileInfo &TQFileInfo::operator=( const TQFileInfo &fi ) -{ - fn = fi.fn; - if ( !fi.fic ) { - delete fic; - fic = 0; - } else { - if ( !fic ) { - fic = new TQFileInfoCache; - TQ_CHECK_PTR( fic ); - } - *fic = *fi.fic; - } - cache = fi.cache; -#if defined(Q_OS_UNIX) - symLink = fi.symLink; -#endif - return *this; -} - - -/*! - Sets the file that the TQFileInfo provides information about to \a - file. - - The \a file can also include an absolute or relative file path. - Absolute paths begin with the directory separator (e.g. "/" under - Unix) or a drive specification (under Windows). Relative file - names begin with a directory name or a file name and specify a - path relative to the current directory. - - Example: - \code - TQString absolute = "/local/bin"; - TQString relative = "local/bin"; - TQFileInfo absFile( absolute ); - TQFileInfo relFile( relative ); - - TQDir::setCurrent( TQDir::rootDirPath() ); - // absFile and relFile now point to the same file - - TQDir::setCurrent( "/tmp" ); - // absFile now points to "/local/bin", - // while relFile points to "/tmp/local/bin" - \endcode - - \sa isRelative(), TQDir::setCurrent(), TQDir::isRelativePath() -*/ - -void TQFileInfo::setFile( const TQString &file ) -{ - fn = file; - slashify( fn ); - delete fic; - fic = 0; -} - -/*! - \overload - - Sets the file that the TQFileInfo provides information about to \a - file. - - If \a file includes a relative path, the TQFileInfo will also have - a relative path. - - \sa isRelative() -*/ - -void TQFileInfo::setFile( const TQFile &file ) -{ - fn = file.name(); - slashify( fn ); - delete fic; - fic = 0; -} - -/*! - \overload - - Sets the file that the TQFileInfo provides information about to \a - fileName in directory \a d. - - If \a fileName includes a relative path, the TQFileInfo will also - have a relative path. - - \sa isRelative() -*/ -#ifndef TQT_NO_DIR -void TQFileInfo::setFile( const TQDir &d, const TQString &fileName ) -{ - fn = d.filePath( fileName ); - slashify( fn ); - delete fic; - fic = 0; -} -#endif - -/*! - Returns TRUE if the file exists; otherwise returns FALSE. -*/ - -bool TQFileInfo::exists() const -{ - return qt_file_access( fn, F_OK ); -} - -/*! - Refreshes the information about the file, i.e. reads in information - from the file system the next time a cached property is fetched. - - \sa setCaching() -*/ - -void TQFileInfo::refresh() const -{ - TQFileInfo *that = (TQFileInfo*)this; // Mutable function - delete that->fic; - that->fic = 0; -} - -/*! - \fn bool TQFileInfo::caching() const - - Returns TRUE if caching is enabled; otherwise returns FALSE. - - \sa setCaching(), refresh() -*/ - -/*! - If \a enable is TRUE, enables caching of file information. If \a - enable is FALSE caching is disabled. - - When caching is enabled, TQFileInfo reads the file information from - the file system the first time it's needed, but generally not - later. - - Caching is enabled by default. - - \sa refresh(), caching() -*/ - -void TQFileInfo::setCaching( bool enable ) -{ - if ( cache == enable ) - return; - cache = enable; - if ( cache ) { - delete fic; - fic = 0; - } -} - - -/*! - Returns the file name, including the path (which may be absolute - or relative). - - \sa isRelative(), absFilePath() -*/ - -TQString TQFileInfo::filePath() const -{ - return fn; -} - -/*! - Returns the base name of the file. - - If \a complete is FALSE (the default) the base name consists of - all characters in the file name up to (but not including) the \e - first '.' character. - - If \a complete is TRUE the base name consists of all characters in - the file up to (but not including) the \e last '.' character. - - The path is not included in either case. - - Example: - \code - TQFileInfo fi( "/tmp/archive.tar.gz" ); - TQString base = fi.baseName(); // base = "archive" - base = fi.baseName( TRUE ); // base = "archive.tar" - \endcode - - \sa fileName(), extension() -*/ - -TQString TQFileInfo::baseName( bool complete ) const -{ - TQString tmp = fileName(); - int pos = complete ? tmp.findRev( '.' ) : tmp.find( '.' ); - if ( pos == -1 ) - return tmp; - else - return tmp.left( pos ); -} - -/*! - Returns the file's extension name. - - If \a complete is TRUE (the default), extension() returns the - string of all characters in the file name after (but not - including) the first '.' character. - - If \a complete is FALSE, extension() returns the string of all - characters in the file name after (but not including) the last '.' - character. - - Example: - \code - TQFileInfo fi( "/tmp/archive.tar.gz" ); - TQString ext = fi.extension(); // ext = "tar.gz" - ext = fi.extension( FALSE ); // ext = "gz" - \endcode - - \sa fileName(), baseName() -*/ - -TQString TQFileInfo::extension( bool complete ) const -{ - TQString s = fileName(); - int pos = complete ? s.find( '.' ) : s.findRev( '.' ); - if ( pos < 0 ) - return TQString::fromLatin1( "" ); - else - return s.right( s.length() - pos - 1 ); -} - -/*! - Returns the file's path as a TQDir object. - - If the TQFileInfo is relative and \a absPath is FALSE, the TQDir - will be relative; otherwise it will be absolute. - - \sa dirPath(), filePath(), fileName(), isRelative() -*/ -#ifndef TQT_NO_DIR -TQDir TQFileInfo::dir( bool absPath ) const -{ - return TQDir( dirPath(absPath) ); -} -#endif - - -/*! - Returns TRUE if the file is readable; otherwise returns FALSE. - - \sa isWritable(), isExecutable(), permission() -*/ - -bool TQFileInfo::isReadable() const -{ -#ifdef TQ_WS_WIN - return qt_file_access( fn, R_OK ) && permission( ReadUser ); -#else - return qt_file_access( fn, R_OK ); -#endif -} - -/*! - Returns TRUE if the file is writable; otherwise returns FALSE. - - \sa isReadable(), isExecutable(), permission() -*/ - -bool TQFileInfo::isWritable() const -{ -#ifdef TQ_WS_WIN - return qt_file_access( fn, W_OK ) && permission( WriteUser ); -#else - return qt_file_access( fn, W_OK ); -#endif -} - -/*! - Returns TRUE if the file is executable; otherwise returns FALSE. - - \sa isReadable(), isWritable(), permission() -*/ - -bool TQFileInfo::isExecutable() const -{ -#ifdef TQ_WS_WIN -#if defined(_MSC_VER) && _MSC_VER >= 1400 - return permission( ExeUser ); -#else - return qt_file_access( fn, X_OK ) && permission( ExeUser ); -#endif //_MSC_VER >= 1400 -#else - return qt_file_access( fn, X_OK ); -#endif -} - -#ifndef TQ_WS_WIN -bool TQFileInfo::isHidden() const -{ - return fileName()[ 0 ] == TQChar( '.' ); -} -#endif - -/*! - Returns TRUE if the file path name is relative. Returns FALSE if - the path is absolute (e.g. under Unix a path is absolute if it - begins with a "/"). -*/ -#ifndef TQT_NO_DIR -bool TQFileInfo::isRelative() const -{ - return TQDir::isRelativePath( fn ); -} - -/*! - Converts the file's path to an absolute path. - - If it is already absolute, nothing is done. - - \sa filePath(), isRelative() -*/ - -bool TQFileInfo::convertToAbs() -{ - if ( isRelative() ) - fn = absFilePath(); - return TQDir::isRelativePath( fn ); -} -#endif - -/*! - Returns the file size in bytes, or 0 if the file does not exist or - if the size is 0 or if the size cannot be fetched. -*/ -uint TQFileInfo::size() const -{ - if ( !fic || !cache ) - doStat(); - if ( fic ) -#if defined(QT_LARGEFILE_SUPPORT) - return (uint)fic->st.st_size > UINT_MAX ? UINT_MAX : (uint)fic->st.st_size; -#else - return (uint)fic->st.st_size; -#endif - else - return 0; -} - -/*! - Returns the date and time when the file was created. - - On platforms where this information is not available, returns the - same as lastModified(). - - \sa created() lastModified() lastRead() -*/ - -TQDateTime TQFileInfo::created() const -{ - TQDateTime dt; - if ( !fic || !cache ) - doStat(); - if ( fic && fic->st.st_ctime != 0 ) { - dt.setTime_t( fic->st.st_ctime ); - return dt; - } else { - return lastModified(); - } -} - -/*! - Returns the date and time when the file was last modified. - - \sa created() lastModified() lastRead() -*/ - -TQDateTime TQFileInfo::lastModified() const -{ - TQDateTime dt; - if ( !fic || !cache ) - doStat(); - if ( fic ) - dt.setTime_t( fic->st.st_mtime ); - return dt; -} - -/*! - Returns the date and time when the file was last read (accessed). - - On platforms where this information is not available, returns the - same as lastModified(). - - \sa created() lastModified() lastRead() -*/ - -TQDateTime TQFileInfo::lastRead() const -{ - TQDateTime dt; - if ( !fic || !cache ) - doStat(); - if ( fic && fic->st.st_atime != 0 ) { - dt.setTime_t( fic->st.st_atime ); - return dt; - } else { - return lastModified(); - } -} - -#ifndef TQT_NO_DIR - -/*! - Returns the absolute path including the file name. - - The absolute path name consists of the full path and the file - name. On Unix this will always begin with the root, '/', - directory. On Windows this will always begin 'D:/' where D is a - drive letter, except for network shares that are not mapped to a - drive letter, in which case the path will begin '//sharename/'. - - This function returns the same as filePath(), unless isRelative() - is TRUE. - - If the TQFileInfo is empty it returns TQDir::currentDirPath(). - - This function can be time consuming under Unix (in the order of - milliseconds). - - \sa isRelative(), filePath() -*/ -TQString TQFileInfo::absFilePath() const -{ - TQString tmp; - if ( TQDir::isRelativePath(fn) -#if defined(Q_OS_WIN32) - && fn[1] != ':' -#endif - ) { - tmp = TQDir::currentDirPath(); - tmp += '/'; - } - tmp += fn; - makeAbs( tmp ); - return TQDir::cleanDirPath( tmp ); -} - -/*! \internal - Detaches all internal data. -*/ -void TQFileInfo::detach() -{ - fn = TQDeepCopy( fn ); - if ( fic ) { - TQFileInfoCache *cur = fic; - fic = new TQFileInfoCache; - *fic = *cur; - delete cur; - } -} - -#endif diff --git a/src/tools/qfileinfo_unix.cpp b/src/tools/qfileinfo_unix.cpp deleted file mode 100644 index 159b43ae2..000000000 --- a/src/tools/qfileinfo_unix.cpp +++ /dev/null @@ -1,400 +0,0 @@ -/**************************************************************************** -** -** Implementation of TQFileInfo class -** -** Created : 950628 -** -** Copyright (C) 1992-2008 Trolltech ASA. All rights reserved. -** -** This file is part of the tools module of the TQt GUI Toolkit. -** -** This file may be used under the terms of the GNU General -** Public License versions 2.0 or 3.0 as published by the Free -** Software Foundation and appearing in the files LICENSE.GPL2 -** and LICENSE.GPL3 included in the packaging of this file. -** Alternatively you may (at your option) use any later version -** of the GNU General Public License if such license has been -** publicly approved by Trolltech ASA (or its successors, if any) -** and the KDE Free TQt Foundation. -** -** Please review the following information to ensure GNU General -** Public Licensing requirements will be met: -** http://trolltech.com/products/qt/licenses/licensing/opensource/. -** If you are unsure which license is appropriate for your use, please -** review the following information: -** http://trolltech.com/products/qt/licenses/licensing/licensingoverview -** or contact the sales department at sales@trolltech.com. -** -** This file may be used under the terms of the Q Public License as -** defined by Trolltech ASA and appearing in the file LICENSE.TQPL -** included in the packaging of this file. Licensees holding valid TQt -** Commercial licenses may use this file in accordance with the TQt -** Commercial License Agreement provided with the Software. -** -** This file is provided "AS IS" with NO WARRANTY OF ANY KIND, -** INCLUDING THE WARRANTIES OF DESIGN, MERCHANTABILITY AND FITNESS FOR -** A PARTICULAR PURPOSE. Trolltech reserves all rights not granted -** herein. -** -**********************************************************************/ - -#include "qplatformdefs.h" -#include "ntqfileinfo.h" -#include "qfiledefs_p.h" -#include "tqdatetime.h" -#include "ntqdir.h" - -#include -#if defined(Q_OS_MAC) -# include -#endif -#if defined(Q_OS_HURD) -# include -#endif - -void TQFileInfo::slashify( TQString& ) -{ - return; -} - - -void TQFileInfo::makeAbs( TQString & ) -{ - return; -} - -/*! - Returns TRUE if this object points to a file. Returns FALSE if the - object points to something which isn't a file, e.g. a directory or - a symlink. - - \sa isDir(), isSymLink() -*/ -bool TQFileInfo::isFile() const -{ - if ( !fic || !cache ) - doStat(); - return fic ? (fic->st.st_mode & S_IFMT) == S_IFREG : FALSE; -} - -/*! - Returns TRUE if this object points to a directory or to a symbolic - link to a directory; otherwise returns FALSE. - - \sa isFile(), isSymLink() -*/ -bool TQFileInfo::isDir() const -{ - if ( !fic || !cache ) - doStat(); - return fic ? (fic->st.st_mode & S_IFMT) == S_IFDIR : FALSE; -} - -/*! - Returns TRUE if this object points to a symbolic link (or to a - shortcut on Windows, or an alias on Mac OS X); otherwise returns - FALSE. - - \sa isFile(), isDir(), readLink() -*/ - -bool TQFileInfo::isSymLink() const -{ - if ( !fic || !cache ) - doStat(); - if(symLink) - return TRUE; -#if defined(Q_OS_MAC) - { - FSRef fref; - if(FSPathMakeRef((const UInt8 *)TQFile::encodeName(fn).data(), &fref, NULL) == noErr) { - Boolean isAlias, isFolder; - if(FSIsAliasFile(&fref, &isAlias, &isFolder) == noErr) - return isAlias; - } - } -#endif - return FALSE; -} - -/*! - Returns the name a symlink (or shortcut on Windows) points to, or - a TQString::null if the object isn't a symbolic link. - - This name may not represent an existing file; it is only a string. - TQFileInfo::exists() returns TRUE if the symlink points to an - existing file. - - \sa exists(), isSymLink(), isDir(), isFile() -*/ - -TQString TQFileInfo::readLink() const -{ - if ( !isSymLink() ) - return TQString(); -#if defined(Q_OS_UNIX) && !defined(Q_OS_OS2EMX) -#if !defined(PATH_MAX) - int size = 256; - char *s = NULL, *s2; - - while (1) - { - s2 = (char *) realloc (s, size); - if (s2 == NULL) { - free( s ); - return TQString(); - } - s = s2; - int len = readlink ( TQFile::encodeName(fn).data(), s, size ); - if ( len < 0 ) { - free( s ); - return TQString(); - } - if ( len < size ) { - s[len] = '\0'; - TQString str = TQFile::decodeName(s); - free(s); - return str; - } - size *= 2; - } -#else - char s[PATH_MAX+1]; - int len = readlink( TQFile::encodeName(fn).data(), s, PATH_MAX ); - if ( len >= 0 ) { - s[len] = '\0'; - return TQFile::decodeName(s); - } -#endif /* !PATH_MAX */ -#endif /* Q_OS_UNIX && !Q_OS_OS2EMX */ -#if defined(Q_OS_MAC) - { - FSRef fref; - if(FSPathMakeRef((const UInt8 *)TQFile::encodeName(fn).data(), &fref, NULL) == noErr) { - Boolean isAlias, isFolder; - if(FSResolveAliasFile(&fref, TRUE, &isFolder, &isAlias) == noErr && isAlias) { - AliasHandle alias; - if(FSNewAlias(0, &fref, &alias) == noErr && alias) { - CFStringRef cfstr; - if(FSCopyAliasInfo(alias, 0, 0, &cfstr, 0, 0) == noErr) { - TQString cfstring2qstring(CFStringRef str); //qglobal.cpp - return cfstring2qstring(cfstr); - } - } - } - } - } -#endif - return TQString(); -} - -static const uint nobodyID = (uint) -2; - -/*! - Returns the owner of the file. On systems where files - do not have owners, or if an error occurs, TQString::null is - returned. - - This function can be time consuming under Unix (in the order of - milliseconds). - - \sa ownerId(), group(), groupId() -*/ - -TQString TQFileInfo::owner() const -{ - passwd *pw = getpwuid( ownerId() ); - if ( pw ) - return TQFile::decodeName( pw->pw_name ); - return TQString::null; -} - -/*! - Returns the id of the owner of the file. - - On Windows and on systems where files do not have owners this - function returns ((uint) -2). - - \sa owner(), group(), groupId() -*/ - -uint TQFileInfo::ownerId() const -{ - if ( !fic || !cache ) - doStat(); - if ( fic ) - return fic->st.st_uid; - return nobodyID; -} - -/*! - Returns the group of the file. On Windows, on systems where files - do not have groups, or if an error occurs, TQString::null is - returned. - - This function can be time consuming under Unix (in the order of - milliseconds). - - \sa groupId(), owner(), ownerId() -*/ - -TQString TQFileInfo::group() const -{ - struct group *gr = getgrgid( groupId() ); - if ( gr ) - return TQFile::decodeName( gr->gr_name ); - return TQString::null; -} - -/*! - Returns the id of the group the file belongs to. - - On Windows and on systems where files do not have groups this - function always returns (uint) -2. - - \sa group(), owner(), ownerId() -*/ - -uint TQFileInfo::groupId() const -{ - if ( !fic || !cache ) - doStat(); - if ( fic ) - return fic->st.st_gid; - return nobodyID; -} - - -/*! - Tests for file permissions. The \a permissionSpec argument can be - several flags of type \c PermissionSpec OR-ed together to check - for permission combinations. - - On systems where files do not have permissions this function - always returns TRUE. - - Example: - \code - TQFileInfo fi( "/tmp/archive.tar.gz" ); - if ( fi.permission( TQFileInfo::WriteUser | TQFileInfo::ReadGroup ) ) - tqWarning( "I can change the file; my group can read the file" ); - if ( fi.permission( TQFileInfo::WriteGroup | TQFileInfo::WriteOther ) ) - tqWarning( "The group or others can change the file" ); - \endcode - - \sa isReadable(), isWritable(), isExecutable() -*/ - -bool TQFileInfo::permission( int permissionSpec ) const -{ - if ( !fic || !cache ) - doStat(); - if ( fic ) { - uint mask = 0; - if ( permissionSpec & ReadOwner ) - mask |= S_IRUSR; - if ( permissionSpec & WriteOwner ) - mask |= S_IWUSR; - if ( permissionSpec & ExeOwner ) - mask |= S_IXUSR; - if ( permissionSpec & ReadUser ) - mask |= S_IRUSR; - if ( permissionSpec & WriteUser ) - mask |= S_IWUSR; - if ( permissionSpec & ExeUser ) - mask |= S_IXUSR; - if ( permissionSpec & ReadGroup ) - mask |= S_IRGRP; - if ( permissionSpec & WriteGroup ) - mask |= S_IWGRP; - if ( permissionSpec & ExeGroup ) - mask |= S_IXGRP; - if ( permissionSpec & ReadOther ) - mask |= S_IROTH; - if ( permissionSpec & WriteOther ) - mask |= S_IWOTH; - if ( permissionSpec & ExeOther ) - mask |= S_IXOTH; - if ( mask ) { - return (fic->st.st_mode & mask) == mask; - } else { -#if defined(QT_CHECK_NULL) - tqWarning( "TQFileInfo::permission: permissionSpec is 0" ); -#endif - return TRUE; - } - } else { - return FALSE; - } -} - -void TQFileInfo::doStat() const -{ - TQFileInfo *that = ((TQFileInfo*)this); // mutable function - if ( !that->fic ) - that->fic = new TQFileInfoCache; - that->symLink = FALSE; - struct stat *b = &that->fic->st; -#if defined(Q_OS_UNIX) && defined(S_IFLNK) - if ( ::lstat( TQFile::encodeName(fn), b ) == 0 ) { - if ( S_ISLNK( b->st_mode ) ) - that->symLink = TRUE; - else - return; - } -#endif - - int r = ::stat( TQFile::encodeName(fn), b ); - if ( r != 0 && !that->symLink ) { - delete that->fic; - that->fic = 0; - } -} - -/*! - Returns the file's path. - - If \a absPath is TRUE an absolute path is returned. - - \sa dir(), filePath(), fileName(), isRelative() -*/ -#ifndef TQT_NO_DIR -TQString TQFileInfo::dirPath( bool absPath ) const -{ - TQString s; - if ( absPath ) - s = absFilePath(); - else - s = fn; - int pos = s.findRev( '/' ); - if ( pos == -1 ) { - return TQString::fromLatin1( "." ); - } else { - if ( pos == 0 ) - return TQString::fromLatin1( "/" ); - return s.left( pos ); - } -} -#endif - -/*! - Returns the name of the file, excluding the path. - - Example: - \code - TQFileInfo fi( "/tmp/archive.tar.gz" ); - TQString name = fi.fileName(); // name = "archive.tar.gz" - \endcode - - \sa isRelative(), filePath(), baseName(), extension() -*/ - -TQString TQFileInfo::fileName() const -{ - int p = fn.findRev( '/' ); - if ( p == -1 ) { - return fn; - } else { - return fn.mid( p + 1 ); - } -} diff --git a/src/tools/qgdict.cpp b/src/tools/qgdict.cpp index 50d2816ee..dd35d64e3 100644 --- a/src/tools/qgdict.cpp +++ b/src/tools/qgdict.cpp @@ -41,7 +41,7 @@ #include "ntqgdict.h" #include "tqptrlist.h" #include "tqstring.h" -#include "ntqdatastream.h" +#include "tqdatastream.h" #include /*! diff --git a/src/tools/qglist.cpp b/src/tools/qglist.cpp index 95e66b38f..7ffa66d4d 100644 --- a/src/tools/qglist.cpp +++ b/src/tools/qglist.cpp @@ -40,7 +40,7 @@ #include "ntqglist.h" #include "ntqgvector.h" -#include "ntqdatastream.h" +#include "tqdatastream.h" #include "tqvaluelist.h" #if defined(TQT_THREAD_SUPPORT) diff --git a/src/tools/qgpluginmanager.cpp b/src/tools/qgpluginmanager.cpp index 3a7c321fd..b2b5bf63d 100644 --- a/src/tools/qgpluginmanager.cpp +++ b/src/tools/qgpluginmanager.cpp @@ -40,7 +40,7 @@ #ifndef TQT_NO_COMPONENT #include "qcomlibrary_p.h" #include "tqmap.h" -#include "ntqdir.h" +#include "tqdir.h" /* The following co-occurrence code is borrowed from TQt Linguist. diff --git a/src/tools/qgvector.cpp b/src/tools/qgvector.cpp index 1c6c8669e..03b502c0b 100644 --- a/src/tools/qgvector.cpp +++ b/src/tools/qgvector.cpp @@ -48,7 +48,7 @@ #include "ntqgvector.h" #include "ntqglist.h" #include "tqstring.h" -#include "ntqdatastream.h" +#include "tqdatastream.h" #include #ifdef TQT_THREAD_SUPPORT diff --git a/src/tools/qiodevice.cpp b/src/tools/qiodevice.cpp deleted file mode 100644 index cf069aa22..000000000 --- a/src/tools/qiodevice.cpp +++ /dev/null @@ -1,759 +0,0 @@ -/**************************************************************************** -** -** Implementation of TQIODevice class -** -** Created : 940913 -** -** Copyright (C) 1992-2008 Trolltech ASA. All rights reserved. -** -** This file is part of the tools module of the TQt GUI Toolkit. -** -** This file may be used under the terms of the GNU General -** Public License versions 2.0 or 3.0 as published by the Free -** Software Foundation and appearing in the files LICENSE.GPL2 -** and LICENSE.GPL3 included in the packaging of this file. -** Alternatively you may (at your option) use any later version -** of the GNU General Public License if such license has been -** publicly approved by Trolltech ASA (or its successors, if any) -** and the KDE Free TQt Foundation. -** -** Please review the following information to ensure GNU General -** Public Licensing requirements will be met: -** http://trolltech.com/products/qt/licenses/licensing/opensource/. -** If you are unsure which license is appropriate for your use, please -** review the following information: -** http://trolltech.com/products/qt/licenses/licensing/licensingoverview -** or contact the sales department at sales@trolltech.com. -** -** This file may be used under the terms of the Q Public License as -** defined by Trolltech ASA and appearing in the file LICENSE.TQPL -** included in the packaging of this file. Licensees holding valid TQt -** Commercial licenses may use this file in accordance with the TQt -** Commercial License Agreement provided with the Software. -** -** This file is provided "AS IS" with NO WARRANTY OF ANY KIND, -** INCLUDING THE WARRANTIES OF DESIGN, MERCHANTABILITY AND FITNESS FOR -** A PARTICULAR PURPOSE. Trolltech reserves all rights not granted -** herein. -** -**********************************************************************/ - -#include "ntqiodevice.h" - -/*! - \class TQIODevice ntqiodevice.h - \reentrant - - \brief The TQIODevice class is the base class of I/O devices. - - \ingroup io - - An I/O device represents a medium that one can read bytes from - and/or write bytes to. The TQIODevice class is the abstract - superclass of all such devices; classes such as TQFile, TQBuffer and - TQSocket inherit TQIODevice and implement virtual functions such as - write() appropriately. - - Although applications sometimes use TQIODevice directly, it is - usually better to use TQTextStream and TQDataStream, which provide - stream operations on any TQIODevice subclass. TQTextStream provides - text-oriented stream functionality (for human-readable ASCII - files, for example), whereas TQDataStream deals with binary data in - a totally platform-independent manner. - - The public member functions in TQIODevice roughly fall into two - groups: the action functions and the state access functions. The - most important action functions are: - - \list - - \i open() opens a device for reading and/or writing, depending on - the mode argument. - - \i close() closes the device and tidies up (e.g. flushes buffered - data) - - \i readBlock() reads a block of data from the device. - - \i writeBlock() writes a block of data to the device. - - \i readLine() reads a line (of text, usually) from the device. - - \i flush() ensures that all buffered data are written to the real device. - - \endlist - - There are also some other, less used, action functions: - - \list - - \i getch() reads a single character. - - \i ungetch() forgets the last call to getch(), if possible. - - \i putch() writes a single character. - - \i size() returns the size of the device, if there is one. - - \i at() returns the current read/write pointer's position, if there - is one for this device, or it moves the pointer if given an offset. - - \i atEnd() indicates whether there is more to read, if this is - meaningful for this device. - - \i reset() moves the read/write pointer to the start of the - device, if that is possible for this device. - - \endlist - - The state access are all "get" functions. The TQIODevice subclass - calls setState() to update the state, and simple access functions - tell the user of the device what the device's state is. Here are - the settings, and their associated access functions: - - \list - - \i Access type. Some devices are direct access (it is possible - to read/write anywhere), whereas others are sequential. TQIODevice - provides the access functions (isDirectAccess(), - isSequentialAccess(), and isCombinedAccess()) to tell users what a - given I/O device supports. - - \i Buffering. Some devices are accessed in raw mode, whereas - others are buffered. Buffering usually provides greater - efficiency, particularly for small read/write operations. - isBuffered() tells the user whether a given device is buffered. - (This can often be set by the application in the call to open().) - - \i Synchronicity. Synchronous devices work immediately (for - example, files). When you read from a file, the file delivers its - data straight away. Other kinds of device, such as a socket - connected to a HTTP server, may not deliver the data until seconds - after you ask to read it. isSynchronous() and isAsynchronous() - tell the user how this device operates. - - \i CR/LF translation. For simplicity, applications often like to - see just a single CR/LF style, and TQIODevice subclasses can - provide this. isTranslated() returns TRUE if this object - translates CR/LF to just LF. (This can often be set by the - application in the call to open().) - - \i Permissions. Some files cannot be written. For example, - isReadable(), isWritable() and isReadWrite() tell the application - whether it can read from and write to a given device. (This can - often be set by the application in the call to open().) - - \i Finally, isOpen() returns TRUE if the device is open, i.e. - after an open() call. - - \endlist - - TQIODevice provides numerous pure virtual functions that you need - to implement when subclassing it. Here is a skeleton subclass with - all the members you are sure to need and some that you will - probably need: - - \code - class MyDevice : public TQIODevice - { - public: - MyDevice(); - ~MyDevice(); - - bool open( int mode ); - void close(); - void flush(); - - uint size() const; - int at() const; // non-pure virtual - bool at( int ); // non-pure virtual - bool atEnd() const; // non-pure virtual - - int readBlock( char *data, uint maxlen ); - int writeBlock( const char *data, uint len ); - int readLine( char *data, uint maxlen ); - - int getch(); - int putch( int ); - int ungetch( int ); - }; - \endcode - - The three non-pure virtual functions need not be reimplemented for - sequential devices. - - \sa TQDataStream, TQTextStream -*/ - -/*! - \enum TQIODevice::Offset - - The offset within the device. -*/ - - -/*! - Constructs an I/O device. -*/ - -TQIODevice::TQIODevice() -{ - ioMode = 0; // initial mode - ioSt = IO_Ok; - ioIndex = 0; -} - -/*! - Destroys the I/O device. -*/ - -TQIODevice::~TQIODevice() -{ -} - - -/*! - \fn int TQIODevice::flags() const - - Returns the current I/O device flags setting. - - Flags consists of mode flags and state flags. - - \sa mode(), state() -*/ - -/*! - \fn int TQIODevice::mode() const - - Returns bits OR'ed together that specify the current operation - mode. - - These are the flags that were given to the open() function. - - The flags are \c IO_ReadOnly, \c IO_WriteOnly, \c IO_ReadWrite, - \c IO_Append, \c IO_Truncate and \c IO_Translate. -*/ - -/*! - \fn int TQIODevice::state() const - - Returns bits OR'ed together that specify the current state. - - The flags are: \c IO_Open. - - Subclasses may define additional flags. -*/ - -/*! - \fn bool TQIODevice::isDirectAccess() const - - Returns TRUE if the I/O device is a direct access device; - otherwise returns FALSE, i.e. if the device is a sequential access - device. - - \sa isSequentialAccess() -*/ - -/*! - \fn bool TQIODevice::isSequentialAccess() const - - Returns TRUE if the device is a sequential access device; - otherwise returns FALSE, i.e. if the device is a direct access - device. - - Operations involving size() and at(int) are not valid on - sequential devices. - - \sa isDirectAccess() -*/ - -/*! - \fn bool TQIODevice::isCombinedAccess() const - - Returns TRUE if the I/O device is a combined access (both direct - and sequential) device; otherwise returns FALSE. - - This access method is currently not in use. -*/ - -/*! - \fn bool TQIODevice::isBuffered() const - - Returns TRUE if the I/O device is a buffered device; otherwise - returns FALSE, i.e. the device is a raw device. - - \sa isRaw() -*/ - -/*! - \fn bool TQIODevice::isRaw() const - - Returns TRUE if the device is a raw device; otherwise returns - FALSE, i.e. if the device is a buffered device. - - \sa isBuffered() -*/ - -/*! - \fn bool TQIODevice::isSynchronous() const - - Returns TRUE if the I/O device is a synchronous device; otherwise - returns FALSE, i.e. the device is an asynchronous device. - - \sa isAsynchronous() -*/ - -/*! - \fn bool TQIODevice::isAsynchronous() const - - Returns TRUE if the device is an asynchronous device; otherwise - returns FALSE, i.e. if the device is a synchronous device. - - This mode is currently not in use. - - \sa isSynchronous() -*/ - -/*! - \fn bool TQIODevice::isTranslated() const - - Returns TRUE if the I/O device translates carriage-return and - linefeed characters; otherwise returns FALSE. - - A TQFile is translated if it is opened with the \c IO_Translate - mode flag. -*/ - -/*! - \fn bool TQIODevice::isReadable() const - - Returns TRUE if the I/O device was opened using \c IO_ReadOnly or - \c IO_ReadWrite mode; otherwise returns FALSE. - - \sa isWritable(), isReadWrite() -*/ - -/*! - \fn bool TQIODevice::isWritable() const - - Returns TRUE if the I/O device was opened using \c IO_WriteOnly or - \c IO_ReadWrite mode; otherwise returns FALSE. - - \sa isReadable(), isReadWrite() -*/ - -/*! - \fn bool TQIODevice::isReadWrite() const - - Returns TRUE if the I/O device was opened using \c IO_ReadWrite - mode; otherwise returns FALSE. - - \sa isReadable(), isWritable() -*/ - -/*! - \fn bool TQIODevice::isInactive() const - - Returns TRUE if the I/O device state is 0, i.e. the device is not - open; otherwise returns FALSE. - - \sa isOpen() -*/ - -/*! - \fn bool TQIODevice::isOpen() const - - Returns TRUE if the I/O device has been opened; otherwise returns - FALSE. - - \sa isInactive() -*/ - - -/*! - \fn int TQIODevice::status() const - - Returns the I/O device status. - - The I/O device status returns an error code. If open() returns - FALSE or readBlock() or writeBlock() return -1, this function can - be called to find out the reason why the operation failed. - - \keyword IO_Ok - \keyword IO_ReadError - \keyword IO_WriteError - \keyword IO_FatalError - \keyword IO_OpenError - \keyword IO_ConnectError - \keyword IO_AbortError - \keyword IO_TimeOutError - \keyword IO_UnspecifiedError - - The status codes are: - \table - \header \i Status code \i Meaning - \row \i \c IO_Ok \i The operation was successful. - \row \i \c IO_ReadError \i Could not read from the device. - \row \i \c IO_WriteError \i Could not write to the device. - \row \i \c IO_FatalError \i A fatal unrecoverable error occurred. - \row \i \c IO_OpenError \i Could not open the device. - \row \i \c IO_ConnectError \i Could not connect to the device. - \row \i \c IO_AbortError \i The operation was unexpectedly aborted. - \row \i \c IO_TimeOutError \i The operation timed out. - \row \i \c IO_UnspecifiedError \i An unspecified error happened on close. - \endtable - - \sa resetStatus() -*/ - -/*! - \fn void TQIODevice::resetStatus() - - Sets the I/O device status to \c IO_Ok. - - \sa status() -*/ - - -/*! - \fn void TQIODevice::setFlags( int flags ) - - Used by subclasses to set the device flags to the \a flags specified. -*/ - -/*! - \fn void TQIODevice::setType( int type ) - - Used by subclasses to set the device type to the \a type specified. -*/ - -void TQIODevice::setType( int t ) -{ -#if defined(QT_CHECK_RANGE) - if ( (t & IO_TypeMask) != t ) - tqWarning( "TQIODevice::setType: Specified type out of range" ); -#endif - ioMode &= ~IO_TypeMask; // reset type bits - ioMode |= t; -} - -/*! - \fn void TQIODevice::setMode( int mode ) - - Used by subclasses to set the device mode to the \a mode specified. -*/ - -void TQIODevice::setMode( int m ) -{ -#if defined(QT_CHECK_RANGE) - if ( (m & IO_ModeMask) != m ) - tqWarning( "TQIODevice::setMode: Specified mode out of range" ); -#endif - ioMode &= ~IO_ModeMask; // reset mode bits - ioMode |= m; -} - -/*! - \fn void TQIODevice::setState( int state ) - - Used by subclasses to set the device state to the \a state specified. -*/ - -void TQIODevice::setState( int s ) -{ -#if defined(QT_CHECK_RANGE) - if ( ((uint)s & IO_StateMask) != (uint)s ) - tqWarning( "TQIODevice::setState: Specified state out of range" ); -#endif - ioMode &= ~IO_StateMask; // reset state bits - ioMode |= (uint)s; -} - -/*! - Used by subclasses to set the device status (not state) to \a s. -*/ - -void TQIODevice::setStatus( int s ) -{ - ioSt = s; -} - - -/*! - \fn bool TQIODevice::open( int mode ) - - Opens the I/O device using the specified \a mode. Returns TRUE if - the device was successfully opened; otherwise returns FALSE. - - The mode parameter \a mode must be an OR'ed combination of the - following flags. - \table - \header \i Mode flags \i Meaning - \row \i \c IO_Raw \i specifies raw (unbuffered) file access. - \row \i \c IO_ReadOnly \i opens a file in read-only mode. - \row \i \c IO_WriteOnly \i opens a file in write-only mode. - \row \i \c IO_ReadWrite \i opens a file in read/write mode. - \row \i \c IO_Append \i sets the file index to the end of the file. - \row \i \c IO_Truncate \i truncates the file. - \row \i \c IO_Translate \i enables carriage returns and linefeed - translation for text files under MS-DOS, Windows and Macintosh. On - Unix systems this flag has no effect. Use with caution as it will - also transform every linefeed written to the file into a CRLF - pair. This is likely to corrupt your file if you write write - binary data. Cannot be combined with \c IO_Raw. - \endtable - - This virtual function must be reimplemented by all subclasses. - - \sa close() -*/ - -/*! - \fn void TQIODevice::close() - - Closes the I/O device. - - This virtual function must be reimplemented by all subclasses. - - \sa open() -*/ - -/*! - \fn void TQIODevice::flush() - - Flushes an open I/O device. - - This virtual function must be reimplemented by all subclasses. -*/ - - -/*! - \fn TQIODevice::Offset TQIODevice::size() const - - Virtual function that returns the size of the I/O device. - - \sa at() -*/ - -/*! - Virtual function that returns the current I/O device position. - - This is the position of the data read/write head of the I/O - device. - - \sa size() -*/ - -TQIODevice::Offset TQIODevice::at() const -{ - return ioIndex; -} - - -/* - The following is a "bad" overload, since it does "not behave essentially - the same" like the above. So don't use \overload in the documentation of - this function and we have to live with the qdoc warning which is generated - for this. -*/ -/*! - Virtual function that sets the I/O device position to \a pos. - Returns TRUE if the position was successfully set, i.e. \a pos is - within range and the seek was successful; otherwise returns FALSE. - - \sa size() -*/ - -bool TQIODevice::at( Offset pos ) -{ -#if defined(QT_CHECK_RANGE) - if ( pos > size() ) { - tqWarning( "TQIODevice::at: Index %lu out of range", pos ); - return FALSE; - } -#endif - ioIndex = pos; - return TRUE; -} - -/*! - Virtual function that returns TRUE if the I/O device position is - at the end of the input; otherwise returns FALSE. -*/ - -bool TQIODevice::atEnd() const -{ - if ( isSequentialAccess() || isTranslated() ) { - TQIODevice* that = (TQIODevice*)this; - const int oldStatus = ioSt; - int c = that->getch(); - bool result = c < 0; - that->ungetch(c); - if (ioSt != oldStatus) - that->ioSt = oldStatus; - return result; - } else { - return at() == size(); - } -} - -/*! - \fn bool TQIODevice::reset() - - Sets the device index position to 0. - - \sa at() -*/ - - -/*! - \fn int TQIODevice::readBlock( char *data, TQ_ULONG maxlen ) - - Reads at most \a maxlen bytes from the I/O device into \a data and - returns the number of bytes actually read. - - This function should return -1 if a fatal error occurs and should - return 0 if there are no bytes to read. - - The device must be opened for reading, and \a data must not be 0. - - This virtual function must be reimplemented by all subclasses. - - \sa writeBlock() isOpen() isReadable() -*/ - -/*! - This convenience function returns all of the remaining data in the - device. -*/ -TQByteArray TQIODevice::readAll() -{ - if ( isDirectAccess() ) { - // we know the size - int n = size()-at(); // ### fix for 64-bit or large files? - int totalRead = 0; - TQByteArray ba( n ); - char* c = ba.data(); - while ( n ) { - int r = readBlock( c, n ); - if ( r < 0 ) - return TQByteArray(); - n -= r; - c += r; - totalRead += r; - // If we have a translated file, then it is possible that - // we read less bytes than size() reports - if ( atEnd() ) { - ba.resize( totalRead ); - break; - } - } - return ba; - } else { - // read until we reach the end - const int blocksize = 512; - int nread = 0; - TQByteArray ba; - while ( !atEnd() ) { - ba.resize( nread + blocksize ); - int r = readBlock( ba.data()+nread, blocksize ); - if ( r < 0 ) - return TQByteArray(); - nread += r; - } - ba.resize( nread ); - return ba; - } -} - -/*! - \fn int TQIODevice::writeBlock( const char *data, TQ_ULONG len ) - - Writes \a len bytes from \a data to the I/O device and returns the - number of bytes actually written. - - This function should return -1 if a fatal error occurs. - - This virtual function must be reimplemented by all subclasses. - - \sa readBlock() -*/ - -/*! - \overload - - This convenience function is the same as calling writeBlock( - data.data(), data.size() ). -*/ -TQ_LONG TQIODevice::writeBlock( const TQByteArray& data ) -{ - return writeBlock( data.data(), data.size() ); -} - -/*! - Reads a line of text, (or up to \a maxlen bytes if a newline isn't - encountered) plus a terminating '\0' into \a data. If there is a - newline at the end if the line, it is not stripped. - - Returns the number of bytes read including the terminating '\0', - or -1 if an error occurred. - - This virtual function can be reimplemented much more efficiently - by the most subclasses. - - \sa readBlock(), TQTextStream::readLine() -*/ - -TQ_LONG TQIODevice::readLine( char *data, TQ_ULONG maxlen ) -{ - if ( maxlen == 0 ) // application bug? - return 0; - char *p = data; - while ( --maxlen && (readBlock(p,1)>0) ) { // read one byte at a time - if ( *p++ == '\n' ) // end of line - break; - } - *p++ = '\0'; - return p - data; -} - - -/*! - \fn int TQIODevice::getch() - - Reads a single byte/character from the I/O device. - - Returns the byte/character read, or -1 if the end of the I/O - device has been reached. - - This virtual function must be reimplemented by all subclasses. - - \sa putch(), ungetch() -*/ - -/*! - \fn int TQIODevice::putch( int ch ) - - Writes the character \a ch to the I/O device. - - Returns \a ch, or -1 if an error occurred. - - This virtual function must be reimplemented by all subclasses. - - \sa getch(), ungetch() -*/ - -/*! - \fn int TQIODevice::ungetch( int ch ) - - Puts the character \a ch back into the I/O device and decrements - the index position if it is not zero. - - This function is normally called to "undo" a getch() operation. - - Returns \a ch, or -1 if an error occurred. - - This virtual function must be reimplemented by all subclasses. - - \sa getch(), putch() -*/ diff --git a/src/tools/qlibrary.cpp b/src/tools/qlibrary.cpp index 002f33215..6b586fcdf 100644 --- a/src/tools/qlibrary.cpp +++ b/src/tools/qlibrary.cpp @@ -41,7 +41,7 @@ #include "qplatformdefs.h" #include #include -#include +#include #ifndef TQT_NO_LIBRARY diff --git a/src/tools/qsettings.cpp b/src/tools/qsettings.cpp deleted file mode 100644 index e76fc6ca7..000000000 --- a/src/tools/qsettings.cpp +++ /dev/null @@ -1,2128 +0,0 @@ -/**************************************************************************** -** -** Implementation of TQSettings class -** -** Created : 000626 -** -** Copyright (C) 2000-2008 Trolltech ASA. All rights reserved. -** -** This file is part of the tools module of the TQt GUI Toolkit. -** -** This file may be used under the terms of the GNU General -** Public License versions 2.0 or 3.0 as published by the Free -** Software Foundation and appearing in the files LICENSE.GPL2 -** and LICENSE.GPL3 included in the packaging of this file. -** Alternatively you may (at your option) use any later version -** of the GNU General Public License if such license has been -** publicly approved by Trolltech ASA (or its successors, if any) -** and the KDE Free TQt Foundation. -** -** Please review the following information to ensure GNU General -** Public Licensing requirements will be met: -** http://trolltech.com/products/qt/licenses/licensing/opensource/. -** If you are unsure which license is appropriate for your use, please -** review the following information: -** http://trolltech.com/products/qt/licenses/licensing/licensingoverview -** or contact the sales department at sales@trolltech.com. -** -** This file may be used under the terms of the Q Public License as -** defined by Trolltech ASA and appearing in the file LICENSE.TQPL -** included in the packaging of this file. Licensees holding valid TQt -** Commercial licenses may use this file in accordance with the TQt -** Commercial License Agreement provided with the Software. -** -** This file is provided "AS IS" with NO WARRANTY OF ANY KIND, -** INCLUDING THE WARRANTIES OF DESIGN, MERCHANTABILITY AND FITNESS FOR -** A PARTICULAR PURPOSE. Trolltech reserves all rights not granted -** herein. -** -**********************************************************************/ - -#include "qplatformdefs.h" -#include - -// POSIX Large File Support redefines open -> open64 -static inline int qt_open( const char *pathname, int flags, mode_t mode ) -{ return ::open( pathname, flags, mode ); } -#if defined(open) -# undef open -#endif - -// POSIX Large File Support redefines truncate -> truncate64 -#if defined(truncate) -# undef truncate -#endif - -#include "ntqsettings.h" - -#ifndef TQT_NO_SETTINGS - -#include "ntqdir.h" -#include "ntqfile.h" -#include "ntqfileinfo.h" -#include "tqmap.h" -#include "tqtextstream.h" -#include "tqregexp.h" -#include -#ifndef NO_ERRNO_H -#include -#endif - -/*! - \class TQSettings - \brief The TQSettings class provides persistent platform-independent application settings. - - \ingroup io - \ingroup misc - \mainclass - - On Unix systems, TQSettings uses text files to store settings. On Windows - systems, TQSettings uses the system registry. On Mac OS X, TQSettings uses - the Carbon preferences API. - - Each setting comprises an identifying key and the data associated with - the key. A key is a unicode string which consists of \e two or more - subkeys. A subkey is a slash, '/', followed by one or more unicode - characters (excluding slashes, newlines, carriage returns and equals, - '=', signs). The associated data, called the entry or value, may be a - boolean, an integer, a double, a string or a list of strings. Entry - strings may contain any unicode characters. - - If you want to save and restore the entire desktop's settings, i.e. - which applications are running, use TQSettings to save the settings - for each individual application and TQSessionManager to save the - desktop's session. - - Example settings: - \code - /MyCompany/MyApplication/background color - /MyCompany/MyApplication/foreground color - /MyCompany/MyApplication/geometry/x - /MyCompany/MyApplication/geometry/y - /MyCompany/MyApplication/geometry/width - /MyCompany/MyApplication/geometry/height - /MyCompany/MyApplication/recent files/1 - /MyCompany/MyApplication/recent files/2 - /MyCompany/MyApplication/recent files/3 - \endcode - Each line above is a complete key, made up of subkeys. - - A typical usage pattern for reading settings at application - startup: - \code - TQSettings settings; - settings.setPath( "MyCompany.com", "MyApplication" ); - - TQString bgColor = settings.readEntry( "/colors/background", "white" ); - int width = settings.readNumEntry( "/geometry/width", 640 ); - // ... - \endcode - - A typical usage pattern for saving settings at application exit or - 'save preferences': - \code - TQSettings settings; - settings.setPath( "MyCompany.com", "MyApplication" ); - - settings.writeEntry( "/colors/background", bgColor ); - settings.writeEntry( "/geometry/width", width ); - // ... - \endcode - - A key prefix can be prepended to all keys using beginGroup(). The - application of the prefix is stopped using endGroup(). For - example: - \code - TQSettings settings; - - settings.beginGroup( "/MainWindow" ); - settings.beginGroup( "/Geometry" ); - int x = settings.readEntry( "/x" ); - // ... - settings.endGroup(); - settings.beginGroup( "/Toolbars" ); - // ... - settings.endGroup(); - settings.endGroup(); - \endcode - - You can get a list of entry-holding keys by calling entryList(), and - a list of key-holding keys using subkeyList(). - - \code - TQStringList keys = settings.entryList( "/MyApplication" ); - // keys contains 'background color' and 'foreground color'. - - TQStringList keys = settings.entryList( "/MyApplication/recent files" ); - // keys contains '1', '2' and '3'. - - TQStringList subkeys = settings.subkeyList( "/MyApplication" ); - // subkeys contains 'geometry' and 'recent files' - - TQStringList subkeys = settings.subkeyList( "/MyApplication/recent files" ); - // subkeys is empty. - \endcode - - Since settings for Windows are stored in the registry there are - some size limitations as follows: - \list - \i A subkey may not exceed 255 characters. - \i An entry's value may not exceed 16,300 characters. - \i All the values of a key (for example, all the 'recent files' - subkeys values), may not exceed 65,535 characters. - \endlist - - These limitations are not enforced on Unix or Mac OS X. - - \warning Creating multiple, simultaneous instances of TQSettings writing - to a text file may lead to data loss! This is a known issue which will - be fixed in a future release of TQt. - - \section1 Notes for Mac OS X Applications - - The location where settings are stored is not formally defined by - the CFPreferences API. - - At the time of writing settings are stored (either on a global or - user basis, preferring locally) into a plist file in \c - $ROOT/System/Library/Preferences (in XML format). TQSettings will - create an appropriate plist file (\c{com..plist}) - out of the full path to a key. - - For further information on CFPreferences see - \link http://developer.apple.com/documentation/CoreFoundation/Conceptual/CFPreferences/index.html - Apple's Specifications\endlink - - \section1 Notes for Unix Applications - - There is no universally accepted place for storing application - settings under Unix. In the examples the settings file will be - searched for in the following directories: - \list 1 - \i \c SYSCONF - the default value is \c INSTALL/etc/settings - \i \c /opt/MyCompany/share/etc - \i \c /opt/MyCompany/share/MyApplication/etc - \i \c $HOME/.qt - \endlist - When reading settings the files are searched in the order shown - above, with later settings overriding earlier settings. Files for - which the user doesn't have read permission are ignored. When saving - settings TQSettings works in the order shown above, writing - to the first settings file for which the user has write permission. - (\c INSTALL is the directory where TQt was installed. This can be - modified by using the configure script's -prefix argument ) - - If you want to put the settings in a particular place in the - filesystem you could do this: - \code - settings.insertSearchPath( TQSettings::Unix, "/opt/MyCompany/share" ); - \endcode - - But in practice you may prefer not to use a search path for Unix. - For example the following code: - \code - settings.writeEntry( "/MyApplication/geometry/width", width ); - \endcode - will end up writing the "geometry/width" setting to the file - \c{$HOME/.qt/myapplicationrc} (assuming that the application is - being run by an ordinary user, i.e. not by root). - - For cross-platform applications you should ensure that the - \link #sizelimit Windows size limitations \endlink are not exceeded. - - \warning TQSettings doesn't write the settings until it is destroyed so - you should construct the TQSettings object on the stack. -*/ - -/*! - \enum TQSettings::System - - \value Mac Macintosh execution environments - \value Unix Mac OS X, Unix, Linux and Unix-like execution environments - \value Windows Windows execution environments -*/ - -/*! - \enum TQSettings::Format - - \value Native Store the settings in a platform dependent location - \value Ini Store the settings in a text file -*/ - -/*! - \enum TQSettings::Scope - - \value Global Save settings as global as possible - \value User Save settings in user space -*/ - -#if defined(Q_OS_UNIX) -typedef int HANDLE; -#define Q_LOCKREAD F_RDLCK -#define Q_LOCKWRITE F_WRLCK -/* - Locks the file specified by name. The lockfile is created as a - hidden file in the same directory as the target file, with .lock - appended to the name. For example, "/etc/settings/onerc" uses a - lockfile named "/etc/settings/.onerc.lock". The type argument - controls the type of the lock, it can be either F_RDLCK for a read - lock, or F_WRLCK for a write lock. - - A file descriptor for the lock file is returned, and should be - closed with closelock() when the lock is no longer needed. - */ -static HANDLE openlock( const TQString &name, int type ) -{ - TQFileInfo info( name ); - // lockfile should be hidden, and never removed - TQString lockfile = info.dirPath() + "/." + info.fileName() + ".lock"; - - // open the lockfile - HANDLE fd = qt_open( TQFile::encodeName( lockfile ), - O_RDWR | O_CREAT, S_IRUSR | S_IWUSR ); - - if ( fd < 0 ) { - // failed to open the lock file, most likely because of permissions - return fd; - } - - struct flock fl; - fl.l_type = type; - fl.l_whence = SEEK_SET; - fl.l_start = 0; - fl.l_len = 0; - if ( fcntl( fd, F_SETLKW, &fl ) == -1 ) { - // the lock failed, so we should fail silently, so that people - // using filesystems that do not support locking don't see - // numerous warnings about a failed lock - close( fd ); - fd = -1; - } - - return fd; -} - -/* - Closes the lock file specified by fd. fd is the file descriptor - returned by the openlock() function. -*/ -static void closelock( HANDLE fd ) -{ - if ( fd < 0 ) { - // the lock file is not open - return; - } - - struct flock fl; - fl.l_type = F_UNLCK; - fl.l_whence = SEEK_SET; - fl.l_start = 0; - fl.l_len = 0; - // ignore the return value, so that the unlock fails silently - (void) fcntl( fd, F_SETLKW, &fl ); - - close( fd ); -} -#endif - - -TQSettingsGroup::TQSettingsGroup() - : modified(FALSE) -{ -} - - - - -void TQSettingsHeading::read(const TQString &filename) -{ - if (! TQFileInfo(filename).exists()) - return; - -#ifndef TQ_WS_WIN - HANDLE lockfd = openlock( filename, Q_LOCKREAD ); -#endif - - TQFile file(filename); - if (! file.open(IO_ReadOnly)) { -#if defined(QT_CHECK_STATE) - tqWarning("TQSettings: failed to open file '%s'", filename.latin1()); -#endif - return; - } - - git = end(); - - TQTextStream stream(&file); - stream.setEncoding(TQTextStream::UnicodeUTF8); - while (! stream.atEnd()) - parseLine(stream); - - git = end(); - - file.close(); - -#ifndef TQ_WS_WIN - closelock( lockfd ); -#endif -} - - -void TQSettingsHeading::parseLine(TQTextStream &stream) -{ - TQString line = stream.readLine(); - if (line.isEmpty()) - // empty line... we'll allow it - return; - - if (line[0] == TQChar('#')) - // commented line - return; - - if (line[0] == TQChar('[')) { - TQString gname = line; - - gname = gname.remove((uint)0, 1); - if (gname[(int)gname.length() - 1] == TQChar(']')) - gname = gname.remove(gname.length() - 1, 1); - - git = find(gname); - if (git == end()) - git = replace(gname, TQSettingsGroup()); - } else { - if (git == end()) { -#if defined(QT_CHECK_STATE) - tqWarning("TQSettings: line '%s' out of group", line.latin1()); -#endif - return; - } - - int i = line.find('='); - if (i == -1) { -#if defined(QT_CHECK_STATE) - tqWarning("TQSettings: malformed line '%s' in group '%s'", - line.latin1(), git.key().latin1()); -#endif - return; - } else { - TQString key, value; - key = line.left(i); - value = ""; - bool esc=TRUE; - i++; - while (esc) { - esc = FALSE; - for ( ; i < (int)line.length(); i++ ) { - if ( esc ) { - if ( line[i] == 'n' ) - value.append('\n'); // escaped newline - else if ( line[i] == '0' ) - value = TQString::null; // escaped empty string - else - value.append(line[i]); - esc = FALSE; - } else if ( line[i] == '\\' ) - esc = TRUE; - else - value.append(line[i]); - } - if ( esc ) { - // Backwards-compatiblity... - // still escaped at EOL - manually escaped "newline" - if (stream.atEnd()) { -#if defined(QT_CHECK_STATE) - tqWarning("TQSettings: reached end of file, expected continued line"); -#endif - break; - } - value.append('\n'); - line = stream.readLine(); - i = 0; - } - } - - (*git).insert(key, value); - } - } -} - -#ifdef TQ_WS_WIN // for homedirpath reading from registry -#include "qt_windows.h" -#include "ntqlibrary.h" - -#ifndef CSIDL_APPDATA -#define CSIDL_APPDATA 0x001a // \Application Data -#endif -#ifndef CSIDL_COMMON_APPDATA -#define CSIDL_COMMON_APPDATA 0x0023 // All Users\Application Data -#endif - -#endif - -TQSettingsPrivate::TQSettingsPrivate( TQSettings::Format format ) - : groupDirty( TRUE ), modified(FALSE), globalScope(TRUE) -{ -#if defined(TQ_WS_WIN) || defined(Q_OS_MAC) - if ( format != TQSettings::Ini ) - return; -#else - Q_UNUSED( format ); -#endif - - TQString home; - home = getenv("QT_HOME_DIR"); - if ( !home.isEmpty() ) { - home += "/"; - TQFileInfo i( home + "qtrc" ); - if ( !i.isReadable() ) { - home = TQDir::homeDirPath() + "/.qt/"; - } - } else { - home = TQDir::homeDirPath() + "/.qt/"; - } - TQString appSettings(home); - - TQString defPath; -#ifdef TQ_WS_WIN -#ifdef Q_OS_TEMP - TCHAR path[MAX_PATH]; - SHGetSpecialFolderPath( 0, path, CSIDL_APPDATA, FALSE ); - appSettings = TQString::fromUcs2( path ); - SHGetSpecialFolderPath( 0, path, CSIDL_COMMON_APPDATA, FALSE ); - defPath = TQString::fromUcs2( path ); -#else - TQLibrary library( "shell32" ); - library.setAutoUnload( FALSE ); - QT_WA( { - typedef BOOL (WINAPI*GetSpecialFolderPath)(HWND, LPTSTR, int, BOOL); - GetSpecialFolderPath SHGetSpecialFolderPath = (GetSpecialFolderPath)library.resolve( "SHGetSpecialFolderPathW" ); - if ( SHGetSpecialFolderPath ) { - TCHAR path[MAX_PATH]; - SHGetSpecialFolderPath( 0, path, CSIDL_APPDATA, FALSE ); - appSettings = TQString::fromUcs2( (ushort*)path ); - SHGetSpecialFolderPath( 0, path, CSIDL_COMMON_APPDATA, FALSE ); - defPath = TQString::fromUcs2( (ushort*)path ); - } - } , { - typedef BOOL (WINAPI*GetSpecialFolderPath)(HWND, char*, int, BOOL); - GetSpecialFolderPath SHGetSpecialFolderPath = (GetSpecialFolderPath)library.resolve( "SHGetSpecialFolderPathA" ); - if ( SHGetSpecialFolderPath ) { - char path[MAX_PATH]; - SHGetSpecialFolderPath( 0, path, CSIDL_APPDATA, FALSE ); - appSettings = TQString::fromLocal8Bit( path ); - SHGetSpecialFolderPath( 0, path, CSIDL_COMMON_APPDATA, FALSE ); - defPath = TQString::fromLocal8Bit( path ); - } - } ); -#endif // Q_OS_TEMP -#else - defPath = tqInstallPathSysconf(); -#endif - TQDir dir(appSettings); - if (! dir.exists()) { - if (! dir.mkdir(dir.path())) -#if defined(QT_CHECK_STATE) - tqWarning("TQSettings: error creating %s", dir.path().latin1()); -#else - ; -#endif - } - - if ( !!defPath ) - searchPaths.append(defPath); - - TQString system; - system = getenv("QT_SYSTEM_DIR"); - if ( !system.isEmpty() && system[0] == '/') { - TQFileInfo i( system + "/qtrc" ); - if ( i.isReadable() ) { - searchPaths.append(system); - } - } - - searchPaths.append(dir.path()); -} - -TQSettingsPrivate::~TQSettingsPrivate() -{ -} - -TQSettingsGroup TQSettingsPrivate::readGroup() -{ - TQSettingsHeading hd; - TQSettingsGroup grp; - - TQMap::Iterator headingsit = headings.find(heading); - if (headingsit != headings.end()) - hd = *headingsit; - - TQSettingsHeading::Iterator grpit = hd.find(group); - if (grpit == hd.end()) { - TQStringList::Iterator it = searchPaths.begin(); - if ( !globalScope ) - ++it; - while (it != searchPaths.end()) { - TQString filebase = heading.lower().replace(TQRegExp(TQString::fromLatin1("\\s+")), "_"); - TQString fn((*it++) + "/" + filebase + "rc"); - if (! hd.contains(fn + "cached")) { - hd.read(fn); - hd.insert(fn + "cached", TQSettingsGroup()); - } - } - - headings.replace(heading, hd); - - grpit = hd.find(group); - if (grpit != hd.end()) - grp = *grpit; - } else if (hd.count() != 0) - grp = *grpit; - - return grp; -} - - -void TQSettingsPrivate::removeGroup(const TQString &key) -{ - TQSettingsHeading hd; - TQSettingsGroup grp; - bool found = FALSE; - - TQMap::Iterator headingsit = headings.find(heading); - if (headingsit != headings.end()) - hd = *headingsit; - - TQSettingsHeading::Iterator grpit = hd.find(group); - if (grpit == hd.end()) { - TQStringList::Iterator it = searchPaths.begin(); - if ( !globalScope ) - ++it; - while (it != searchPaths.end()) { - TQString filebase = heading.lower().replace(TQRegExp(TQString::fromLatin1("\\s+")), "_"); - TQString fn((*it++) + "/" + filebase + "rc"); - if (! hd.contains(fn + "cached")) { - hd.read(fn); - hd.insert(fn + "cached", TQSettingsGroup()); - } - } - - headings.replace(heading, hd); - - grpit = hd.find(group); - if (grpit != hd.end()) { - found = TRUE; - grp = *grpit; - } - } else if (hd.count() != 0) { - found = TRUE; - grp = *grpit; - } - - if (found) { - grp.remove(key); - - if (grp.count() > 0) - hd.replace(group, grp); - else - hd.remove(group); - - if (hd.count() > 0) - headings.replace(heading, hd); - else - headings.remove(heading); - - modified = TRUE; - } -} - - -void TQSettingsPrivate::writeGroup(const TQString &key, const TQString &value) -{ - TQSettingsHeading hd; - TQSettingsGroup grp; - - TQMap::Iterator headingsit = headings.find(heading); - if (headingsit != headings.end()) - hd = *headingsit; - - TQSettingsHeading::Iterator grpit = hd.find(group); - if (grpit == hd.end()) { - TQStringList::Iterator it = searchPaths.begin(); - if ( !globalScope ) - ++it; - while (it != searchPaths.end()) { - TQString filebase = heading.lower().replace(TQRegExp(TQString::fromLatin1("\\s+")), "_"); - TQString fn((*it++) + "/" + filebase + "rc"); - if (! hd.contains(fn + "cached")) { - hd.read(fn); - hd.insert(fn + "cached", TQSettingsGroup()); - } - } - - headings.replace(heading, hd); - - grpit = hd.find(group); - if (grpit != hd.end()) - grp = *grpit; - } else if (hd.count() != 0) - grp = *grpit; - - grp.modified = TRUE; - grp.replace(key, value); - hd.replace(group, grp); - headings.replace(heading, hd); - - modified = TRUE; -} - - -TQDateTime TQSettingsPrivate::modificationTime() -{ - TQSettingsHeading hd = headings[heading]; - TQSettingsGroup grp = hd[group]; - - TQDateTime datetime; - - TQStringList::Iterator it = searchPaths.begin(); - if ( !globalScope ) - ++it; - while (it != searchPaths.end()) { - TQFileInfo fi((*it++) + "/" + heading + "rc"); - if (fi.exists() && fi.lastModified() > datetime) - datetime = fi.lastModified(); - } - - return datetime; -} - -bool qt_verify_key( const TQString &key ) -{ - if ( key.isEmpty() || key[0] != '/' || key.contains( TQRegExp(TQString::fromLatin1("[=\\r\\n]")) ) ) - return FALSE; - return TRUE; -} - -static TQString groupKey( const TQString &group, const TQString &key ) -{ - TQString grp_key; - if ( group.isEmpty() || ( group.length() == 1 && group[0] == '/' ) ) { - // group is empty, or it contains a single '/', so we just return the key - if ( key.startsWith( "/" ) ) - grp_key = key; - else - grp_key = "/" + key; - } else if ( group.endsWith( "/" ) || key.startsWith( "/" ) ) { - grp_key = group + key; - } else { - grp_key = group + "/" + key; - } - return grp_key; -} - -/*! - Inserts \a path into the settings search path. The semantics of \a - path depends on the system \a s. It is usually easier and better to - use setPath() instead of this function. - - When \a s is \e Windows and the execution environment is \e not - Windows the function does nothing. Similarly when \a s is \e Unix and - the execution environment is \e not Unix the function does nothing. - - When \a s is \e Windows, and the execution environment is Windows, the - search path list will be used as the first subfolder of the "Software" - folder in the registry. - - When reading settings the folders are searched forwards from the - first folder (listed below) to the last, returning the first - settings found, and ignoring any folders for which the user doesn't - have read permission. - \list 1 - \i HKEY_CURRENT_USER/Software/MyCompany/MyApplication - \i HKEY_LOCAL_MACHINE/Software/MyCompany/MyApplication - \i HKEY_CURRENT_USER/Software/MyApplication - \i HKEY_LOCAL_MACHINE/Software/MyApplication - \endlist - - \code - TQSettings settings; - settings.insertSearchPath( TQSettings::Windows, "/MyCompany" ); - settings.writeEntry( "/MyApplication/Tip of the day", TRUE ); - \endcode - The code above will write the subkey "Tip of the day" into the \e - first of the registry folders listed below that is found and for - which the user has write permission. - \list 1 - \i HKEY_LOCAL_MACHINE/Software/MyCompany/MyApplication - \i HKEY_CURRENT_USER/Software/MyCompany/MyApplication - \i HKEY_LOCAL_MACHINE/Software/MyApplication - \i HKEY_CURRENT_USER/Software/MyApplication - \endlist - If a setting is found in the HKEY_CURRENT_USER space, this setting - is overwritten independently of write permissions in the - HKEY_LOCAL_MACHINE space. - - When \a s is \e Unix, and the execution environment is Unix, the - search path list will be used when trying to determine a suitable - filename for reading and writing settings files. By default, there are - two entries in the search path: - - \list 1 - \i \c SYSCONF - where \c SYSCONF is a directory specified when - configuring TQt; by default it is INSTALL/etc/settings. - \i \c $HOME/.qt/ - where \c $HOME is the user's home directory. - \endlist - - All insertions into the search path will go before $HOME/.qt/. - For example: - \code - TQSettings settings; - settings.insertSearchPath( TQSettings::Unix, "/opt/MyCompany/share/etc" ); - settings.insertSearchPath( TQSettings::Unix, "/opt/MyCompany/share/MyApplication/etc" ); - // ... - \endcode - Will result in a search path of: - \list 1 - \i SYSCONF - \i /opt/MyCompany/share/etc - \i /opt/MyCompany/share/MyApplication/etc - \i $HOME/.qt - \endlist - When reading settings the files are searched in the order shown - above, with later settings overriding earlier settings. Files for - which the user doesn't have read permission are ignored. When saving - settings TQSettings works in the order shown above, writing - to the first settings file for which the user has write permission. - - Note that paths in the file system are not created by this - function, so they must already exist to be useful. - - Settings under Unix are stored in files whose names are based on the - first subkey of the key (not including the search path). The algorithm - for creating names is essentially: lowercase the first subkey, replace - spaces with underscores and add 'rc', e.g. - /MyCompany/MyApplication/background color will be stored in - myapplicationrc (assuming that /MyCompany is part of - the search path). - - \sa removeSearchPath() - -*/ -void TQSettings::insertSearchPath( System s, const TQString &path) -{ -#if defined(TQ_WS_WIN) || defined(Q_OS_MAC) - if ( d->sysd ) { - d->sysInsertSearchPath( s, path ); - return; - } -#endif - -#if !defined(TQ_WS_WIN) - if ( s == Windows ) - return; -#endif -#if !defined(Q_OS_MAC) - if ( s == Mac ) - return; -#endif - - if ( !qt_verify_key( path ) ) { -#if defined(QT_CHECK_STATE) - tqWarning( "TQSettings::insertSearchPath: Invalid key: '%s'", path.isNull() ? "(null)" : path.latin1() ); -#endif - return; - } - -#if defined(TQ_WS_WIN) || defined(Q_OS_MAC) - if ( d->sysd && s != Unix ) { -#else - if ( s != Unix ) { -#endif -#if defined(Q_OS_MAC) - if(s != Mac) //mac is respected on the mac as well -#endif - return; - } - - TQString realPath = path; -#if defined(TQ_WS_WIN) - TQString defPath = d->globalScope ? d->searchPaths.first() : d->searchPaths.last(); - realPath = defPath + path; -#endif - - TQStringList::Iterator it = d->searchPaths.find(d->searchPaths.last()); - if (it != d->searchPaths.end()) { - d->searchPaths.insert(it, realPath); - } -} - - -/*! - Removes all occurrences of \a path (using exact matching) from the - settings search path for system \a s. Note that the default search - paths cannot be removed. - - \sa insertSearchPath() -*/ -void TQSettings::removeSearchPath( System s, const TQString &path) -{ - if ( !qt_verify_key( path ) ) { -#if defined(QT_CHECK_STATE) - tqWarning( "TQSettings::insertSearchPath: Invalid key: '%s'", path.isNull() ? "(null)" : path.latin1() ); -#endif - return; - } - -#ifdef TQ_WS_WIN - if ( d->sysd ) { - d->sysRemoveSearchPath( s, path ); - return; - } -#endif -#if defined(TQ_WS_WIN) || defined(Q_OS_MAC) - if ( d->sysd && s != Unix ) { -#else - if ( s != Unix ) { -#endif -#if defined(Q_OS_MAC) - if(s != Mac) //mac is respected on the mac as well -#endif - return; - } - - if (path == d->searchPaths.first() || path == d->searchPaths.last()) - return; - - d->searchPaths.remove(path); -} - - -/*! - Creates a settings object. - - Be aware that you must call setPath() or insertSearchPath() before - you can use the TQSettings object. -*/ -TQSettings::TQSettings() -{ - d = new TQSettingsPrivate( Native ); - TQ_CHECK_PTR(d); - -#if defined(TQ_WS_WIN) || defined(Q_OS_MAC) - d->sysd = 0; - d->sysInit(); -#endif -} - -/*! - Creates a settings object. If \a format is 'Ini' the settings will - be stored in a text file, using the Unix strategy (see above). If \a format - is 'Native', the settings will be stored in a platform specific way - (ie. the Windows registry). - - Be aware that you must call setPath() or insertSearchPath() before - you can use the TQSettings object. -*/ -TQSettings::TQSettings( Format format ) -{ - d = new TQSettingsPrivate( format ); - TQ_CHECK_PTR(d); - -#if defined(TQ_WS_WIN) || defined(Q_OS_MAC) - d->sysd = 0; - if ( format == Native ) - d->sysInit(); -#else - Q_UNUSED(format); -#endif -} - -/*! - Destroys the settings object. All modifications made to the settings - will automatically be saved. - -*/ -TQSettings::~TQSettings() -{ - sync(); - -#if defined(TQ_WS_WIN) || defined(Q_OS_MAC) - if ( d->sysd ) - d->sysClear(); -#endif - - delete d; -} - - -/*! \internal - Writes all modifications to the settings to disk. If any errors are - encountered, this function returns FALSE, otherwise it will return TRUE. -*/ -bool TQSettings::sync() -{ -#if defined(TQ_WS_WIN) || defined(Q_OS_MAC) - if ( d->sysd ) - return d->sysSync(); -#endif - if (! d->modified) - // fake success - return TRUE; - - bool success = TRUE; - TQMap::Iterator it = d->headings.begin(); - - while (it != d->headings.end()) { - // determine filename - TQSettingsHeading hd(*it); - TQSettingsHeading::Iterator hdit = hd.begin(); - TQString filename; - - TQStringList::Iterator pit = d->searchPaths.begin(); - if ( !d->globalScope ) - ++pit; - while (pit != d->searchPaths.end()) { - TQString filebase = it.key().lower().replace(TQRegExp(TQString::fromLatin1("\\s+")), "_"); - TQFileInfo di(*pit); - if ( !di.exists() ) { - TQDir dir; - dir.mkdir( *pit ); - } - - TQFileInfo fi((*pit++) + "/" + filebase + "rc"); - - if ((fi.exists() && fi.isFile() && fi.isWritable()) || - (! fi.exists() && di.isDir() -#ifndef TQ_WS_WIN - && di.isWritable() -#else - && ((qWinVersion()&TQt::WV_NT_based) > TQt::WV_2000 || di.isWritable()) -#endif - )) { - filename = fi.filePath(); - break; - } - } - - ++it; - - if ( filename.isEmpty() ) { - -#ifdef QT_CHECK_STATE - tqWarning("TQSettings::sync: filename is null/empty"); -#endif // QT_CHECK_STATE - - success = FALSE; - continue; - } - -#ifndef TQ_WS_WIN - HANDLE lockfd = openlock( filename, Q_LOCKWRITE ); -#endif - - TQFile file( filename + ".tmp" ); - if (! file.open(IO_WriteOnly)) { - -#ifdef QT_CHECK_STATE - tqWarning("TQSettings::sync: failed to open '%s' for writing", - file.name().latin1()); -#endif // QT_CHECK_STATE - - success = FALSE; - continue; - } - - // spew to file - TQTextStream stream(&file); - stream.setEncoding(TQTextStream::UnicodeUTF8); - - while (hdit != hd.end()) { - if ((*hdit).count() > 0) { - stream << "[" << hdit.key() << "]" << endl; - - TQSettingsGroup grp(*hdit); - TQSettingsGroup::Iterator grpit = grp.begin(); - - while (grpit != grp.end()) { - TQString v = grpit.data(); - if ( v.isNull() ) { - v = TQString::fromLatin1("\\0"); // escape null string - } else { - v.replace('\\', TQString::fromLatin1("\\\\")); // escape backslash - v.replace('\n', TQString::fromLatin1("\\n")); // escape newlines - } - - stream << grpit.key() << "=" << v << endl; - ++grpit; - } - - stream << endl; - } - - ++hdit; - } - - if (file.status() != IO_Ok) { - -#ifdef QT_CHECK_STATE - tqWarning("TQSettings::sync: error at end of write"); -#endif // QT_CHECK_STATE - - success = FALSE; - } - - file.close(); - - if ( success ) { - TQDir dir( TQFileInfo( file ).dir( TRUE ) ); - if ( ( dir.exists( filename ) && !dir.remove( filename ) ) || - !dir.rename( file.name(), filename, TRUE ) ) { - -#ifdef QT_CHECK_STATE - tqWarning( "TQSettings::sync: error writing file '%s'", - TQFile::encodeName( filename ).data() ); -#endif // QT_CHECK_STATE - - success = FALSE; - } - } - - // remove temporary file - file.remove(); - -#ifndef TQ_WS_WIN - closelock( lockfd ); -#endif - } - - d->modified = FALSE; - - return success; -} - - -/*! - \fn bool TQSettings::readBoolEntry(const TQString &key, bool def, bool *ok ) const - - Reads the entry specified by \a key, and returns a bool, or the - default value, \a def, if the entry couldn't be read. - If \a ok is non-null, *ok is set to TRUE if the key was read, FALSE - otherwise. - - \sa readEntry(), readNumEntry(), readDoubleEntry(), writeEntry(), removeEntry() -*/ - -/*! - \internal -*/ -bool TQSettings::readBoolEntry(const TQString &key, bool def, bool *ok ) -{ - TQString grp_key( groupKey( group(), key ) ); - if ( !qt_verify_key( grp_key ) ) { -#if defined(QT_CHECK_STATE) - tqWarning( "TQSettings::readBoolEntry: Invalid key: '%s'", grp_key.isNull() ? "(null)" : grp_key.latin1() ); -#endif - if ( ok ) - *ok = FALSE; - - return def; - } - -#if defined(TQ_WS_WIN) || defined(Q_OS_MAC) - if ( d->sysd ) - return d->sysReadBoolEntry( grp_key, def, ok ); -#endif - - TQString value = readEntry( key, ( def ? "true" : "false" ), ok ); - - if (value.lower() == "true") - return TRUE; - else if (value.lower() == "false") - return FALSE; - else if (value == "1") - return TRUE; - else if (value == "0") - return FALSE; - - if (! value.isEmpty()) - tqWarning("TQSettings::readBoolEntry: '%s' is not 'true' or 'false'", - value.latin1()); - if ( ok ) - *ok = FALSE; - return def; -} - - -/*! - \fn double TQSettings::readDoubleEntry(const TQString &key, double def, bool *ok ) const - - Reads the entry specified by \a key, and returns a double, or the - default value, \a def, if the entry couldn't be read. - If \a ok is non-null, *ok is set to TRUE if the key was read, FALSE - otherwise. - - \sa readEntry(), readNumEntry(), readBoolEntry(), writeEntry(), removeEntry() -*/ - -/*! - \internal -*/ -double TQSettings::readDoubleEntry(const TQString &key, double def, bool *ok ) -{ - TQString grp_key( groupKey( group(), key ) ); - if ( !qt_verify_key( grp_key ) ) { -#if defined(QT_CHECK_STATE) - tqWarning( "TQSettings::readDoubleEntry: Invalid key: '%s'", grp_key.isNull() ? "(null)" : grp_key.latin1() ); -#endif - if ( ok ) - *ok = FALSE; - - return def; - } - -#if defined(TQ_WS_WIN) || defined(Q_OS_MAC) - if ( d->sysd ) - return d->sysReadDoubleEntry( grp_key, def, ok ); -#endif - - TQString value = readEntry( key, TQString::number(def), ok ); - bool conv_ok; - double retval = value.toDouble( &conv_ok ); - if ( conv_ok ) - return retval; - if ( ! value.isEmpty() ) - tqWarning( "TQSettings::readDoubleEntry: '%s' is not a number", - value.latin1() ); - if ( ok ) - *ok = FALSE; - return def; -} - - -/*! - \fn int TQSettings::readNumEntry(const TQString &key, int def, bool *ok ) const - - Reads the entry specified by \a key, and returns an integer, or the - default value, \a def, if the entry couldn't be read. - If \a ok is non-null, *ok is set to TRUE if the key was read, FALSE - otherwise. - - \sa readEntry(), readDoubleEntry(), readBoolEntry(), writeEntry(), removeEntry() -*/ - -/*! - \internal -*/ -int TQSettings::readNumEntry(const TQString &key, int def, bool *ok ) -{ - TQString grp_key( groupKey( group(), key ) ); - if ( !qt_verify_key( grp_key ) ) { -#if defined(QT_CHECK_STATE) - tqWarning( "TQSettings::readNumEntry: Invalid key: '%s'", grp_key.isNull() ? "(null)" : grp_key.latin1() ); -#endif - if ( ok ) - *ok = FALSE; - return def; - } - -#if defined(TQ_WS_WIN) || defined(Q_OS_MAC) - if ( d->sysd ) - return d->sysReadNumEntry( grp_key, def, ok ); -#endif - - TQString value = readEntry( key, TQString::number( def ), ok ); - bool conv_ok; - int retval = value.toInt( &conv_ok ); - if ( conv_ok ) - return retval; - if ( ! value.isEmpty() ) - tqWarning( "TQSettings::readNumEntry: '%s' is not a number", - value.latin1() ); - if ( ok ) - *ok = FALSE; - return def; -} - - -/*! - \fn TQString TQSettings::readEntry(const TQString &key, const TQString &def, bool *ok ) const - - Reads the entry specified by \a key, and returns a TQString, or the - default value, \a def, if the entry couldn't be read. - If \a ok is non-null, *ok is set to TRUE if the key was read, FALSE - otherwise. - - \sa readListEntry(), readNumEntry(), readDoubleEntry(), readBoolEntry(), writeEntry(), removeEntry() -*/ - -/*! - \internal -*/ -TQString TQSettings::readEntry(const TQString &key, const TQString &def, bool *ok ) -{ - TQString grp_key( groupKey( group(), key ) ); - if ( !qt_verify_key( grp_key ) ) { -#if defined(QT_CHECK_STATE) - tqWarning( "TQSettings::readEntry: Invalid key: '%s'", grp_key.isNull() ? "(null)" : grp_key.latin1() ); -#endif - if ( ok ) - *ok = FALSE; - - return def; - } - -#if defined(TQ_WS_WIN) || defined(Q_OS_MAC) - if ( d->sysd ) - return d->sysReadEntry( grp_key, def, ok ); -#endif - - if ( ok ) // no, everything is not ok - *ok = FALSE; - - TQString realkey; - - if (grp_key[0] == '/') { - // parse our key - TQStringList list(TQStringList::split('/', grp_key)); - - if (list.count() < 2) { -#ifdef QT_CHECK_STATE - tqWarning("TQSettings::readEntry: invalid key '%s'", grp_key.latin1()); -#endif // QT_CHECK_STATE - if ( ok ) - *ok = FALSE; - return def; - } - - if (list.count() == 2) { - d->heading = list[0]; - d->group = "General"; - realkey = list[1]; - } else { - d->heading = list[0]; - d->group = list[1]; - - // remove the group from the list - list.remove(list.at(1)); - // remove the heading from the list - list.remove(list.at(0)); - - realkey = list.join("/"); - } - } else { - realkey = grp_key; - } - - TQSettingsGroup grp = d->readGroup(); - TQSettingsGroup::const_iterator it = grp.find( realkey ), end = grp.end(); - TQString retval = def; - if ( it != end ) { - // found the value we needed - retval = *it; - if ( ok ) *ok = TRUE; - } - return retval; -} - - -#if !defined(Q_NO_BOOL_TYPE) -/*! - Writes the boolean entry \a value into key \a key. The \a key is - created if it doesn't exist. Any previous value is overwritten by \a - value. - - If an error occurs the settings are left unchanged and FALSE is - returned; otherwise TRUE is returned. - - \warning On certain platforms, keys are required to contain at least - two components (e.g., "/foo/bar"). This limitation does not apply to - TQt 4. - - \sa readListEntry(), readNumEntry(), readDoubleEntry(), readBoolEntry(), removeEntry() -*/ -bool TQSettings::writeEntry(const TQString &key, bool value) -{ - TQString grp_key( groupKey( group(), key ) ); - if ( !qt_verify_key( grp_key ) ) { -#if defined(QT_CHECK_STATE) - tqWarning( "TQSettings::writeEntry: Invalid key: '%s'", grp_key.isNull() ? "(null)" : grp_key.latin1() ); -#endif - return FALSE; - } - -#if defined(TQ_WS_WIN) || defined(Q_OS_MAC) - if ( d->sysd ) - return d->sysWriteEntry( grp_key, value ); -#endif - TQString s(value ? "true" : "false"); - return writeEntry(key, s); -} -#endif - - -/*! - \overload - Writes the double entry \a value into key \a key. The \a key is - created if it doesn't exist. Any previous value is overwritten by \a - value. - - If an error occurs the settings are left unchanged and FALSE is - returned; otherwise TRUE is returned. - - \sa readListEntry(), readNumEntry(), readDoubleEntry(), readBoolEntry(), removeEntry() -*/ -bool TQSettings::writeEntry(const TQString &key, double value) -{ - TQString grp_key( groupKey( group(), key ) ); - if ( !qt_verify_key( grp_key ) ) { -#if defined(QT_CHECK_STATE) - tqWarning( "TQSettings::writeEntry: Invalid key: '%s'", grp_key.isNull() ? "(null)" : grp_key.latin1() ); -#endif - return FALSE; - } - -#if defined(TQ_WS_WIN) || defined(Q_OS_MAC) - if ( d->sysd ) - return d->sysWriteEntry( grp_key, value ); -#endif - TQString s(TQString::number(value)); - return writeEntry(key, s); -} - - -/*! - \overload - Writes the integer entry \a value into key \a key. The \a key is - created if it doesn't exist. Any previous value is overwritten by \a - value. - - If an error occurs the settings are left unchanged and FALSE is - returned; otherwise TRUE is returned. - - \sa readListEntry(), readNumEntry(), readDoubleEntry(), readBoolEntry(), removeEntry() -*/ -bool TQSettings::writeEntry(const TQString &key, int value) -{ - TQString grp_key( groupKey( group(), key ) ); - if ( !qt_verify_key( grp_key ) ) { -#if defined(QT_CHECK_STATE) - tqWarning( "TQSettings::writeEntry: Invalid key: '%s'", grp_key.isNull() ? "(null)" : grp_key.latin1() ); -#endif - return FALSE; - } - -#if defined(TQ_WS_WIN) || defined(Q_OS_MAC) - if ( d->sysd ) - return d->sysWriteEntry( grp_key, value ); -#endif - TQString s(TQString::number(value)); - return writeEntry(key, s); -} - - -/*! - \internal - - Writes the entry specified by \a key with the string-literal \a value, - replacing any previous setting. If \a value is zero-length or null, the - entry is replaced by an empty setting. - - \e NOTE: This function is provided because some compilers use the - writeEntry (const TQString &, bool) overload for this code: - writeEntry ("/foo/bar", "baz") - - If an error occurs, this functions returns FALSE and the object is left - unchanged. - - \sa readEntry(), removeEntry() -*/ -bool TQSettings::writeEntry(const TQString &key, const char *value) -{ - return writeEntry(key, TQString(value)); -} - - -/*! - \overload - Writes the string entry \a value into key \a key. The \a key is - created if it doesn't exist. Any previous value is overwritten by \a - value. If \a value is an empty string or a null string the key's - value will be an empty string. - - If an error occurs the settings are left unchanged and FALSE is - returned; otherwise TRUE is returned. - - \sa readListEntry(), readNumEntry(), readDoubleEntry(), readBoolEntry(), removeEntry() -*/ -bool TQSettings::writeEntry(const TQString &key, const TQString &value) -{ - TQString grp_key( groupKey( group(), key ) ); - if ( !qt_verify_key( grp_key ) ) { -#if defined(QT_CHECK_STATE) - tqWarning( "TQSettings::writeEntry: Invalid key: '%s'", grp_key.isNull() ? "(null)" : grp_key.latin1() ); -#endif - return FALSE; - } - -#if defined(TQ_WS_WIN) || defined(Q_OS_MAC) - if ( d->sysd ) - return d->sysWriteEntry( grp_key, value ); -#endif - // NOTE: we *do* allow value to be a null/empty string - - TQString realkey; - - if (grp_key[0] == '/') { - // parse our key - TQStringList list(TQStringList::split('/', grp_key)); - - if (list.count() < 2) { -#ifdef QT_CHECK_STATE - tqWarning("TQSettings::writeEntry: invalid key '%s'", grp_key.latin1()); -#endif // QT_CHECK_STATE - - return FALSE; - } - - if (list.count() == 2) { - d->heading = list[0]; - d->group = "General"; - realkey = list[1]; - } else { - d->heading = list[0]; - d->group = list[1]; - - // remove the group from the list - list.remove(list.at(1)); - // remove the heading from the list - list.remove(list.at(0)); - - realkey = list.join("/"); - } - } else { - realkey = grp_key; - } - - d->writeGroup(realkey, value); - return TRUE; -} - - -/*! - Removes the entry specified by \a key. - - Returns true if the entry was successfully removed; otherwise - returns false. Note that removing the last entry in any given - folder, will also remove the folder. - - \sa readEntry(), writeEntry() -*/ -bool TQSettings::removeEntry(const TQString &key) -{ - TQString grp_key( groupKey( group(), key ) ); - if ( !qt_verify_key( grp_key ) ) { -#if defined(QT_CHECK_STATE) - tqWarning( "TQSettings::removeEntry: Invalid key: '%s'", grp_key.isNull() ? "(null)" : grp_key.latin1() ); -#endif - return FALSE; - } - -#if defined(TQ_WS_WIN) || defined(Q_OS_MAC) - if ( d->sysd ) - return d->sysRemoveEntry( grp_key ); -#endif - - TQString realkey; - if (grp_key[0] == '/') { - // parse our key - TQStringList list(TQStringList::split('/', grp_key)); - - if (list.count() < 2) { -#ifdef QT_CHECK_STATE - tqWarning("TQSettings::removeEntry: invalid key '%s'", grp_key.latin1()); -#endif // QT_CHECK_STATE - - return FALSE; - } - - if (list.count() == 2) { - d->heading = list[0]; - d->group = "General"; - realkey = list[1]; - } else { - d->heading = list[0]; - d->group = list[1]; - - // remove the group from the list - list.remove(list.at(1)); - // remove the heading from the list - list.remove(list.at(0)); - - realkey = list.join("/"); - } - } else { - realkey = grp_key; - } - - d->removeGroup(realkey); - return TRUE; -} - - -/*! - Returns a list of the keys which contain entries under \a key. Does \e - not return any keys that contain subkeys. - - Example settings: - \code - /MyCompany/MyApplication/background color - /MyCompany/MyApplication/foreground color - /MyCompany/MyApplication/geometry/x - /MyCompany/MyApplication/geometry/y - /MyCompany/MyApplication/geometry/width - /MyCompany/MyApplication/geometry/height - \endcode - \code - TQStringList keys = settings.entryList( "/MyCompany/MyApplication" ); - \endcode - - In the above example, \c keys will contain 'background color' and - 'foreground color'. It will not contain 'geometry' because this key - contains subkeys not entries. - - To access the geometry values, you could either use subkeyList() - to read the keys then read each entry, or simply read each entry - directly by specifying its full key, e.g. - "/MyCompany/MyApplication/geometry/y". - - \sa subkeyList() -*/ -TQStringList TQSettings::entryList(const TQString &key) const -{ - TQString grp_key( groupKey( group(), key ) ); - if ( !qt_verify_key( grp_key ) ) { -#if defined(QT_CHECK_STATE) - tqWarning( "TQSettings::entryList: Invalid key: %s", grp_key.isNull() ? "(null)" : grp_key.latin1() ); -#endif - return TQStringList(); - } - -#if defined(TQ_WS_WIN) || defined(Q_OS_MAC) - if ( d->sysd ) - return d->sysEntryList( grp_key ); -#endif - - TQString realkey; - if (grp_key[0] == '/') { - // parse our key - TQStringList list(TQStringList::split('/', grp_key)); - - if (list.count() < 1) { -#ifdef QT_CHECK_STATE - tqWarning("TQSettings::listEntries: invalid key '%s'", grp_key.latin1()); -#endif // QT_CHECK_STATE - - return TQStringList(); - } - - if (list.count() == 1) { - d->heading = list[0]; - d->group = "General"; - } else { - d->heading = list[0]; - d->group = list[1]; - - // remove the group from the list - list.remove(list.at(1)); - // remove the heading from the list - list.remove(list.at(0)); - - realkey = list.join("/"); - } - } else - realkey = grp_key; - - TQSettingsGroup grp = d->readGroup(); - TQSettingsGroup::Iterator it = grp.begin(); - TQStringList ret; - TQString itkey; - while (it != grp.end()) { - itkey = it.key(); - ++it; - - if ( realkey.length() > 0 ) { - if ( itkey.left( realkey.length() ) != realkey ) - continue; - else - itkey.remove( 0, realkey.length() + 1 ); - } - - if ( itkey.find( '/' ) != -1 ) - continue; - - ret << itkey; - } - - return ret; -} - - -/*! - Returns a list of the keys which contain subkeys under \a key. Does \e - not return any keys that contain entries. - - Example settings: - \code - /MyCompany/MyApplication/background color - /MyCompany/MyApplication/foreground color - /MyCompany/MyApplication/geometry/x - /MyCompany/MyApplication/geometry/y - /MyCompany/MyApplication/geometry/width - /MyCompany/MyApplication/geometry/height - /MyCompany/MyApplication/recent files/1 - /MyCompany/MyApplication/recent files/2 - /MyCompany/MyApplication/recent files/3 - \endcode - \code - TQStringList keys = settings.subkeyList( "/MyCompany/MyApplication" ); - \endcode - - In the above example, \c keys will contain 'geometry' and - 'recent files'. It will not contain 'background color' or - 'foreground color' because those keys contain entries not - subkeys. To get a list of keys that contain entries rather than - subkeys use entryList() instead. - - \warning In the above example, if TQSettings is writing to an Ini file, - then a call to - \code subkeyList("/MyCompany") \endcode - will return an empty list. This happens because a key like - \code /MyCompany/MyApplication/background color \endcode - is written to the file \e{"mycompanyrc"}, under the section \e{[MyApplication]}. - This call is therefore a request to list the sections in an ini file, which - is not supported in this version of TQSettings. This is a known issue which - will be fixed in TQt-4. - - \sa entryList() -*/ -TQStringList TQSettings::subkeyList(const TQString &key) const -{ - TQString grp_key( groupKey( group(), key ) ); - if ( !qt_verify_key( grp_key ) ) { -#if defined(QT_CHECK_STATE) - tqWarning( "TQSettings::subkeyList: Invalid key: %s", grp_key.isNull() ? "(null)" : grp_key.latin1() ); -#endif - return TQStringList(); - } - -#if defined(TQ_WS_WIN) || defined(Q_OS_MAC) - if ( d->sysd ) - return d->sysSubkeyList( grp_key ); -#endif - - TQString realkey; - int subkeycount = 2; - if (grp_key[0] == '/') { - // parse our key - TQStringList list(TQStringList::split('/', grp_key)); - - if (list.count() < 1) { -#ifdef QT_CHECK_STATE - tqWarning("TQSettings::subkeyList: invalid key '%s'", grp_key.latin1()); -#endif // QT_CHECK_STATE - - return TQStringList(); - } - - subkeycount = (int)list.count(); - - if (list.count() == 1) { - d->heading = list[0]; - d->group = "General"; - } else { - d->heading = list[0]; - d->group = list[1]; - - // remove the group from the list - list.remove(list.at(1)); - // remove the heading from the list - list.remove(list.at(0)); - - realkey = list.join("/"); - } - - } else - realkey = grp_key; - - TQStringList ret; - if ( subkeycount == 1 ) { - TQMap::Iterator it = d->headings.begin(); - while ( it != d->headings.end() ) { - if ( it.key() != "General" && ! ret.contains( it.key() ) ) - ret << it.key(); - ++it; - } - - return ret; - } - - TQSettingsGroup grp = d->readGroup(); - TQSettingsGroup::Iterator it = grp.begin(); - TQString itkey; - while (it != grp.end()) { - itkey = it.key(); - ++it; - - if ( realkey.length() > 0 ) { - if ( itkey.left( realkey.length() ) != realkey - || itkey.length()+1 < realkey.length() - || itkey[(int)realkey.length()] != '/') - continue; - else - itkey.remove( 0, realkey.length() + 1 ); - } - - int slash = itkey.find( '/' ); - if ( slash == -1 ) - continue; - itkey.truncate( slash ); - - if ( ! ret.contains( itkey ) ) - ret << itkey; - } - - return ret; -} - - -/*! - \internal - - This function returns the time of last modification for \a key. -*/ -TQDateTime TQSettings::lastModificationTime( const TQString &key ) -{ - TQString grp_key( groupKey( group(), key ) ); - if ( !qt_verify_key( grp_key ) ) { -#if defined(QT_CHECK_STATE) - tqWarning( "TQSettings::lastModificationTime: Invalid key '%s'", grp_key.isNull() ? "(null)" : grp_key.latin1() ); -#endif - return TQDateTime(); - } - -#if defined(TQ_WS_WIN) || defined(Q_OS_MAC) - if ( d->sysd ) - return TQDateTime(); -#endif - - if (grp_key[0] == '/') { - // parse our key - TQStringList list(TQStringList::split('/', grp_key)); - - if (list.count() < 2) { -#ifdef QT_CHECK_STATE - tqWarning("TQSettings::lastModificationTime: Invalid key '%s'", grp_key.latin1()); -#endif // QT_CHECK_STATE - - return TQDateTime(); - } - - if (list.count() == 2) { - d->heading = list[0]; - d->group = "General"; - } else { - d->heading = list[0]; - d->group = list[1]; - } - } - - return d->modificationTime(); -} - - -/*! - \overload - \obsolete - - Writes the string list entry \a value into key \a key. The \a key - is created if it doesn't exist. Any previous value is overwritten - by \a value. The list is stored as a sequence of strings separated - by \a separator (using TQStringList::join()), so none of the - strings in the list should contain the separator. If the list is - empty or null the key's value will be an empty string. - - \warning The list should not contain empty or null strings, as - readListEntry() will use TQStringList::split() to recreate the - list. As the documentation states, TQStringList::split() will omit - empty strings from the list. Because of this, it is impossible to - retrieve identical list data that is stored with this function. - We recommend using the writeEntry() and readListEntry() overloads - that do not take a \a separator argument. - - - If an error occurs the settings are left unchanged and FALSE is - returned; otherwise returns TRUE. - - \sa readListEntry(), readNumEntry(), readDoubleEntry(), readBoolEntry(), removeEntry(), TQStringList::join() -*/ -bool TQSettings::writeEntry(const TQString &key, const TQStringList &value, - const TQChar &separator) -{ - TQString s(value.join(separator)); - return writeEntry(key, s); -} - -/*! - \overload - - Writes the string list entry \a value into key \a key. The \a key - is created if it doesn't exist. Any previous value is overwritten - by \a value. - - If an error occurs the settings are left unchanged and FALSE is - returned; otherwise returns TRUE. - - \sa readListEntry(), readNumEntry(), readDoubleEntry(), readBoolEntry(), removeEntry() -*/ -bool TQSettings::writeEntry(const TQString &key, const TQStringList &value) -{ - TQString s; - for (TQStringList::ConstIterator it=value.begin(); it!=value.end(); ++it) { - TQString el = *it; - if ( el.isNull() ) { - el = "^0"; - } else { - el.replace("^", "^^"); - } - s+=el; - s+="^e"; // end of element - } - return writeEntry(key, s); -} - - -/*! - \overload TQStringList TQSettings::readListEntry(const TQString &key, const TQChar &separator, bool *ok ) const - \obsolete - - Reads the entry specified by \a key as a string. The \a separator - is used to create a TQStringList by calling TQStringList::split(\a - separator, entry). If \a ok is not 0: \a *ok is set to TRUE - if the key was read, otherwise \a *ok is set to FALSE. - - \warning As the documentation states, TQStringList::split() will - omit empty strings from the list. Because of this, it is - impossible to retrieve identical list data with this function. We - recommend using the readListEntry() and writeEntry() overloads - that do not take a \a separator argument. - - Note that if you want to iterate over the list, you should iterate - over a copy, e.g. - \code - TQStringList list = mySettings.readListEntry( "size", " " ); - TQStringList::Iterator it = list.begin(); - while( it != list.end() ) { - myProcessing( *it ); - ++it; - } - \endcode - - \sa readEntry(), readDoubleEntry(), readBoolEntry(), writeEntry(), removeEntry(), TQStringList::split() -*/ - -/*! - \internal -*/ -TQStringList TQSettings::readListEntry(const TQString &key, const TQChar &separator, bool *ok ) -{ - TQString value = readEntry( key, TQString::null, ok ); - if ( ok && !*ok ) - return TQStringList(); - - return TQStringList::split(separator, value); -} - -/*! - \fn TQStringList TQSettings::readListEntry(const TQString &key, bool *ok ) const - Reads the entry specified by \a key as a string. If \a ok is not - 0, \a *ok is set to TRUE if the key was read, otherwise \a *ok is - set to FALSE. - - Note that if you want to iterate over the list, you should iterate - over a copy, e.g. - \code - TQStringList list = mySettings.readListEntry( "recentfiles" ); - TQStringList::Iterator it = list.begin(); - while( it != list.end() ) { - myProcessing( *it ); - ++it; - } - \endcode - - \sa readEntry(), readDoubleEntry(), readBoolEntry(), writeEntry(), removeEntry(), TQStringList::split() -*/ - -/*! - \internal -*/ -TQStringList TQSettings::readListEntry(const TQString &key, bool *ok ) -{ - TQString value = readEntry( key, TQString::null, ok ); - if ( ok && !*ok ) - return TQStringList(); - TQStringList l; - TQString s; - bool esc=FALSE; - for (int i=0; i<(int)value.length(); i++) { - if ( esc ) { - if ( value[i] == 'e' ) { // end-of-string - l.append(s); - s=""; - } else if ( value[i] == '0' ) { // null string - s=TQString::null; - } else { - s.append(value[i]); - } - esc=FALSE; - } else if ( value[i] == '^' ) { - esc = TRUE; - } else { - s.append(value[i]); - if ( i == (int)value.length()-1 ) - l.append(s); - } - } - return l; -} - -#ifdef Q_OS_MAC -void qt_setSettingsBasePath(const TQString &); //qsettings_mac.cpp -#endif - -/*! - Insert platform-dependent paths from platform-independent information. - - The \a domain should be an Internet domain name - controlled by the producer of the software, eg. Trolltech products - use "trolltech.com". - - The \a product should be the official name of the product. - - The \a scope should be - TQSettings::User for user-specific settings, or - TQSettings::Global for system-wide settings (generally - these will be read-only to many users). - - Not all information is relevant on all systems. -*/ - -void TQSettings::setPath( const TQString &domain, const TQString &product, Scope scope ) -{ -// On Windows, any trailing ".com(\..*)" is stripped from the domain. The -// Global scope corresponds to HKEY_LOCAL_MACHINE, and User corresponds to -// HKEY_CURRENT_USER. Note that on some installations, not all users can -// write to the Global scope. On UNIX, any trailing ".com(\..*)" is stripped -// from the domain. The Global scope corresponds to "/opt" (this would be -// configurable at library build time - eg. to "/usr/local" or "/usr"), -// while the User scope corresponds to $HOME/.*rc. -// Note that on most installations, not all users can write to the System -// scope. -// -// On MacOS X, if there is no "." in domain, append ".com", then reverse the -// order of the elements (Mac OS uses "com.apple.finder" as domain+product). -// The Global scope corresponds to /Library/Preferences/*.plist, while the -// User scope corresponds to ~/Library/Preferences/*.plist. -// Note that on most installations, not all users can write to the System -// scope. - d->globalScope = scope == Global; - - TQString actualSearchPath; - int lastDot = domain.findRev( '.' ); - -#if defined(TQ_WS_WIN) - actualSearchPath = "/" + domain.mid( 0, lastDot ) + "/" + product; - insertSearchPath( Windows, actualSearchPath ); -#elif defined(Q_OS_MAC) - if(lastDot != -1) { - TQString topLevelDomain = domain.right( domain.length() - lastDot - 1 ) + "."; - if ( !topLevelDomain.isEmpty() ) - qt_setSettingsBasePath( topLevelDomain ); - } - actualSearchPath = "/" + domain.left( lastDot ) + "." + product; - insertSearchPath( Mac, actualSearchPath ); -#else - if (scope == User) - actualSearchPath = TQDir::homeDirPath() + "/."; - else - actualSearchPath = TQString(tqInstallPathSysconf()) + "/"; - actualSearchPath += domain.mid( 0, lastDot ) + "/" + product; - insertSearchPath( Unix, actualSearchPath ); -#endif -} - -/*! - Appends \a group to the current key prefix. - - \code - TQSettings settings; - settings.beginGroup( "/MainWindow" ); - // read values - settings.endGroup(); - \endcode -*/ -void TQSettings::beginGroup( const TQString &group ) -{ - d->groupStack.push( group ); - d->groupDirty = TRUE; -} - -/*! - Undo previous calls to beginGroup(). Note that a single beginGroup("a/b/c") is undone - by a single call to endGroup(). - - \code - TQSettings settings; - settings.beginGroup( "/MainWindow/Geometry" ); - // read values - settings.endGroup(); - \endcode -*/ -void TQSettings::endGroup() -{ - d->groupStack.pop(); - d->groupDirty = TRUE; -} - -/*! - Set the current key prefix to the empty string. -*/ -void TQSettings::resetGroup() -{ - d->groupStack.clear(); - d->groupDirty = FALSE; - d->groupPrefix = TQString::null; -} - -/*! - Returns the current key prefix, or a null string if there is no key prefix set. - - \sa beginGroup(); -*/ -TQString TQSettings::group() const -{ - if ( d->groupDirty ) { - d->groupDirty = FALSE; - d->groupPrefix = TQString::null; - - TQValueStack::Iterator it = d->groupStack.begin(); - while ( it != d->groupStack.end() ) { - TQString group = *it; - ++it; - if ( group[0] != '/' ) - group.prepend( "/" ); - d->groupPrefix += group; - } - } - return d->groupPrefix; -} - -#endif diff --git a/src/tools/qsettings_p.h b/src/tools/qsettings_p.h deleted file mode 100644 index 75318492d..000000000 --- a/src/tools/qsettings_p.h +++ /dev/null @@ -1,148 +0,0 @@ -/**************************************************************************** -** -** Definition of TQSettings related classes -** -** Created : 990124 -** -** Copyright (C) 1999-2008 Trolltech ASA. All rights reserved. -** -** This file is part of the kernel module of the TQt GUI Toolkit. -** -** This file may be used under the terms of the GNU General -** Public License versions 2.0 or 3.0 as published by the Free -** Software Foundation and appearing in the files LICENSE.GPL2 -** and LICENSE.GPL3 included in the packaging of this file. -** Alternatively you may (at your option) use any later version -** of the GNU General Public License if such license has been -** publicly approved by Trolltech ASA (or its successors, if any) -** and the KDE Free TQt Foundation. -** -** Please review the following information to ensure GNU General -** Public Licensing requirements will be met: -** http://trolltech.com/products/qt/licenses/licensing/opensource/. -** If you are unsure which license is appropriate for your use, please -** review the following information: -** http://trolltech.com/products/qt/licenses/licensing/licensingoverview -** or contact the sales department at sales@trolltech.com. -** -** This file may be used under the terms of the Q Public License as -** defined by Trolltech ASA and appearing in the file LICENSE.TQPL -** included in the packaging of this file. Licensees holding valid TQt -** Commercial licenses may use this file in accordance with the TQt -** Commercial License Agreement provided with the Software. -** -** This file is provided "AS IS" with NO WARRANTY OF ANY KIND, -** INCLUDING THE WARRANTIES OF DESIGN, MERCHANTABILITY AND FITNESS FOR -** A PARTICULAR PURPOSE. Trolltech reserves all rights not granted -** herein. -** -**********************************************************************/ - -#ifndef TQSETTINGS_P_H -#define TQSETTINGS_P_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the TQt API. It exists for the convenience -// of TQSettings. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// -// - -#ifndef QT_H -#include "tqstringlist.h" -#include "tqmap.h" -#include "tqvaluestack.h" -#endif // QT_H - -#ifndef TQT_NO_SETTINGS -class TQSettingsSysPrivate; - -// TQSettingsGroup is a map of key/value pairs -class TQSettingsGroup : public TQMap -{ -public: - TQSettingsGroup(); - - bool modified; -}; - -// TQSettingsHeading is a map of heading/group pairs -class TQSettingsHeading : public TQMap -{ -public: - TQSettingsHeading::Iterator git; - void read(const TQString &); - void parseLine(TQTextStream &); -}; - - -class TQSettingsPrivate -{ -public: - TQSettingsPrivate( TQSettings::Format format ); - ~TQSettingsPrivate(); - - TQSettingsGroup readGroup(); - void removeGroup(const TQString &); - void writeGroup(const TQString &, const TQString &); - TQDateTime modificationTime(); - - TQStringList searchPaths; - TQMap headings; - TQString group; - TQString heading; - - /*### static data brings threading trouble - static TQString *defProduct; - static TQString *defDomain; - */ - TQValueStack groupStack; - TQString groupPrefix; - - bool groupDirty :1; - bool modified :1; - bool globalScope :1; - -#if defined(TQ_WS_WIN) || defined(Q_OS_MAC) - // system dependent implementations to use the - // system specific setting database (ie. registry on Windows) - - TQSettingsSysPrivate *sysd; - void sysInit(); - void sysClear(); - -#if !defined(Q_NO_BOOL_TYPE) - bool sysWriteEntry( const TQString &, bool ); -#endif - bool sysWriteEntry( const TQString &, double ); - bool sysWriteEntry( const TQString &, int ); - bool sysWriteEntry( const TQString &, const TQString & ); - bool sysWriteEntry( const TQString &, const TQStringList & ); - bool sysWriteEntry( const TQString &, const TQStringList &, const TQChar& sep ); - - TQStringList sysEntryList(const TQString &) const; - TQStringList sysSubkeyList(const TQString &) const; - - TQStringList sysReadListEntry( const TQString &, bool * = 0 ) const; - TQStringList sysReadListEntry( const TQString &, const TQChar& sep, bool * = 0 ) const; - TQString sysReadEntry( const TQString &, const TQString &def = TQString::null, bool * = 0 ) const; - int sysReadNumEntry( const TQString &, int def = 0, bool * = 0 ) const; - double sysReadDoubleEntry( const TQString &, double def = 0, bool * = 0 ) const; - bool sysReadBoolEntry( const TQString &, bool def = 0, bool * = 0 ) const; - - bool sysRemoveEntry( const TQString & ); - - bool sysSync(); - - void sysInsertSearchPath( TQSettings::System, const TQString & ); - void sysRemoveSearchPath( TQSettings::System, const TQString & ); -#endif - -}; -#endif //TQT_NO_SETTINGS -#endif // TQSETTINGS_P_H diff --git a/src/tools/qt_tools.pri b/src/tools/qt_tools.pri index dc9fa2753..c4cced519 100644 --- a/src/tools/qt_tools.pri +++ b/src/tools/qt_tools.pri @@ -6,21 +6,21 @@ tools { $$TOOLS_H/tqasciicache.h \ $$TOOLS_H/tqasciidict.h \ $$TOOLS_H/tqbitarray.h \ - $$TOOLS_H/ntqbuffer.h \ + $$TOOLS_H/tqbuffer.h \ $$TOOLS_H/tqcache.h \ $$TOOLS_H/ntqcleanuphandler.h \ $$TOOLS_P/qcomponentfactory_p.h \ $$TOOLS_P/qcomlibrary_p.h \ $$TOOLS_H/tqcstring.h \ - $$TOOLS_H/ntqdatastream.h \ + $$TOOLS_H/tqdatastream.h \ $$TOOLS_H/tqdatetime.h \ $$TOOLS_H/tqdeepcopy.h \ $$TOOLS_H/tqdict.h \ - $$TOOLS_H/ntqdir.h \ - $$TOOLS_P/qdir_p.h \ - $$TOOLS_H/ntqfile.h \ - $$TOOLS_P/qfiledefs_p.h \ - $$TOOLS_H/ntqfileinfo.h \ + $$TOOLS_H/tqdir.h \ + $$TOOLS_P/tqdir_p.h \ + $$TOOLS_H/tqfile.h \ + $$TOOLS_P/tqfiledefs_p.h \ + $$TOOLS_H/tqfileinfo.h \ $$TOOLS_H/ntqgarray.h \ $$TOOLS_H/ntqgcache.h \ $$TOOLS_H/ntqgdict.h \ @@ -31,7 +31,7 @@ tools { $$TOOLS_H/ntqgvector.h \ $$TOOLS_H/tqintcache.h \ $$TOOLS_H/tqintdict.h \ - $$TOOLS_H/ntqiodevice.h \ + $$TOOLS_H/tqiodevice.h \ $$TOOLS_H/ntqlibrary.h \ $$TOOLS_P/qlibrary_p.h \ $$TOOLS_H/ntqlocale.h \ @@ -47,8 +47,8 @@ tools { $$TOOLS_H/tqptrqueue.h \ $$TOOLS_H/tqregexp.h \ $$TOOLS_H/tqsemaphore.h \ - $$TOOLS_H/ntqsettings.h \ - $$TOOLS_P/qsettings_p.h \ + $$TOOLS_H/tqsettings.h \ + $$TOOLS_P/tqsettings_p.h \ $$TOOLS_H/ntqshared.h \ $$TOOLS_H/tqptrstack.h \ $$TOOLS_H/tqstring.h \ @@ -68,11 +68,11 @@ tools { $$TOOLS_P/qucom_p.h \ $$TOOLS_H/ntquuid.h - win32:SOURCES += $$TOOLS_CPP/qdir_win.cpp \ - $$TOOLS_CPP/qfile_win.cpp \ - $$TOOLS_CPP/qfileinfo_win.cpp \ + win32:SOURCES += $$TOOLS_CPP/tqdir_win.cpp \ + $$TOOLS_CPP/tqfile_win.cpp \ + $$TOOLS_CPP/tqfileinfo_win.cpp \ $$TOOLS_CPP/qlibrary_win.cpp \ - $$TOOLS_CPP/qsettings_win.cpp \ + $$TOOLS_CPP/tqsettings_win.cpp \ $$TOOLS_CPP/tqmutex_win.cpp \ $$TOOLS_CPP/tqwaitcondition_win.cpp \ $$TOOLS_CPP/tqthreadstorage_win.cpp \ @@ -81,25 +81,25 @@ tools { win32-borland:SOURCES += $$TOOLS_CPP/qwinexport.cpp wince-* { - SOURCES -= $$TOOLS_CPP/qdir_win.cpp \ - $$TOOLS_CPP/qfile_win.cpp \ - $$TOOLS_CPP/qfileinfo_win.cpp - SOURCES += $$TOOLS_CPP/qdir_wce.cpp \ - $$TOOLS_CPP/qfile_wce.cpp \ - $$TOOLS_CPP/qfileinfo_wce.cpp + SOURCES -= $$TOOLS_CPP/tqdir_win.cpp \ + $$TOOLS_CPP/tqfile_win.cpp \ + $$TOOLS_CPP/tqfileinfo_win.cpp + SOURCES += $$TOOLS_CPP/tqdir_wce.cpp \ + $$TOOLS_CPP/tqfile_wce.cpp \ + $$TOOLS_CPP/tqfileinfo_wce.cpp } - offmac:SOURCES += $$TOOLS_CPP/qdir_mac.cpp \ - $$TOOLS_CPP/qfile_mac.cpp \ - $$TOOLS_CPP/qfileinfo_mac.cpp - else:unix:SOURCES += $$TOOLS_CPP/qdir_unix.cpp \ - $$TOOLS_CPP/qfile_unix.cpp \ - $$TOOLS_CPP/qfileinfo_unix.cpp \ + offmac:SOURCES += $$TOOLS_CPP/tqdir_mac.cpp \ + $$TOOLS_CPP/tqfile_mac.cpp \ + $$TOOLS_CPP/tqfileinfo_mac.cpp + else:unix:SOURCES += $$TOOLS_CPP/tqdir_unix.cpp \ + $$TOOLS_CPP/tqfile_unix.cpp \ + $$TOOLS_CPP/tqfileinfo_unix.cpp \ $$TOOLS_CPP/tqmutex_unix.cpp \ $$TOOLS_CPP/tqthreadstorage_unix.cpp \ $$TOOLS_CPP/tqwaitcondition_unix.cpp - mac:!x11:!embedded:SOURCES += $$TOOLS_CPP/qsettings_mac.cpp + mac:!x11:!embedded:SOURCES += $$TOOLS_CPP/tqsettings_mac.cpp mac { SOURCES+=3rdparty/dlcompat/dlfcn.c INCLUDEPATH+=3rdparty/dlcompat @@ -107,16 +107,16 @@ tools { unix:SOURCES += $$TOOLS_CPP/qlibrary_unix.cpp SOURCES += $$TOOLS_CPP/tqbitarray.cpp \ - $$TOOLS_CPP/qbuffer.cpp \ + $$TOOLS_CPP/tqbuffer.cpp \ $$TOOLS_CPP/qcomponentfactory.cpp \ $$TOOLS_CPP/qcomlibrary.cpp \ $$TOOLS_CPP/tqcstring.cpp \ - $$TOOLS_CPP/qdatastream.cpp \ + $$TOOLS_CPP/tqdatastream.cpp \ $$TOOLS_CPP/tqdatetime.cpp \ $$TOOLS_CPP/tqdeepcopy.cpp \ - $$TOOLS_CPP/qdir.cpp \ - $$TOOLS_CPP/qfile.cpp \ - $$TOOLS_CPP/qfileinfo.cpp \ + $$TOOLS_CPP/tqdir.cpp \ + $$TOOLS_CPP/tqfile.cpp \ + $$TOOLS_CPP/tqfileinfo.cpp \ $$TOOLS_CPP/qgarray.cpp \ $$TOOLS_CPP/qgcache.cpp \ $$TOOLS_CPP/qgdict.cpp \ @@ -124,7 +124,7 @@ tools { $$TOOLS_CPP/qglobal.cpp \ $$TOOLS_CPP/qgpluginmanager.cpp \ $$TOOLS_CPP/qgvector.cpp \ - $$TOOLS_CPP/qiodevice.cpp \ + $$TOOLS_CPP/tqiodevice.cpp \ $$TOOLS_CPP/qlibrary.cpp \ $$TOOLS_CPP/qlocale.cpp \ $$TOOLS_CPP/tqmap.cpp \ @@ -133,7 +133,7 @@ tools { $$TOOLS_CPP/tqregexp.cpp \ $$TOOLS_CPP/tqstring.cpp \ $$TOOLS_CPP/tqsemaphore.cpp \ - $$TOOLS_CPP/qsettings.cpp \ + $$TOOLS_CPP/tqsettings.cpp \ $$TOOLS_CPP/tqstringlist.cpp \ $$TOOLS_CPP/tqtextstream.cpp \ $$TOOLS_CPP/qunicodetables.cpp \ diff --git a/src/tools/quuid.cpp b/src/tools/quuid.cpp index 34b6e3db7..b07eadd09 100644 --- a/src/tools/quuid.cpp +++ b/src/tools/quuid.cpp @@ -38,7 +38,7 @@ #include "ntquuid.h" -#include "ntqdatastream.h" +#include "tqdatastream.h" /*! \class TQUuid ntquuid.h diff --git a/src/tools/qwinexport.cpp b/src/tools/qwinexport.cpp index cb5ce9c17..64422497e 100644 --- a/src/tools/qwinexport.cpp +++ b/src/tools/qwinexport.cpp @@ -7,9 +7,9 @@ #include #include #include -#include +#include #include -#include +#include #include #include #include diff --git a/src/tools/tqbitarray.cpp b/src/tools/tqbitarray.cpp index 283a99406..5eb33b92b 100644 --- a/src/tools/tqbitarray.cpp +++ b/src/tools/tqbitarray.cpp @@ -39,7 +39,7 @@ **********************************************************************/ #include "tqbitarray.h" -#include "ntqdatastream.h" +#include "tqdatastream.h" #define SHBLOCK ((bitarr_data*)(sharedBlock())) diff --git a/src/tools/tqbuffer.cpp b/src/tools/tqbuffer.cpp new file mode 100644 index 000000000..827f5c187 --- /dev/null +++ b/src/tools/tqbuffer.cpp @@ -0,0 +1,494 @@ +/**************************************************************************** +** +** Implementation of TQBuffer class +** +** Created : 930812 +** +** Copyright (C) 1992-2008 Trolltech ASA. All rights reserved. +** +** This file is part of the tools module of the TQt GUI Toolkit. +** +** This file may be used under the terms of the GNU General +** Public License versions 2.0 or 3.0 as published by the Free +** Software Foundation and appearing in the files LICENSE.GPL2 +** and LICENSE.GPL3 included in the packaging of this file. +** Alternatively you may (at your option) use any later version +** of the GNU General Public License if such license has been +** publicly approved by Trolltech ASA (or its successors, if any) +** and the KDE Free TQt Foundation. +** +** Please review the following information to ensure GNU General +** Public Licensing requirements will be met: +** http://trolltech.com/products/qt/licenses/licensing/opensource/. +** If you are unsure which license is appropriate for your use, please +** review the following information: +** http://trolltech.com/products/qt/licenses/licensing/licensingoverview +** or contact the sales department at sales@trolltech.com. +** +** This file may be used under the terms of the Q Public License as +** defined by Trolltech ASA and appearing in the file LICENSE.TQPL +** included in the packaging of this file. Licensees holding valid TQt +** Commercial licenses may use this file in accordance with the TQt +** Commercial License Agreement provided with the Software. +** +** This file is provided "AS IS" with NO WARRANTY OF ANY KIND, +** INCLUDING THE WARRANTIES OF DESIGN, MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE. Trolltech reserves all rights not granted +** herein. +** +**********************************************************************/ + +#include "tqbuffer.h" +#include + +/*! + \class TQBuffer tqbuffer.h + \reentrant + \brief The TQBuffer class is an I/O device that operates on a TQByteArray. + + \ingroup io + \ingroup collection + + TQBuffer is used to read and write to a memory buffer. It is + normally used with a TQTextStream or a TQDataStream. TQBuffer has an + associated TQByteArray which holds the buffer data. The size() of + the buffer is automatically adjusted as data is written. + + The constructor \c TQBuffer(TQByteArray) creates a TQBuffer using an + existing byte array. The byte array can also be set with + setBuffer(). Writing to the TQBuffer will modify the original byte + array because TQByteArray is \link shclass.html explicitly + shared.\endlink + + Use open() to open the buffer before use and to set the mode + (read-only, write-only, etc.). close() closes the buffer. The + buffer must be closed before reopening or calling setBuffer(). + + A common way to use TQBuffer is through \l TQDataStream or \l + TQTextStream, which have constructors that take a TQBuffer + parameter. For convenience, there are also TQDataStream and + TQTextStream constructors that take a TQByteArray parameter. These + constructors create and open an internal TQBuffer. + + Note that TQTextStream can also operate on a TQString (a Unicode + string); a TQBuffer cannot. + + You can also use TQBuffer directly through the standard TQIODevice + functions readBlock(), writeBlock() readLine(), at(), getch(), + putch() and ungetch(). + + \sa TQFile, TQDataStream, TQTextStream, TQByteArray, \link shclass.html Shared Classes\endlink +*/ + + +/*! + Constructs an empty buffer. +*/ + +TQBuffer::TQBuffer() +{ + setFlags( IO_Direct ); + a_inc = 16; // initial increment + a_len = 0; + ioIndex = 0; +} + + +/*! + Constructs a buffer that operates on \a buf. + + If you open the buffer in write mode (\c IO_WriteOnly or + \c IO_ReadWrite) and write something into the buffer, \a buf + will be modified. + + Example: + \code + TQCString str = "abc"; + TQBuffer b( str ); + b.open( IO_WriteOnly ); + b.at( 3 ); // position at the 4th character (the terminating \0) + b.writeBlock( "def", 4 ); // write "def" including the terminating \0 + b.close(); + // Now, str == "abcdef" with a terminating \0 + \endcode + + \sa setBuffer() +*/ + +TQBuffer::TQBuffer( TQByteArray buf ) : a(buf) +{ + setFlags( IO_Direct ); + a_len = a.size(); + a_inc = (a_len > 512) ? 512 : a_len; // initial increment + if ( a_inc < 16 ) + a_inc = 16; + ioIndex = 0; +} + +/*! + Destroys the buffer. +*/ + +TQBuffer::~TQBuffer() +{ +} + + +/*! + Replaces the buffer's contents with \a buf and returns TRUE. + + Does nothing (and returns FALSE) if isOpen() is TRUE. + + Note that if you open the buffer in write mode (\c IO_WriteOnly or + IO_ReadWrite) and write something into the buffer, \a buf is also + modified because TQByteArray is an explicitly shared class. + + \sa buffer(), open(), close() +*/ + +bool TQBuffer::setBuffer( TQByteArray buf ) +{ + if ( isOpen() ) { +#if defined(QT_CHECK_STATE) + tqWarning( "TQBuffer::setBuffer: Buffer is open" ); +#endif + return FALSE; + } + a = buf; + a_len = a.size(); + a_inc = (a_len > 512) ? 512 : a_len; // initial increment + if ( a_inc < 16 ) + a_inc = 16; + ioIndex = 0; + return TRUE; +} + +/*! + \fn TQByteArray TQBuffer::buffer() const + + Returns this buffer's byte array. + + \sa setBuffer() +*/ + +/*! + \reimp + + Opens the buffer in mode \a m. Returns TRUE if successful; + otherwise returns FALSE. The buffer must be opened before use. + + The mode parameter \a m must be a combination of the following flags. + \list + \i \c IO_ReadOnly opens the buffer in read-only mode. + \i \c IO_WriteOnly opens the buffer in write-only mode. + \i \c IO_ReadWrite opens the buffer in read/write mode. + \i \c IO_Append sets the buffer index to the end of the buffer. + \i \c IO_Truncate truncates the buffer. + \endlist + + \sa close(), isOpen() +*/ + +bool TQBuffer::open( int m ) +{ + if ( isOpen() ) { // buffer already open +#if defined(QT_CHECK_STATE) + tqWarning( "TQBuffer::open: Buffer already open" ); +#endif + return FALSE; + } + setMode( m ); + if ( m & IO_Truncate ) { // truncate buffer + a.resize( 0 ); + a_len = 0; + } + if ( m & IO_Append ) { // append to end of buffer + ioIndex = a.size(); + } else { + ioIndex = 0; + } + a_inc = 16; + setState( IO_Open ); + resetStatus(); + return TRUE; +} + +/*! + \reimp + + Closes an open buffer. + + \sa open() +*/ + +void TQBuffer::close() +{ + if ( isOpen() ) { + setFlags( IO_Direct ); + ioIndex = 0; + a_inc = 16; + } +} + +/*! + \reimp + + The flush function does nothing for a TQBuffer. +*/ + +void TQBuffer::flush() +{ + return; +} + + +/*! + \fn TQIODevice::Offset TQBuffer::at() const + + \reimp +*/ + +/*! + \fn TQIODevice::Offset TQBuffer::size() const + + \reimp +*/ + +/*! + \reimp +*/ + +bool TQBuffer::at( Offset pos ) +{ +#if defined(QT_CHECK_STATE) + if ( !isOpen() ) { + tqWarning( "TQBuffer::at: Buffer is not open" ); + return FALSE; + } +#endif + if ( pos > a_len ) { +#if defined(QT_CHECK_RANGE) + tqWarning( "TQBuffer::at: Index %lu out of range", pos ); +#endif + return FALSE; + } + ioIndex = pos; + return TRUE; +} + + +/*! + \reimp +*/ + +TQ_LONG TQBuffer::readBlock( char *p, TQ_ULONG len ) +{ +#if defined(QT_CHECK_STATE) + if ( !p ) { + tqWarning( "TQBuffer::readBlock: Null pointer error" ); + return -1; + } + if ( !isOpen() ) { // buffer not open + tqWarning( "TQBuffer::readBlock: Buffer not open" ); + return -1; + } + if ( !isReadable() ) { // reading not permitted + tqWarning( "TQBuffer::readBlock: Read operation not permitted" ); + return -1; + } +#endif + if ( ioIndex + len > a.size() ) { // overflow + if ( ioIndex >= a.size() ) { + return 0; + } else { + len = a.size() - ioIndex; + } + } + memcpy(p, a.data() + ioIndex, len); + ioIndex += len; + return len; +} + +/*! + \overload TQ_LONG TQBuffer::writeBlock( const TQByteArray& data ) + + This convenience function is the same as calling + \c{writeBlock( data.data(), data.size() )} with \a data. +*/ + +/*! + Writes \a len bytes from \a p into the buffer at the current + index position, overwriting any characters there and extending the + buffer if necessary. Returns the number of bytes actually written. + + Returns -1 if an error occurred. + + \sa readBlock() +*/ + +TQ_LONG TQBuffer::writeBlock( const char *p, TQ_ULONG len ) +{ + if ( len == 0 ) + return 0; + +#if defined(QT_CHECK_NULL) + if ( p == 0 ) { + tqWarning( "TQBuffer::writeBlock: Null pointer error" ); + return -1; + } +#endif +#if defined(QT_CHECK_STATE) + if ( !isOpen() ) { // buffer not open + tqWarning( "TQBuffer::writeBlock: Buffer not open" ); + return -1; + } + if ( !isWritable() ) { // writing not permitted + tqWarning( "TQBuffer::writeBlock: Write operation not permitted" ); + return -1; + } +#endif + if ( ioIndex + len > a_len ) { // overflow + TQ_ULONG new_len = a_len + a_inc*((ioIndex+len-a_len)/a_inc+1); + if ( !a.resize( new_len ) ) { // could not resize +#if defined(QT_CHECK_NULL) + tqWarning( "TQBuffer::writeBlock: Memory allocation error" ); +#endif + setStatus( IO_ResourceError ); + return -1; + } + a_inc *= 2; // double increment + a_len = new_len; + a.shd->len = ioIndex + len; + } + memcpy( a.data()+ioIndex, p, len ); + ioIndex += len; + if ( a.shd->len < ioIndex ) + a.shd->len = ioIndex; // fake (not alloc'd) length + return len; +} + + +/*! + \reimp +*/ + +TQ_LONG TQBuffer::readLine( char *p, TQ_ULONG maxlen ) +{ +#if defined(QT_CHECK_NULL) + if ( p == 0 ) { + tqWarning( "TQBuffer::readLine: Null pointer error" ); + return -1; + } +#endif +#if defined(QT_CHECK_STATE) + if ( !isOpen() ) { // buffer not open + tqWarning( "TQBuffer::readLine: Buffer not open" ); + return -1; + } + if ( !isReadable() ) { // reading not permitted + tqWarning( "TQBuffer::readLine: Read operation not permitted" ); + return -1; + } +#endif + if ( maxlen == 0 ) + return 0; + TQ_ULONG start = ioIndex; + char *d = a.data() + ioIndex; + maxlen--; // make room for 0-terminator + if ( a.size() - ioIndex < maxlen ) + maxlen = a.size() - ioIndex; + while ( maxlen-- ) { + if ( (*p++ = *d++) == '\n' ) + break; + } + *p = '\0'; + ioIndex = d - a.data(); + return ioIndex - start; +} + + +/*! + \reimp +*/ + +int TQBuffer::getch() +{ +#if defined(QT_CHECK_STATE) + if ( !isOpen() ) { // buffer not open + tqWarning( "TQBuffer::getch: Buffer not open" ); + return -1; + } + if ( !isReadable() ) { // reading not permitted + tqWarning( "TQBuffer::getch: Read operation not permitted" ); + return -1; + } +#endif + if ( ioIndex+1 > a.size() ) { // overflow + setStatus( IO_ReadError ); + return -1; + } + return uchar(*(a.data()+ioIndex++)); +} + +/*! + \reimp + + Writes the character \a ch into the buffer at the current index + position, overwriting any existing character and extending the + buffer if necessary. + + Returns \a ch, or -1 if an error occurred. + + \sa getch(), ungetch() +*/ + +int TQBuffer::putch( int ch ) +{ +#if defined(QT_CHECK_STATE) + if ( !isOpen() ) { // buffer not open + tqWarning( "TQBuffer::putch: Buffer not open" ); + return -1; + } + if ( !isWritable() ) { // writing not permitted + tqWarning( "TQBuffer::putch: Write operation not permitted" ); + return -1; + } +#endif + if ( ioIndex + 1 > a_len ) { // overflow + char buf[1]; + buf[0] = (char)ch; + if ( writeBlock(buf,1) != 1 ) + return -1; // write error + } else { + *(a.data() + ioIndex++) = (char)ch; + if ( a.shd->len < ioIndex ) + a.shd->len = ioIndex; + } + return ch; +} + +/*! + \reimp +*/ + +int TQBuffer::ungetch( int ch ) +{ +#if defined(QT_CHECK_STATE) + if ( !isOpen() ) { // buffer not open + tqWarning( "TQBuffer::ungetch: Buffer not open" ); + return -1; + } + if ( !isReadable() ) { // reading not permitted + tqWarning( "TQBuffer::ungetch: Read operation not permitted" ); + return -1; + } +#endif + if ( ch != -1 ) { + if ( ioIndex ) + ioIndex--; + else + ch = -1; + } + return ch; +} + diff --git a/src/tools/tqbuffer.h b/src/tools/tqbuffer.h new file mode 100644 index 000000000..ff5899826 --- /dev/null +++ b/src/tools/tqbuffer.h @@ -0,0 +1,103 @@ +/**************************************************************************** +** +** Definition of TQBuffer class +** +** Created : 930812 +** +** Copyright (C) 1992-2008 Trolltech ASA. All rights reserved. +** +** This file is part of the tools module of the TQt GUI Toolkit. +** +** This file may be used under the terms of the GNU General +** Public License versions 2.0 or 3.0 as published by the Free +** Software Foundation and appearing in the files LICENSE.GPL2 +** and LICENSE.GPL3 included in the packaging of this file. +** Alternatively you may (at your option) use any later version +** of the GNU General Public License if such license has been +** publicly approved by Trolltech ASA (or its successors, if any) +** and the KDE Free TQt Foundation. +** +** Please review the following information to ensure GNU General +** Public Licensing requirements will be met: +** http://trolltech.com/products/qt/licenses/licensing/opensource/. +** If you are unsure which license is appropriate for your use, please +** review the following information: +** http://trolltech.com/products/qt/licenses/licensing/licensingoverview +** or contact the sales department at sales@trolltech.com. +** +** This file may be used under the terms of the Q Public License as +** defined by Trolltech ASA and appearing in the file LICENSE.TQPL +** included in the packaging of this file. Licensees holding valid TQt +** Commercial licenses may use this file in accordance with the TQt +** Commercial License Agreement provided with the Software. +** +** This file is provided "AS IS" with NO WARRANTY OF ANY KIND, +** INCLUDING THE WARRANTIES OF DESIGN, MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE. Trolltech reserves all rights not granted +** herein. +** +**********************************************************************/ + +#ifndef TQBUFFER_H +#define TQBUFFER_H + +#ifndef QT_H +#include "tqiodevice.h" +#include "tqstring.h" +#endif // QT_H + + +class TQ_EXPORT TQBuffer : public TQIODevice +{ +public: + TQBuffer(); + TQBuffer( TQByteArray ); + ~TQBuffer(); + + TQByteArray buffer() const; + bool setBuffer( TQByteArray ); + + bool open( int ); + void close(); + void flush(); + + Offset size() const; + Offset at() const; + bool at( Offset ); + + TQ_LONG readBlock( char *p, TQ_ULONG ); + TQ_LONG writeBlock( const char *p, TQ_ULONG ); + TQ_LONG writeBlock( const TQByteArray& data ) + { return TQIODevice::writeBlock(data); } + TQ_LONG readLine( char *p, TQ_ULONG ); + + int getch(); + int putch( int ); + int ungetch( int ); + +protected: + TQByteArray a; + +private: + uint a_len; + uint a_inc; + +private: // Disabled copy constructor and operator= +#if defined(TQ_DISABLE_COPY) + TQBuffer( const TQBuffer & ); + TQBuffer &operator=( const TQBuffer & ); +#endif +}; + + +inline TQByteArray TQBuffer::buffer() const +{ return a; } + +inline TQIODevice::Offset TQBuffer::size() const +{ return (Offset)a.size(); } + +inline TQIODevice::Offset TQBuffer::at() const +{ return ioIndex; } + + +#endif // TQBUFFER_H diff --git a/src/tools/tqcstring.cpp b/src/tools/tqcstring.cpp index d4af46412..8c09d227c 100644 --- a/src/tools/tqcstring.cpp +++ b/src/tools/tqcstring.cpp @@ -41,7 +41,7 @@ #include "tqstring.h" #include "tqregexp.h" -#include "ntqdatastream.h" +#include "tqdatastream.h" #ifdef TQT_THREAD_SUPPORT # include diff --git a/src/tools/tqdatastream.cpp b/src/tools/tqdatastream.cpp new file mode 100644 index 000000000..f2980a4e1 --- /dev/null +++ b/src/tools/tqdatastream.cpp @@ -0,0 +1,1180 @@ +/**************************************************************************** +** +** Implementation of TQDataStream class +** +** Created : 930831 +** +** Copyright (C) 1992-2008 Trolltech ASA. All rights reserved. +** +** This file is part of the tools module of the TQt GUI Toolkit. +** +** This file may be used under the terms of the GNU General +** Public License versions 2.0 or 3.0 as published by the Free +** Software Foundation and appearing in the files LICENSE.GPL2 +** and LICENSE.GPL3 included in the packaging of this file. +** Alternatively you may (at your option) use any later version +** of the GNU General Public License if such license has been +** publicly approved by Trolltech ASA (or its successors, if any) +** and the KDE Free TQt Foundation. +** +** Please review the following information to ensure GNU General +** Public Licensing requirements will be met: +** http://trolltech.com/products/qt/licenses/licensing/opensource/. +** If you are unsure which license is appropriate for your use, please +** review the following information: +** http://trolltech.com/products/qt/licenses/licensing/licensingoverview +** or contact the sales department at sales@trolltech.com. +** +** This file may be used under the terms of the Q Public License as +** defined by Trolltech ASA and appearing in the file LICENSE.TQPL +** included in the packaging of this file. Licensees holding valid TQt +** Commercial licenses may use this file in accordance with the TQt +** Commercial License Agreement provided with the Software. +** +** This file is provided "AS IS" with NO WARRANTY OF ANY KIND, +** INCLUDING THE WARRANTIES OF DESIGN, MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE. Trolltech reserves all rights not granted +** herein. +** +**********************************************************************/ + +#include "tqdatastream.h" + +#ifndef TQT_NO_DATASTREAM +#include "tqbuffer.h" +#include +#include +#include +#ifndef Q_OS_TEMP +#include +#else +#include "qt_windows.h" +#endif + +/*! + \class TQDataStream tqdatastream.h + \reentrant + \brief The TQDataStream class provides serialization of binary data + to a TQIODevice. + + \ingroup io + + A data stream is a binary stream of encoded information which is + 100% independent of the host computer's operating system, CPU or + byte order. For example, a data stream that is written by a PC + under Windows can be read by a Sun SPARC running Solaris. + + You can also use a data stream to read/write \link #raw raw + unencoded binary data\endlink. If you want a "parsing" input + stream, see TQTextStream. + + The TQDataStream class implements the serialization of C++'s basic + data types, like \c char, \c short, \c int, \c char*, etc. + Serialization of more complex data is accomplished by breaking up + the data into primitive units. + + A data stream cooperates closely with a TQIODevice. A TQIODevice + represents an input/output medium one can read data from and write + data to. The TQFile class is an example of an IO device. + + Example (write binary data to a stream): + \code + TQFile file( "file.dat" ); + file.open( IO_WriteOnly ); + TQDataStream stream( &file ); // we will serialize the data into the file + stream << "the answer is"; // serialize a string + stream << (TQ_INT32)42; // serialize an integer + \endcode + + Example (read binary data from a stream): + \code + TQFile file( "file.dat" ); + file.open( IO_ReadOnly ); + TQDataStream stream( &file ); // read the data serialized from the file + TQString str; + TQ_INT32 a; + stream >> str >> a; // extract "the answer is" and 42 + \endcode + + Each item written to the stream is written in a predefined binary + format that varies depending on the item's type. Supported TQt + types include TQBrush, TQColor, TQDateTime, TQFont, TQPixmap, TQString, + TQVariant and many others. For the complete list of all TQt types + supporting data streaming see the \link datastreamformat.html + Format of the TQDataStream operators \endlink. + + For integers it is best to always cast to a TQt integer type for + writing, and to read back into the same TQt integer type. This + ensures that you get integers of the size you want and insulates + you from compiler and platform differences. + + To take one example, a \c char* string is written as a 32-bit + integer equal to the length of the string including the NUL byte + ('\0'), followed by all the characters of the string including the + NUL byte. When reading a \c char* string, 4 bytes are read to + create the 32-bit length value, then that many characters for the + \c char* string including the NUL are read. + + The initial IODevice is usually set in the constructor, but can be + changed with setDevice(). If you've reached the end of the data + (or if there is no IODevice set) atEnd() will return TRUE. + + If you want the data to be compatible with an earlier version of + TQt use setVersion(). + + If you want the data to be human-readable, e.g. for debugging, you + can set the data stream into printable data mode with + setPrintableData(). The data is then written slower, in a bloated + but human readable format. + + If you are producing a new binary data format, such as a file + format for documents created by your application, you could use a + TQDataStream to write the data in a portable format. Typically, you + would write a brief header containing a magic string and a version + number to give yourself room for future expansion. For example: + + \code + TQFile file( "file.xxx" ); + file.open( IO_WriteOnly ); + TQDataStream stream( &file ); + + // Write a header with a "magic number" and a version + stream << (TQ_UINT32)0xA0B0C0D0; + stream << (TQ_INT32)123; + + // Write the data + stream << [lots of interesting data] + \endcode + + Then read it in with: + + \code + TQFile file( "file.xxx" ); + file.open( IO_ReadOnly ); + TQDataStream stream( &file ); + + // Read and check the header + TQ_UINT32 magic; + stream >> magic; + if ( magic != 0xA0B0C0D0 ) + return XXX_BAD_FILE_FORMAT; + + // Read the version + TQ_INT32 version; + stream >> version; + if ( version < 100 ) + return XXX_BAD_FILE_TOO_OLD; + if ( version > 123 ) + return XXX_BAD_FILE_TOO_NEW; + if ( version <= 110 ) + stream.setVersion(1); + + // Read the data + stream >> [lots of interesting data]; + if ( version > 120 ) + stream >> [data new in XXX version 1.2]; + stream >> [other interesting data]; + \endcode + + You can select which byte order to use when serializing data. The + default setting is big endian (MSB first). Changing it to little + endian breaks the portability (unless the reader also changes to + little endian). We recommend keeping this setting unless you have + special requirements. + + \target raw + \section1 Reading and writing raw binary data + + You may wish to read/write your own raw binary data to/from the + data stream directly. Data may be read from the stream into a + preallocated char* using readRawBytes(). Similarly data can be + written to the stream using writeRawBytes(). Notice that any + encoding/decoding of the data must be done by you. + + A similar pair of functions is readBytes() and writeBytes(). These + differ from their \e raw counterparts as follows: readBytes() + reads a TQ_UINT32 which is taken to be the length of the data to be + read, then that number of bytes is read into the preallocated + char*; writeBytes() writes a TQ_UINT32 containing the length of the + data, followed by the data. Notice that any encoding/decoding of + the data (apart from the length TQ_UINT32) must be done by you. + + \sa TQTextStream TQVariant +*/ + +/*! + \enum TQDataStream::ByteOrder + + The byte order used for reading/writing the data. + + \value BigEndian the default + \value LittleEndian +*/ + + +/***************************************************************************** + TQDataStream member functions + *****************************************************************************/ + +#if defined(QT_CHECK_STATE) +#undef CHECK_STREAM_PRECOND +#define CHECK_STREAM_PRECOND if ( !dev ) { \ + tqWarning( "TQDataStream: No device" ); \ + return *this; } +#else +#define CHECK_STREAM_PRECOND +#endif + +static int systemWordSize = 0; +static bool systemBigEndian; + +static const int DefaultStreamVersion = 6; +// ### On next version bump, TQPen::width() should not be restricted to 8-bit values. +// ### On next version bump, when streaming invalid TQVariants, just the type should +// be written, no "data" after it +// 6 is default in TQt 3.3 +// 5 is default in TQt 3.1 +// 4 is default in TQt 3.0 +// 3 is default in TQt 2.1 +// 2 is the TQt 2.0.x format +// 1 is the TQt 1.x format + +/*! + Constructs a data stream that has no IO device. + + \sa setDevice() +*/ + +TQDataStream::TQDataStream() +{ + if ( systemWordSize == 0 ) // get system features + tqSysInfo( &systemWordSize, &systemBigEndian ); + dev = 0; // no device set + owndev = FALSE; + byteorder = BigEndian; // default byte order + printable = FALSE; + ver = DefaultStreamVersion; + noswap = systemBigEndian; +} + +/*! + Constructs a data stream that uses the IO device \a d. + + \warning If you use TQSocket or TQSocketDevice as the IO device \a d + for reading data, you must make sure that enough data is available + on the socket for the operation to successfully proceed; + TQDataStream does not have any means to handle or recover from + short-reads. + + \sa setDevice(), device() +*/ + +TQDataStream::TQDataStream( TQIODevice *d ) +{ + if ( systemWordSize == 0 ) // get system features + tqSysInfo( &systemWordSize, &systemBigEndian ); + dev = d; // set device + owndev = FALSE; + byteorder = BigEndian; // default byte order + printable = FALSE; + ver = DefaultStreamVersion; + noswap = systemBigEndian; +} + +/*! + Constructs a data stream that operates on a byte array, \a a, + through an internal TQBuffer device. The \a mode is a + TQIODevice::mode(), usually either \c IO_ReadOnly or \c + IO_WriteOnly. + + Example: + \code + static char bindata[] = { 231, 1, 44, ... }; + TQByteArray a; + a.setRawData( bindata, sizeof(bindata) ); // a points to bindata + TQDataStream stream( a, IO_ReadOnly ); // open on a's data + stream >> [something]; // read raw bindata + a.resetRawData( bindata, sizeof(bindata) ); // finished + \endcode + + The TQByteArray::setRawData() function is not for the inexperienced. +*/ + +TQDataStream::TQDataStream( TQByteArray a, int mode ) +{ + if ( systemWordSize == 0 ) // get system features + tqSysInfo( &systemWordSize, &systemBigEndian ); + dev = new TQBuffer( a ); // create device + ((TQBuffer *)dev)->open( mode ); // open device + owndev = TRUE; + byteorder = BigEndian; // default byte order + printable = FALSE; + ver = DefaultStreamVersion; + noswap = systemBigEndian; +} + +/*! + Destroys the data stream. + + The destructor will not affect the current IO device, unless it is + an internal IO device processing a TQByteArray passed in the \e + constructor, in which case the internal IO device is destroyed. +*/ + +TQDataStream::~TQDataStream() +{ + if ( owndev ) + delete dev; +} + + +/*! + \fn TQIODevice *TQDataStream::device() const + + Returns the IO device currently set. + + \sa setDevice(), unsetDevice() +*/ + +/*! + void TQDataStream::setDevice(TQIODevice *d ) + + Sets the IO device to \a d. + + \sa device(), unsetDevice() +*/ + +void TQDataStream::setDevice(TQIODevice *d ) +{ + if ( owndev ) { + delete dev; + owndev = FALSE; + } + dev = d; +} + +/*! + Unsets the IO device. This is the same as calling setDevice( 0 ). + + \sa device(), setDevice() +*/ + +void TQDataStream::unsetDevice() +{ + setDevice( 0 ); +} + + +/*! + \fn bool TQDataStream::atEnd() const + + Returns TRUE if the IO device has reached the end position (end of + the stream or file) or if there is no IO device set; otherwise + returns FALSE, i.e. if the current position of the IO device is + before the end position. + + \sa TQIODevice::atEnd() +*/ + +/*!\fn bool TQDataStream::eof() const + + \obsolete + + Returns TRUE if the IO device has reached the end position (end of + stream or file) or if there is no IO device set. + + Returns FALSE if the current position of the read/write head of the IO + device is somewhere before the end position. + + \sa TQIODevice::atEnd() +*/ + +/*! + \fn int TQDataStream::byteOrder() const + + Returns the current byte order setting -- either \c BigEndian or + \c LittleEndian. + + \sa setByteOrder() +*/ + +/*! + Sets the serialization byte order to \a bo. + + The \a bo parameter can be \c TQDataStream::BigEndian or \c + TQDataStream::LittleEndian. + + The default setting is big endian. We recommend leaving this + setting unless you have special requirements. + + \sa byteOrder() +*/ + +void TQDataStream::setByteOrder( int bo ) +{ + byteorder = bo; + if ( systemBigEndian ) + noswap = byteorder == BigEndian; + else + noswap = byteorder == LittleEndian; +} + + +/*! + \fn bool TQDataStream::isPrintableData() const + + Returns TRUE if the printable data flag has been set; otherwise + returns FALSE. + + \sa setPrintableData() +*/ + +/*! + \fn void TQDataStream::setPrintableData( bool enable ) + + If \a enable is TRUE, data will be output in a human readable + format. If \a enable is FALSE, data will be output in a binary + format. + + If \a enable is TRUE, the write functions will generate output + that consists of printable characters (7 bit ASCII). This output + will typically be a lot larger than the default binary output, and + consequently slower to write. + + We recommend only enabling printable data for debugging purposes. +*/ + + +/*! + \fn int TQDataStream::version() const + + Returns the version number of the data serialization format. In TQt + 3.1, this number is 5. + + \sa setVersion() +*/ + +/*! + \fn void TQDataStream::setVersion( int v ) + + Sets the version number of the data serialization format to \a v. + + You don't need to set a version if you are using the current + version of TQt. + + In order to accommodate new functionality, the datastream + serialization format of some TQt classes has changed in some + versions of TQt. If you want to read data that was created by an + earlier version of TQt, or write data that can be read by a program + that was compiled with an earlier version of TQt, use this function + to modify the serialization format of TQDataStream. + + \table + \header \i TQt Version \i TQDataStream Version + \row \i TQt 3.3 \i11 6 + \row \i TQt 3.2 \i11 5 + \row \i TQt 3.1 \i11 5 + \row \i TQt 3.0 \i11 4 + \row \i TQt 2.1.x and TQt 2.2.x \i11 3 + \row \i TQt 2.0.x \i11 2 + \row \i TQt 1.x \i11 1 + \endtable + + \sa version() +*/ + +/***************************************************************************** + TQDataStream read functions + *****************************************************************************/ + +#if defined(Q_OS_HPUX) && !defined(__LP64__) +extern "C" long long __strtoll( const char *, char**, int ); +#endif + +static TQ_INT64 read_int_ascii( TQDataStream *s ) +{ + int n = 0; + char buf[40]; + for ( ;; ) { + buf[n] = s->device()->getch(); + if ( buf[n] == '\n' || n > 38 ) // $-terminator + break; + n++; + } + buf[n] = '\0'; + +#if defined(__LP64__) || defined(Q_OS_OSF) + // sizeof(long) == 8 + return strtol(buf, (char **)0, 10); +#else +# if defined(Q_OS_TEMP) + return strtol( buf, (char**)0, 10 ); +# elif defined(Q_OS_WIN) + return _atoi64( buf ); +# elif defined(Q_OS_HPUX) + return __strtoll( buf, (char**)0, 10 ); +# elif defined(Q_OS_MACX) && defined(QT_MACOSX_VERSION) && QT_MACOSX_VERSION < 0x1020 + return strtoq( buf, (char**)0, 10 ); +# else + return strtoll( buf, (char**)0, 10 ); // C99 function +# endif +#endif +} + +/*! + \overload TQDataStream &TQDataStream::operator>>( TQ_UINT8 &i ) + + Reads an unsigned byte from the stream into \a i, and returns a + reference to the stream. +*/ + +/*! + Reads a signed byte from the stream into \a i, and returns a + reference to the stream. +*/ + +TQDataStream &TQDataStream::operator>>( TQ_INT8 &i ) +{ + CHECK_STREAM_PRECOND + if ( printable ) { // printable data + i = (TQ_INT8)dev->getch(); + if ( i == '\\' ) { // read octal code + char buf[4]; + dev->readBlock( buf, 3 ); + i = (buf[2] & 0x07)+((buf[1] & 0x07) << 3)+((buf[0] & 0x07) << 6); + } + } else { // data or text + int ret = dev->getch(); + if (ret >= 0) { + i = (TQ_INT8)ret; + } + } + return *this; +} + + +/*! + \overload TQDataStream &TQDataStream::operator>>( TQ_UINT16 &i ) + + Reads an unsigned 16-bit integer from the stream into \a i, and + returns a reference to the stream. +*/ + +/*! + \overload + + Reads a signed 16-bit integer from the stream into \a i, and + returns a reference to the stream. +*/ + +TQDataStream &TQDataStream::operator>>( TQ_INT16 &i ) +{ + CHECK_STREAM_PRECOND + if ( printable ) { // printable data + i = (TQ_INT16)read_int_ascii( this ); + } else if ( noswap ) { // no conversion needed + dev->readBlock( (char *)&i, sizeof(TQ_INT16) ); + } else { // swap bytes + uchar *p = (uchar *)(&i); + char b[2]; + if (dev->readBlock( b, 2 ) >= 2) { + *p++ = b[1]; + *p = b[0]; + } + } + return *this; +} + + +/*! + \overload TQDataStream &TQDataStream::operator>>( TQ_UINT32 &i ) + + Reads an unsigned 32-bit integer from the stream into \a i, and + returns a reference to the stream. +*/ + +/*! + \overload + + Reads a signed 32-bit integer from the stream into \a i, and + returns a reference to the stream. +*/ + +TQDataStream &TQDataStream::operator>>( TQ_INT32 &i ) +{ + CHECK_STREAM_PRECOND + if ( printable ) { // printable data + i = (TQ_INT32)read_int_ascii( this ); + } else if ( noswap ) { // no conversion needed + dev->readBlock( (char *)&i, sizeof(TQ_INT32) ); + } else { // swap bytes + uchar *p = (uchar *)(&i); + char b[4]; + if (dev->readBlock( b, 4 ) >= 4) { + *p++ = b[3]; + *p++ = b[2]; + *p++ = b[1]; + *p = b[0]; + } + } + return *this; +} + +/*! + \overload TQDataStream &TQDataStream::operator>>( TQ_UINT64 &i ) + + Reads an unsigned 64-bit integer from the stream, into \a i, and + returns a reference to the stream. +*/ + +/*! + \overload + + Reads a signed 64-bit integer from the stream into \a i, and + returns a reference to the stream. +*/ + +TQDataStream &TQDataStream::operator>>( TQ_INT64 &i ) +{ + CHECK_STREAM_PRECOND + if ( printable ) { // printable data + i = read_int_ascii( this ); + } else if ( version() < 6 ) { + TQ_UINT32 i1, i2; + *this >> i2 >> i1; + i = ((TQ_UINT64)i1 << 32) + i2; + } else if ( noswap ) { // no conversion needed + dev->readBlock( (char *)&i, sizeof(TQ_INT64) ); + } else { // swap bytes + uchar *p = (uchar *)(&i); + char b[8]; + if (dev->readBlock( b, 8 ) >= 8) { + *p++ = b[7]; + *p++ = b[6]; + *p++ = b[5]; + *p++ = b[4]; + *p++ = b[3]; + *p++ = b[2]; + *p++ = b[1]; + *p = b[0]; + } + } + return *this; +} + + +/*! + \overload TQDataStream &TQDataStream::operator>>( TQ_ULONG &i ) + + Reads an unsigned integer of the system's word length from the + stream, into \a i, and returns a reference to the stream. +*/ + +#if !defined(Q_OS_WIN64) +/*! + \overload + + Reads a signed integer of the system's word length from the stream + into \a i, and returns a reference to the stream. + +*/ + +TQDataStream &TQDataStream::operator>>( TQ_LONG &i ) +{ + CHECK_STREAM_PRECOND + if ( printable ) { // printable data + i = (TQ_LONG)read_int_ascii( this ); + } else if ( noswap ) { // no conversion needed + dev->readBlock( (char *)&i, sizeof(TQ_LONG) ); + } else { // swap bytes + uchar *p = (uchar *)(&i); + char b[sizeof(TQ_LONG)]; + if (dev->readBlock( b, sizeof(TQ_LONG) ) >= (int)sizeof(TQ_LONG)) { + for ( int j = sizeof(TQ_LONG); j; ) { + *p++ = b[--j]; + } + } + } + return *this; +} +#endif + +static double read_double_ascii( TQDataStream *s ) +{ + int n = 0; + char buf[80]; + for ( ;; ) { + buf[n] = s->device()->getch(); + if ( buf[n] == '\n' || n > 78 ) // $-terminator + break; + n++; + } + buf[n] = '\0'; + return atof( buf ); +} + + +/*! + \overload + + Reads a 32-bit floating point number from the stream into \a f, + using the standard IEEE754 format. Returns a reference to the + stream. +*/ + +TQDataStream &TQDataStream::operator>>( float &f ) +{ + CHECK_STREAM_PRECOND + if ( printable ) { // printable data + f = (float)read_double_ascii( this ); + } else if ( noswap ) { // no conversion needed + dev->readBlock( (char *)&f, sizeof(float) ); + } else { // swap bytes + uchar *p = (uchar *)(&f); + char b[4]; + if (dev->readBlock( b, 4 ) >= 4) { + *p++ = b[3]; + *p++ = b[2]; + *p++ = b[1]; + *p = b[0]; + } + } + return *this; +} + + +/*! + \overload + + Reads a 64-bit floating point number from the stream into \a f, + using the standard IEEE754 format. Returns a reference to the + stream. +*/ + +TQDataStream &TQDataStream::operator>>( double &f ) +{ + CHECK_STREAM_PRECOND + if ( printable ) { // printable data + f = read_double_ascii( this ); + } else if ( noswap ) { // no conversion needed + dev->readBlock( (char *)&f, sizeof(double) ); + } else { // swap bytes + uchar *p = (uchar *)(&f); + char b[8]; + if (dev->readBlock( b, 8 ) >= 8) { + *p++ = b[7]; + *p++ = b[6]; + *p++ = b[5]; + *p++ = b[4]; + *p++ = b[3]; + *p++ = b[2]; + *p++ = b[1]; + *p = b[0]; + } + } + return *this; +} + + +/*! + \overload + + Reads the '\0'-terminated string \a s from the stream and returns + a reference to the stream. + + Space for the string is allocated using \c new -- the caller must + destroy it with delete[]. +*/ + +TQDataStream &TQDataStream::operator>>( char *&s ) +{ + uint len = 0; + return readBytes( s, len ); +} + + +/*! + Reads the buffer \a s from the stream and returns a reference to + the stream. + + The buffer \a s is allocated using \c new. Destroy it with the \c + delete[] operator. If the length is zero or \a s cannot be + allocated, \a s is set to 0. + + The \a l parameter will be set to the length of the buffer. + + The serialization format is a TQ_UINT32 length specifier first, + then \a l bytes of data. Note that the data is \e not encoded. + + \sa readRawBytes(), writeBytes() +*/ + +TQDataStream &TQDataStream::readBytes( char *&s, uint &l ) +{ + CHECK_STREAM_PRECOND + TQ_UINT32 len; + *this >> len; // first read length spec + l = (uint)len; + if ( len == 0 || eof() ) { + s = 0; + return *this; + } else { + s = new char[len]; // create char array + TQ_CHECK_PTR( s ); + if ( !s ) // no memory + return *this; + return readRawBytes( s, (uint)len ); + } +} + + +/*! + Reads \a len bytes from the stream into \a s and returns a + reference to the stream. + + The buffer \a s must be preallocated. The data is \e not encoded. + + \sa readBytes(), TQIODevice::readBlock(), writeRawBytes() +*/ + +TQDataStream &TQDataStream::readRawBytes( char *s, uint len ) +{ + CHECK_STREAM_PRECOND + if ( printable ) { // printable data + TQ_INT8 *p = (TQ_INT8*)s; + if ( version() < 4 ) { + while ( len-- ) { + TQ_INT32 tmp; + *this >> tmp; + *p++ = tmp; + } + } else { + while ( len-- ) + *this >> *p++; + } + } else { // read data char array + dev->readBlock( s, len ); + } + return *this; +} + + +/***************************************************************************** + TQDataStream write functions + *****************************************************************************/ + + +/*! + \overload TQDataStream &TQDataStream::operator<<( TQ_UINT8 i ) + + Writes an unsigned byte, \a i, to the stream and returns a + reference to the stream. +*/ + +/*! + Writes a signed byte, \a i, to the stream and returns a reference + to the stream. +*/ + +TQDataStream &TQDataStream::operator<<( TQ_INT8 i ) +{ + CHECK_STREAM_PRECOND + if ( printable && (i == '\\' || !isprint((uchar) i)) ) { + char buf[6]; // write octal code + buf[0] = '\\'; + buf[1] = '0' + ((i >> 6) & 0x07); + buf[2] = '0' + ((i >> 3) & 0x07); + buf[3] = '0' + (i & 0x07); + buf[4] = '\0'; + dev->writeBlock( buf, 4 ); + } else { + dev->putch( i ); + } + return *this; +} + + +/*! + \overload TQDataStream &TQDataStream::operator<<( TQ_UINT16 i ) + + Writes an unsigned 16-bit integer, \a i, to the stream and returns + a reference to the stream. +*/ + +/*! + \overload + + Writes a signed 16-bit integer, \a i, to the stream and returns a + reference to the stream. +*/ + +TQDataStream &TQDataStream::operator<<( TQ_INT16 i ) +{ + CHECK_STREAM_PRECOND + if ( printable ) { // printable data + char buf[16]; + sprintf( buf, "%d\n", i ); + dev->writeBlock( buf, strlen(buf) ); + } else if ( noswap ) { // no conversion needed + dev->writeBlock( (char *)&i, sizeof(TQ_INT16) ); + } else { // swap bytes + uchar *p = (uchar *)(&i); + char b[2]; + b[1] = *p++; + b[0] = *p; + dev->writeBlock( b, 2 ); + } + return *this; +} + +/*! + \overload + + Writes a signed 32-bit integer, \a i, to the stream and returns a + reference to the stream. +*/ + +TQDataStream &TQDataStream::operator<<( TQ_INT32 i ) +{ + CHECK_STREAM_PRECOND + if ( printable ) { // printable data + char buf[16]; + sprintf( buf, "%d\n", i ); + dev->writeBlock( buf, strlen(buf) ); + } else if ( noswap ) { // no conversion needed + dev->writeBlock( (char *)&i, sizeof(TQ_INT32) ); + } else { // swap bytes + uchar *p = (uchar *)(&i); + char b[4]; + b[3] = *p++; + b[2] = *p++; + b[1] = *p++; + b[0] = *p; + dev->writeBlock( b, 4 ); + } + return *this; +} + +/*! + \overload TQDataStream &TQDataStream::operator<<( TQ_UINT64 i ) + + Writes an unsigned 64-bit integer, \a i, to the stream and returns a + reference to the stream. +*/ + +/*! + \overload + + Writes a signed 64-bit integer, \a i, to the stream and returns a + reference to the stream. +*/ + +TQDataStream &TQDataStream::operator<<( TQ_INT64 i ) +{ + CHECK_STREAM_PRECOND + if ( printable ) { // printable data + char buf[16]; +#ifdef Q_OS_WIN + sprintf( buf, "%I64d\n", i ); +#else + sprintf( buf, "%lld\n", i ); +#endif + dev->writeBlock( buf, strlen(buf) ); + } else if ( version() < 6 ) { + TQ_UINT32 i1 = i & 0xffffffff; + TQ_UINT32 i2 = i >> 32; + *this << i2 << i1; + } else if ( noswap ) { // no conversion needed + dev->writeBlock( (char *)&i, sizeof(TQ_INT64) ); + } else { // swap bytes + uchar *p = (uchar *)(&i); + char b[8]; + b[7] = *p++; + b[6] = *p++; + b[5] = *p++; + b[4] = *p++; + b[3] = *p++; + b[2] = *p++; + b[1] = *p++; + b[0] = *p; + dev->writeBlock( b, 8 ); + } + return *this; +} + +/*! + \overload TQDataStream &TQDataStream::operator<<( TQ_ULONG i ) + + Writes an unsigned integer \a i, of the system's word length, to + the stream and returns a reference to the stream. +*/ + +#if !defined(Q_OS_WIN64) +/*! + \overload + + Writes a signed integer \a i, of the system's word length, to the + stream and returns a reference to the stream. +*/ + +TQDataStream &TQDataStream::operator<<( TQ_LONG i ) +{ + CHECK_STREAM_PRECOND + if ( printable ) { // printable data + char buf[20]; + sprintf( buf, "%ld\n", i ); + dev->writeBlock( buf, strlen(buf) ); + } else if ( noswap ) { // no conversion needed + dev->writeBlock( (char *)&i, sizeof(TQ_LONG) ); + } else { // swap bytes + uchar *p = (uchar *)(&i); + char b[sizeof(TQ_LONG)]; + for ( int j = sizeof(TQ_LONG); j; ) + b[--j] = *p++; + dev->writeBlock( b, sizeof(TQ_LONG) ); + } + return *this; +} +#endif + + +/*! + \overload TQDataStream &TQDataStream::operator<<( TQ_UINT32 i ) + + Writes an unsigned integer, \a i, to the stream as a 32-bit + unsigned integer (TQ_UINT32). Returns a reference to the stream. +*/ + +/*! + \overload + + Writes a 32-bit floating point number, \a f, to the stream using + the standard IEEE754 format. Returns a reference to the stream. +*/ + +TQDataStream &TQDataStream::operator<<( float f ) +{ + CHECK_STREAM_PRECOND + if ( printable ) { // printable data + TQString num = TQString::number((double)f); + dev->writeBlock(num.latin1(), num.length()); + dev->putch('\n'); + } else { + float g = f; // fixes float-on-stack problem + if ( noswap ) { // no conversion needed + dev->writeBlock( (char *)&g, sizeof(float) ); + } else { // swap bytes + uchar *p = (uchar *)(&g); + char b[4]; + b[3] = *p++; + b[2] = *p++; + b[1] = *p++; + b[0] = *p; + dev->writeBlock( b, 4 ); + } + } + return *this; +} + + +/*! + \overload + + Writes a 64-bit floating point number, \a f, to the stream using + the standard IEEE754 format. Returns a reference to the stream. +*/ + +TQDataStream &TQDataStream::operator<<( double f ) +{ + CHECK_STREAM_PRECOND + if ( printable ) { // printable data + TQString num = TQString::number((double)f); + dev->writeBlock(num.latin1(), num.length()); + dev->putch('\n'); + } else if ( noswap ) { // no conversion needed + dev->writeBlock( (char *)&f, sizeof(double) ); + } else { // swap bytes + uchar *p = (uchar *)(&f); + char b[8]; + b[7] = *p++; + b[6] = *p++; + b[5] = *p++; + b[4] = *p++; + b[3] = *p++; + b[2] = *p++; + b[1] = *p++; + b[0] = *p; + dev->writeBlock( b, 8 ); + } + return *this; +} + + +/*! + \overload + + Writes the '\0'-terminated string \a s to the stream and returns a + reference to the stream. + + The string is serialized using writeBytes(). +*/ + +TQDataStream &TQDataStream::operator<<( const char *s ) +{ + if ( !s ) { + *this << (TQ_UINT32)0; + return *this; + } + uint len = tqstrlen( s ) + 1; // also write null terminator + *this << (TQ_UINT32)len; // write length specifier + return writeRawBytes( s, len ); +} + + +/*! + Writes the length specifier \a len and the buffer \a s to the + stream and returns a reference to the stream. + + The \a len is serialized as a TQ_UINT32, followed by \a len bytes + from \a s. Note that the data is \e not encoded. + + \sa writeRawBytes(), readBytes() +*/ + +TQDataStream &TQDataStream::writeBytes(const char *s, uint len) +{ + CHECK_STREAM_PRECOND + *this << (TQ_UINT32)len; // write length specifier + if ( len ) + writeRawBytes( s, len ); + return *this; +} + + +/*! + Writes \a len bytes from \a s to the stream and returns a + reference to the stream. The data is \e not encoded. + + \sa writeBytes(), TQIODevice::writeBlock(), readRawBytes() +*/ + +TQDataStream &TQDataStream::writeRawBytes( const char *s, uint len ) +{ + CHECK_STREAM_PRECOND + if ( printable ) { // write printable + if ( version() < 4 ) { + char *p = (char *)s; + while ( len-- ) + *this << *p++; + } else { + TQ_INT8 *p = (TQ_INT8*)s; + while ( len-- ) + *this << *p++; + } + } else { // write data char array + dev->writeBlock( s, len ); + } + return *this; +} + +#endif // TQT_NO_DATASTREAM diff --git a/src/tools/tqdatastream.h b/src/tools/tqdatastream.h new file mode 100644 index 000000000..5111a2fb9 --- /dev/null +++ b/src/tools/tqdatastream.h @@ -0,0 +1,193 @@ +/**************************************************************************** +** +** Definition of TQDataStream class +** +** Created : 930831 +** +** Copyright (C) 1992-2008 Trolltech ASA. All rights reserved. +** +** This file is part of the tools module of the TQt GUI Toolkit. +** +** This file may be used under the terms of the GNU General +** Public License versions 2.0 or 3.0 as published by the Free +** Software Foundation and appearing in the files LICENSE.GPL2 +** and LICENSE.GPL3 included in the packaging of this file. +** Alternatively you may (at your option) use any later version +** of the GNU General Public License if such license has been +** publicly approved by Trolltech ASA (or its successors, if any) +** and the KDE Free TQt Foundation. +** +** Please review the following information to ensure GNU General +** Public Licensing requirements will be met: +** http://trolltech.com/products/qt/licenses/licensing/opensource/. +** If you are unsure which license is appropriate for your use, please +** review the following information: +** http://trolltech.com/products/qt/licenses/licensing/licensingoverview +** or contact the sales department at sales@trolltech.com. +** +** This file may be used under the terms of the Q Public License as +** defined by Trolltech ASA and appearing in the file LICENSE.TQPL +** included in the packaging of this file. Licensees holding valid TQt +** Commercial licenses may use this file in accordance with the TQt +** Commercial License Agreement provided with the Software. +** +** This file is provided "AS IS" with NO WARRANTY OF ANY KIND, +** INCLUDING THE WARRANTIES OF DESIGN, MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE. Trolltech reserves all rights not granted +** herein. +** +**********************************************************************/ + +#ifndef TQDATASTREAM_H +#define TQDATASTREAM_H + +#ifndef QT_H +#include "tqiodevice.h" +#include "tqstring.h" +#endif // QT_H + +#ifndef TQT_NO_DATASTREAM +class TQ_EXPORT TQDataStream // data stream class +{ +public: + TQDataStream(); + TQDataStream( TQIODevice * ); + TQDataStream( TQByteArray, int mode ); + virtual ~TQDataStream(); + + TQIODevice *device() const; + void setDevice( TQIODevice * ); + void unsetDevice(); + + bool atEnd() const; + bool eof() const; + + enum ByteOrder { BigEndian, LittleEndian }; + int byteOrder() const; + void setByteOrder( int ); + + bool isPrintableData() const; + void setPrintableData( bool ); + + int version() const; + void setVersion( int ); + + TQDataStream &operator>>( TQ_INT8 &i ); + TQDataStream &operator>>( TQ_UINT8 &i ); + TQDataStream &operator>>( TQ_INT16 &i ); + TQDataStream &operator>>( TQ_UINT16 &i ); + TQDataStream &operator>>( TQ_INT32 &i ); + TQDataStream &operator>>( TQ_UINT32 &i ); + TQDataStream &operator>>( TQ_INT64 &i ); + TQDataStream &operator>>( TQ_UINT64 &i ); +#if !defined(Q_OS_WIN64) + TQDataStream &operator>>( TQ_LONG &i ); + TQDataStream &operator>>( TQ_ULONG &i ); +#endif + + TQDataStream &operator>>( float &f ); + TQDataStream &operator>>( double &f ); + TQDataStream &operator>>( char *&str ); + + TQDataStream &operator<<( TQ_INT8 i ); + TQDataStream &operator<<( TQ_UINT8 i ); + TQDataStream &operator<<( TQ_INT16 i ); + TQDataStream &operator<<( TQ_UINT16 i ); + TQDataStream &operator<<( TQ_INT32 i ); + TQDataStream &operator<<( TQ_UINT32 i ); + TQDataStream &operator<<( TQ_INT64 i ); + TQDataStream &operator<<( TQ_UINT64 i ); +#if !defined(Q_OS_WIN64) + TQDataStream &operator<<( TQ_LONG i ); + TQDataStream &operator<<( TQ_ULONG i ); +#endif + TQDataStream &operator<<( float f ); + TQDataStream &operator<<( double f ); + TQDataStream &operator<<( const char *str ); + + TQDataStream &readBytes( char *&, uint &len ); + TQDataStream &readRawBytes( char *, uint len ); + + TQDataStream &writeBytes( const char *, uint len ); + TQDataStream &writeRawBytes( const char *, uint len ); + +private: + TQIODevice *dev; + bool owndev; + int byteorder; + bool printable; + bool noswap; + int ver; + +private: // Disabled copy constructor and operator= +#if defined(TQ_DISABLE_COPY) + TQDataStream( const TQDataStream & ); + TQDataStream &operator=( const TQDataStream & ); +#endif +}; + + +/***************************************************************************** + TQDataStream inline functions + *****************************************************************************/ + +inline TQIODevice *TQDataStream::device() const +{ return dev; } + +inline bool TQDataStream::atEnd() const +{ return dev ? dev->atEnd() : TRUE; } + +inline bool TQDataStream::eof() const +{ return atEnd(); } + +inline int TQDataStream::byteOrder() const +{ return byteorder; } + +inline bool TQDataStream::isPrintableData() const +{ return printable; } + +inline void TQDataStream::setPrintableData( bool p ) +{ printable = p; } + +inline int TQDataStream::version() const +{ return ver; } + +inline void TQDataStream::setVersion( int v ) +{ ver = v; } + +inline TQDataStream &TQDataStream::operator>>( TQ_UINT8 &i ) +{ return *this >> (TQ_INT8&)i; } + +inline TQDataStream &TQDataStream::operator>>( TQ_UINT16 &i ) +{ return *this >> (TQ_INT16&)i; } + +inline TQDataStream &TQDataStream::operator>>( TQ_UINT32 &i ) +{ return *this >> (TQ_INT32&)i; } + +inline TQDataStream &TQDataStream::operator>>( TQ_UINT64 &i ) +{ return *this >> (TQ_INT64&)i; } + +#if !defined(Q_OS_WIN64) +inline TQDataStream &TQDataStream::operator>>( TQ_ULONG &i ) +{ return *this >> (TQ_LONG&)i; } +#endif + +inline TQDataStream &TQDataStream::operator<<( TQ_UINT8 i ) +{ return *this << (TQ_INT8)i; } + +inline TQDataStream &TQDataStream::operator<<( TQ_UINT16 i ) +{ return *this << (TQ_INT16)i; } + +inline TQDataStream &TQDataStream::operator<<( TQ_UINT32 i ) +{ return *this << (TQ_INT32)i; } + +inline TQDataStream &TQDataStream::operator<<( TQ_UINT64 i ) +{ return *this << (TQ_INT64)i; } + +#if !defined(Q_OS_WIN64) +inline TQDataStream &TQDataStream::operator<<( TQ_ULONG i ) +{ return *this << (TQ_LONG)i; } +#endif + +#endif // TQT_NO_DATASTREAM +#endif // TQDATASTREAM_H diff --git a/src/tools/tqdatetime.cpp b/src/tools/tqdatetime.cpp index 5253fa50e..49ae68bb4 100644 --- a/src/tools/tqdatetime.cpp +++ b/src/tools/tqdatetime.cpp @@ -41,7 +41,7 @@ #include "qplatformdefs.h" #include "tqdatetime.h" -#include "ntqdatastream.h" +#include "tqdatastream.h" #include "tqregexp.h" #include diff --git a/src/tools/tqdir.cpp b/src/tools/tqdir.cpp new file mode 100644 index 000000000..21bea6afd --- /dev/null +++ b/src/tools/tqdir.cpp @@ -0,0 +1,1390 @@ +/**************************************************************************** +** +** Implementation of TQDir class +** +** Created : 950427 +** +** Copyright (C) 1992-2008 Trolltech ASA. All rights reserved. +** +** This file is part of the tools module of the TQt GUI Toolkit. +** +** This file may be used under the terms of the GNU General +** Public License versions 2.0 or 3.0 as published by the Free +** Software Foundation and appearing in the files LICENSE.GPL2 +** and LICENSE.GPL3 included in the packaging of this file. +** Alternatively you may (at your option) use any later version +** of the GNU General Public License if such license has been +** publicly approved by Trolltech ASA (or its successors, if any) +** and the KDE Free TQt Foundation. +** +** Please review the following information to ensure GNU General +** Public Licensing requirements will be met: +** http://trolltech.com/products/qt/licenses/licensing/opensource/. +** If you are unsure which license is appropriate for your use, please +** review the following information: +** http://trolltech.com/products/qt/licenses/licensing/licensingoverview +** or contact the sales department at sales@trolltech.com. +** +** This file may be used under the terms of the Q Public License as +** defined by Trolltech ASA and appearing in the file LICENSE.TQPL +** included in the packaging of this file. Licensees holding valid TQt +** Commercial licenses may use this file in accordance with the TQt +** Commercial License Agreement provided with the Software. +** +** This file is provided "AS IS" with NO WARRANTY OF ANY KIND, +** INCLUDING THE WARRANTIES OF DESIGN, MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE. Trolltech reserves all rights not granted +** herein. +** +**********************************************************************/ + +#include "qplatformdefs.h" +#include "tqdir.h" + +#ifndef TQT_NO_DIR +#include +#include "tqfileinfo.h" +#include "tqregexp.h" +#include "tqstringlist.h" +#include "tqdeepcopy.h" +#include + +#if defined(Q_FS_FAT) && !defined(Q_OS_UNIX) +const bool CaseSensitiveFS = FALSE; +#else +const bool CaseSensitiveFS = TRUE; +#endif + + +/*! + \class TQDir + \reentrant + \brief The TQDir class provides access to directory structures and their contents in a platform-independent way. + + \ingroup io + \mainclass + + A TQDir is used to manipulate path names, access information + regarding paths and files, and manipulate the underlying file + system. + + A TQDir can point to a file using either a relative or an absolute + path. Absolute paths begin with the directory separator "/" + (optionally preceded by a drive specification under Windows). If + you always use "/" as a directory separator, TQt will translate + your paths to conform to the underlying operating system. Relative + file names begin with a directory name or a file name and specify + a path relative to the current directory. + + The "current" path refers to the application's working directory. + A TQDir's own path is set and retrieved with setPath() and path(). + + An example of an absolute path is the string "/tmp/quartz", a + relative path might look like "src/fatlib". You can use the + function isRelative() to check if a TQDir is using a relative or an + absolute file path. Call convertToAbs() to convert a relative TQDir + to an absolute one. For a simplified path use cleanDirPath(). To + obtain a path which has no symbolic links or redundant ".." + elements use canonicalPath(). The path can be set with setPath(), + and changed with cd() and cdUp(). + + TQDir provides several static functions, for example, setCurrent() + to set the application's working directory and currentDirPath() to + retrieve the application's working directory. Access to some + common paths is provided with the static functions, current(), + home() and root() which return TQDir objects or currentDirPath(), + homeDirPath() and rootDirPath() which return the path as a string. + If you want to know about your application's path use + \l{TQApplication::applicationDirPath()}. + + The number of entries in a directory is returned by count(). + Obtain a string list of the names of all the files and directories + in a directory with entryList(). If you prefer a list of TQFileInfo + pointers use entryInfoList(). Both these functions can apply a + name filter, an attributes filter (e.g. read-only, files not + directories, etc.), and a sort order. The filters and sort may be + set with calls to setNameFilter(), setFilter() and setSorting(). + They may also be specified in the entryList() and + entryInfoList()'s arguments. + + Create a new directory with mkdir(), rename a directory with + rename() and remove an existing directory with rmdir(). Remove a + file with remove(). You can interrogate a directory with exists(), + isReadable() and isRoot(). + + To get a path with a filename use filePath(), and to get a + directory name use dirName(); neither of these functions checks + for the existence of the file or directory. + + The list of root directories is provided by drives(); on Unix + systems this returns a list containing one root directory, "/"; on + Windows the list will usually contain "C:/", and possibly "D:/", + etc. + + It is easiest to work with "/" separators in TQt code. If you need + to present a path to the user or need a path in a form suitable + for a function in the underlying operating system use + convertSeparators(). + + Examples: + + See if a directory exists. + \code + TQDir d( "example" ); // "./example" + if ( !d.exists() ) + tqWarning( "Cannot find the example directory" ); + \endcode + + Traversing directories and reading a file. + \code + TQDir d = TQDir::root(); // "/" + if ( !d.cd("tmp") ) { // "/tmp" + tqWarning( "Cannot find the \"/tmp\" directory" ); + } else { + TQFile f( d.filePath("ex1.txt") ); // "/tmp/ex1.txt" + if ( !f.open(IO_ReadWrite) ) + tqWarning( "Cannot create the file %s", f.name() ); + } + \endcode + + A program that lists all the files in the current directory + (excluding symbolic links), sorted by size, smallest first: + \code + #include + #include + + int main( int argc, char **argv ) + { + TQDir d; + d.setFilter( TQDir::Files | TQDir::Hidden | TQDir::NoSymLinks ); + d.setSorting( TQDir::Size | TQDir::Reversed ); + + const TQFileInfoList *list = d.entryInfoList(); + TQFileInfoListIterator it( *list ); + TQFileInfo *fi; + + printf( " Bytes Filename\n" ); + while ( (fi = it.current()) != 0 ) { + printf( "%10li %s\n", fi->size(), fi->fileName().latin1() ); + ++it; + } + return 0; + } + \endcode + + \sa TQApplication::applicationDirPath() +*/ + +/*! + Constructs a TQDir pointing to the current directory ("."). + + \sa currentDirPath() +*/ + +TQDir::TQDir() +{ + dPath = TQString::fromLatin1("."); + init(); +} + +/*! + Constructs a TQDir with path \a path, that filters its entries by + name using \a nameFilter and by attributes using \a filterSpec. It + also sorts the names using \a sortSpec. + + The default \a nameFilter is an empty string, which excludes + nothing; the default \a filterSpec is \c All, which also means + exclude nothing. The default \a sortSpec is \c Name|IgnoreCase, + i.e. sort by name case-insensitively. + + Example that lists all the files in "/tmp": + \code + TQDir d( "/tmp" ); + for ( int i = 0; i < d.count(); i++ ) + printf( "%s\n", d[i] ); + \endcode + + If \a path is "" or TQString::null, TQDir uses "." (the current + directory). If \a nameFilter is "" or TQString::null, TQDir uses the + name filter "*" (all files). + + Note that \a path need not exist. + + \sa exists(), setPath(), setNameFilter(), setFilter(), setSorting() +*/ + +TQDir::TQDir( const TQString &path, const TQString &nameFilter, + int sortSpec, int filterSpec ) +{ + init(); + dPath = cleanDirPath( path ); + if ( dPath.isEmpty() ) + dPath = TQString::fromLatin1("."); + nameFilt = nameFilter; + if ( nameFilt.isEmpty() ) + nameFilt = TQString::fromLatin1("*"); + filtS = (FilterSpec)filterSpec; + sortS = (SortSpec)sortSpec; +} + +/*! + Constructs a TQDir that is a copy of the directory \a d. + + \sa operator=() +*/ + +TQDir::TQDir( const TQDir &d ) +{ + dPath = d.dPath; + fList = 0; + fiList = 0; + nameFilt = d.nameFilt; + dirty = TRUE; + allDirs = d.allDirs; + filtS = d.filtS; + sortS = d.sortS; +} + +/*! + Refreshes the directory information. +*/ +void TQDir::refresh() const +{ + TQDir* that = (TQDir*) this; + that->dirty = TRUE; +} + +void TQDir::init() +{ + fList = 0; + fiList = 0; + nameFilt = TQString::fromLatin1("*"); + dirty = TRUE; + allDirs = FALSE; + filtS = All; + sortS = SortSpec(Name | IgnoreCase); +} + +/*! + Destroys the TQDir frees up its resources. +*/ + +TQDir::~TQDir() +{ + delete fList; + delete fiList; +} + + +/*! + Sets the path of the directory to \a path. The path is cleaned of + redundant ".", ".." and of multiple separators. No check is made + to ensure that a directory with this path exists. + + The path can be either absolute or relative. Absolute paths begin + with the directory separator "/" (optionally preceded by a drive + specification under Windows). Relative file names begin with a + directory name or a file name and specify a path relative to the + current directory. An example of an absolute path is the string + "/tmp/quartz", a relative path might look like "src/fatlib". + + \sa path(), absPath(), exists(), cleanDirPath(), dirName(), + absFilePath(), isRelative(), convertToAbs() +*/ + +void TQDir::setPath( const TQString &path ) +{ + dPath = cleanDirPath( path ); + if ( dPath.isEmpty() ) + dPath = TQString::fromLatin1("."); + dirty = TRUE; +} + +/*! + \fn TQString TQDir::path() const + + Returns the path, this may contain symbolic links, but never + contains redundant ".", ".." or multiple separators. + + The returned path can be either absolute or relative (see + setPath()). + + \sa setPath(), absPath(), exists(), cleanDirPath(), dirName(), + absFilePath(), convertSeparators() +*/ + +/*! + Returns the absolute path (a path that starts with "/" or with a + drive specification), which may contain symbolic links, but never + contains redundant ".", ".." or multiple separators. + + \sa setPath(), canonicalPath(), exists(), cleanDirPath(), + dirName(), absFilePath() +*/ + +TQString TQDir::absPath() const +{ + if ( TQDir::isRelativePath(dPath) ) { + TQString tmp = currentDirPath(); + if ( tmp.right(1) != TQString::fromLatin1("/") ) + tmp += '/'; + tmp += dPath; + return cleanDirPath( tmp ); + } else { + return cleanDirPath( dPath ); + } +} + +/*! + Returns the name of the directory; this is \e not the same as the + path, e.g. a directory with the name "mail", might have the path + "/var/spool/mail". If the directory has no name (e.g. it is the + root directory) TQString::null is returned. + + No check is made to ensure that a directory with this name + actually exists. + + \sa path(), absPath(), absFilePath(), exists(), TQString::isNull() +*/ + +TQString TQDir::dirName() const +{ + int pos = dPath.findRev( '/' ); + if ( pos == -1 ) + return dPath; + return dPath.right( dPath.length() - pos - 1 ); +} + +/*! + Returns the path name of a file in the directory. Does \e not + check if the file actually exists in the directory. If the TQDir is + relative the returned path name will also be relative. Redundant + multiple separators or "." and ".." directories in \a fileName + will not be removed (see cleanDirPath()). + + If \a acceptAbsPath is TRUE a \a fileName starting with a + separator "/" will be returned without change. If \a acceptAbsPath + is FALSE an absolute path will be prepended to the fileName and + the resultant string returned. + + \sa absFilePath(), isRelative(), canonicalPath() +*/ + +TQString TQDir::filePath( const TQString &fileName, + bool acceptAbsPath ) const +{ + if ( acceptAbsPath && !isRelativePath(fileName) ) + return TQString(fileName); + + TQString tmp = dPath; + if ( tmp.isEmpty() || (tmp[(int)tmp.length()-1] != '/' && !!fileName && + fileName[0] != '/') ) + tmp += '/'; + tmp += fileName; + return tmp; +} + +/*! + Returns the absolute path name of a file in the directory. Does \e + not check if the file actually exists in the directory. Redundant + multiple separators or "." and ".." directories in \a fileName + will not be removed (see cleanDirPath()). + + If \a acceptAbsPath is TRUE a \a fileName starting with a + separator "/" will be returned without change. If \a acceptAbsPath + is FALSE an absolute path will be prepended to the fileName and + the resultant string returned. + + \sa filePath() +*/ + +TQString TQDir::absFilePath( const TQString &fileName, + bool acceptAbsPath ) const +{ + if ( acceptAbsPath && !isRelativePath( fileName ) ) + return fileName; + + TQString tmp = absPath(); +#ifdef Q_OS_WIN32 + if ( fileName[0].isLetter() && fileName[1] == ':' ) { + int drv = fileName.upper()[0].latin1() - 'A' + 1; + if ( _getdrive() != drv ) { + QT_WA( { + TCHAR buf[PATH_MAX]; + ::_wgetdcwd( drv, buf, PATH_MAX ); + tmp.setUnicodeCodes( (ushort*)buf, (uint)::wcslen(buf) ); + }, { + char buf[PATH_MAX]; + ::_getdcwd( drv, buf, PATH_MAX ); + tmp = buf; + } ); + if ( !tmp.endsWith("\\") ) + tmp += "\\"; + tmp += fileName.right( fileName.length() - 2 ); + int x; + for ( x = 0; x < (int) tmp.length(); x++ ) { + if ( tmp[x] == '\\' ) + tmp[x] = '/'; + } + } + } else +#endif + { + if ( tmp.isEmpty() || (tmp[(int)tmp.length()-1] != '/' && !!fileName && + fileName[0] != '/') ) + tmp += '/'; + tmp += fileName; + } + return tmp; +} + + +/*! + Returns \a pathName with the '/' separators converted to + separators that are appropriate for the underlying operating + system. + + On Windows, convertSeparators("c:/winnt/system32") returns + "c:\winnt\system32". + + The returned string may be the same as the argument on some + operating systems, for example on Unix. +*/ + +TQString TQDir::convertSeparators( const TQString &pathName ) +{ + TQString n( pathName ); +#if defined(Q_FS_FAT) || defined(Q_OS_OS2EMX) + for ( int i=0; i<(int)n.length(); i++ ) { + if ( n[i] == '/' ) + n[i] = '\\'; + } +#elif defined(Q_OS_MAC9) + while(n.length() && n[0] == '/' ) n = n.right(n.length()-1); + for ( int i=0; i<(int)n.length(); i++ ) { + if ( n[i] == '/' ) + n[i] = ':'; + } + if(n.contains(':') && n.left(1) != ':') + n.prepend(':'); +#endif + return n; +} + + +/*! + Changes the TQDir's directory to \a dirName. + + If \a acceptAbsPath is TRUE a path starting with separator "/" + will cause the function to change to the absolute directory. If \a + acceptAbsPath is FALSE any number of separators at the beginning + of \a dirName will be removed and the function will descend into + \a dirName. + + Returns TRUE if the new directory exists and is readable; + otherwise returns FALSE. Note that the logical cd() operation is + not performed if the new directory does not exist. + + Calling cd( ".." ) is equivalent to calling cdUp(). + + \sa cdUp(), isReadable(), exists(), path() +*/ + +bool TQDir::cd( const TQString &dirName, bool acceptAbsPath ) +{ + if ( dirName.isEmpty() || dirName == TQString::fromLatin1(".") ) + return TRUE; + TQString old = dPath; + if ( acceptAbsPath && !isRelativePath(dirName) ) { + dPath = cleanDirPath( dirName ); + } else { + if ( isRoot() ) { + if ( dirName == ".." ) { + dPath = old; + return FALSE; + } + } else { + dPath += '/'; + } + + dPath += dirName; + if ( dirName.find('/') >= 0 + || old == TQString::fromLatin1(".") + || dirName == TQString::fromLatin1("..") ) { + dPath = cleanDirPath( dPath ); + + /* + If dPath starts with .., we convert it to absolute to + avoid infinite looping on + + TQDir dir( "." ); + while ( dir.cdUp() ) + ; + */ + if ( dPath[0] == TQChar('.') && dPath[1] == TQChar('.') && + (dPath.length() == 2 || dPath[2] == TQChar('/')) ) + convertToAbs(); + } + } + if ( !exists() ) { + dPath = old; // regret + return FALSE; + } + dirty = TRUE; + return TRUE; +} + +/*! + Changes directory by moving one directory up from the TQDir's + current directory. + + Returns TRUE if the new directory exists and is readable; + otherwise returns FALSE. Note that the logical cdUp() operation is + not performed if the new directory does not exist. + + \sa cd(), isReadable(), exists(), path() +*/ + +bool TQDir::cdUp() +{ + return cd( TQString::fromLatin1("..") ); +} + +/*! + \fn TQString TQDir::nameFilter() const + + Returns the string set by setNameFilter() +*/ + +/*! + Sets the name filter used by entryList() and entryInfoList() to \a + nameFilter. + + The \a nameFilter is a wildcard (globbing) filter that understands + "*" and "?" wildcards. (See \link tqregexp.html#wildcard-matching + TQRegExp wildcard matching\endlink.) You may specify several filter + entries all separated by a single space " " or by a semi-colon + ";". + + For example, if you want entryList() and entryInfoList() to list + all files ending with either ".cpp" or ".h", you would use either + dir.setNameFilter("*.cpp *.h") or dir.setNameFilter("*.cpp;*.h"). + + \sa nameFilter(), setFilter() +*/ + +void TQDir::setNameFilter( const TQString &nameFilter ) +{ + nameFilt = nameFilter; + if ( nameFilt.isEmpty() ) + nameFilt = TQString::fromLatin1("*"); + dirty = TRUE; +} + +/*! + \fn TQDir::FilterSpec TQDir::filter() const + + Returns the value set by setFilter() +*/ + +/*! + \enum TQDir::FilterSpec + + This enum describes the filtering options available to TQDir, e.g. + for entryList() and entryInfoList(). The filter value is specified + by OR-ing together values from the following list: + + \value Dirs List directories only. + \value Files List files only. + \value Drives List disk drives (ignored under Unix). + \value NoSymLinks Do not list symbolic links (ignored by operating + systems that don't support symbolic links). + \value All List directories, files, drives and symlinks (this does not list + broken symlinks unless you specify System). + \value TypeMask A mask for the the Dirs, Files, Drives and + NoSymLinks flags. + \value Readable List files for which the application has read access. + \value Writable List files for which the application has write access. + \value Executable List files for which the application has execute + access. Executables needs to be combined with Dirs or Files. + \value RWEMask A mask for the Readable, Writable and Executable flags. + \value Modified Only list files that have been modified (ignored + under Unix). + \value Hidden List hidden files (on Unix, files starting with a .). + \value System List system files (on Unix, FIFOs, sockets and + device files) + \value AccessMask A mask for the Readable, Writable, Executable + Modified, Hidden and System flags + \value DefaultFilter Internal flag. + + If you do not set any of \c Readable, \c Writable or \c + Executable, TQDir will set all three of them. This makes the + default easy to write and at the same time useful. + + Examples: \c Readable|Writable means list all files for which the + application has read access, write access or both. \c Dirs|Drives + means list drives, directories, all files that the application can + read, write or execute, and also symlinks to such + files/directories. +*/ + + +/*! + Sets the filter used by entryList() and entryInfoList() to \a + filterSpec. The filter is used to specify the kind of files that + should be returned by entryList() and entryInfoList(). See + \l{TQDir::FilterSpec}. + + \sa filter(), setNameFilter() +*/ + +void TQDir::setFilter( int filterSpec ) +{ + if ( filtS == (FilterSpec) filterSpec ) + return; + filtS = (FilterSpec) filterSpec; + dirty = TRUE; +} + +/*! + \fn TQDir::SortSpec TQDir::sorting() const + + Returns the value set by setSorting() + + \sa setSorting() SortSpec +*/ + +/*! + \enum TQDir::SortSpec + + This enum describes the sort options available to TQDir, e.g. for + entryList() and entryInfoList(). The sort value is specified by + OR-ing together values from the following list: + + \value Name Sort by name. + \value Time Sort by time (modification time). + \value Size Sort by file size. + \value Unsorted Do not sort. + \value SortByMask A mask for Name, Time and Size. + + \value DirsFirst Put the directories first, then the files. + \value Reversed Reverse the sort order. + \value IgnoreCase Sort case-insensitively. + \value LocaleAware Sort names using locale aware compares + \value DefaultSort Internal flag. + + You can only specify one of the first four. + + If you specify both \c DirsFirst and \c Reversed, directories are + still put first, but in reverse order; the files will be listed + after the directories, again in reverse order. +*/ + +// ### Unsorted+DirsFirst ? Unsorted+Reversed? + +/*! + Sets the sort order used by entryList() and entryInfoList(). + + The \a sortSpec is specified by OR-ing values from the enum + \l{TQDir::SortSpec}. + + \sa sorting() SortSpec +*/ + +void TQDir::setSorting( int sortSpec ) +{ + if ( sortS == (SortSpec) sortSpec ) + return; + sortS = (SortSpec) sortSpec; + dirty = TRUE; +} + +/*! + \fn bool TQDir::matchAllDirs() const + + Returns the value set by setMatchAllDirs() + + \sa setMatchAllDirs() +*/ + +/*! + If \a enable is TRUE then all directories are included (e.g. in + entryList()), and the nameFilter() is only applied to the files. + If \a enable is FALSE then the nameFilter() is applied to both + directories and files. + + \sa matchAllDirs() +*/ + +void TQDir::setMatchAllDirs( bool enable ) +{ + if ( (bool)allDirs == enable ) + return; + allDirs = enable; + dirty = TRUE; +} + + +/*! + Returns the total number of directories and files that were found. + + Equivalent to entryList().count(). + + \sa operator[](), entryList() +*/ + +uint TQDir::count() const +{ + return (uint)entryList().count(); +} + +/*! + Returns the file name at position \a index in the list of file + names. Equivalent to entryList().at(index). + + Returns a TQString::null if the \a index is out of range or if the + entryList() function failed. + + \sa count(), entryList() +*/ + +TQString TQDir::operator[]( int index ) const +{ + entryList(); + return fList && index >= 0 && index < (int)fList->count() ? + (*fList)[index] : TQString::null; +} + + +/*! + \obsolete + This function is included to easy porting from TQt 1.x to TQt 2.0, + it is the same as entryList(), but encodes the filenames as 8-bit + strings using TQFile::encodedName(). + + It is more efficient to use entryList(). +*/ +TQStrList TQDir::encodedEntryList( int filterSpec, int sortSpec ) const +{ + TQStrList r; + TQStringList l = entryList(filterSpec,sortSpec); + for ( TQStringList::Iterator it = l.begin(); it != l.end(); ++it ) { + r.append( TQFile::encodeName(*it) ); + } + return r; +} + +/*! + \obsolete + \overload + This function is included to easy porting from TQt 1.x to TQt 2.0, + it is the same as entryList(), but encodes the filenames as 8-bit + strings using TQFile::encodedName(). + + It is more efficient to use entryList(). +*/ +TQStrList TQDir::encodedEntryList( const TQString &nameFilter, + int filterSpec, + int sortSpec ) const +{ + TQStrList r; + TQStringList l = entryList(nameFilter,filterSpec,sortSpec); + for ( TQStringList::Iterator it = l.begin(); it != l.end(); ++it ) { + r.append( TQFile::encodeName(*it) ); + } + return r; +} + + + +/*! + \overload + + Returns a list of the names of all the files and directories in + the directory, ordered in accordance with setSorting() and + filtered in accordance with setFilter() and setNameFilter(). + + The filter and sorting specifications can be overridden using the + \a filterSpec and \a sortSpec arguments. + + Returns an empty list if the directory is unreadable or does not + exist. + + \sa entryInfoList(), setNameFilter(), setSorting(), setFilter() +*/ + +TQStringList TQDir::entryList( int filterSpec, int sortSpec ) const +{ + if ( !dirty && filterSpec == (int)DefaultFilter && + sortSpec == (int)DefaultSort ) + return *fList; + return entryList( nameFilt, filterSpec, sortSpec ); +} + +/*! + Returns a list of the names of all the files and directories in + the directory, ordered in accordance with setSorting() and + filtered in accordance with setFilter() and setNameFilter(). + + The filter and sorting specifications can be overridden using the + \a nameFilter, \a filterSpec and \a sortSpec arguments. + + Returns an empty list if the directory is unreadable or does not + exist. + + \sa entryInfoList(), setNameFilter(), setSorting(), setFilter() +*/ + +TQStringList TQDir::entryList( const TQString &nameFilter, + int filterSpec, int sortSpec ) const +{ + if ( filterSpec == (int)DefaultFilter ) + filterSpec = filtS; + if ( sortSpec == (int)DefaultSort ) + sortSpec = sortS; + TQDir *that = (TQDir*)this; // mutable function + if ( that->readDirEntries(nameFilter, filterSpec, sortSpec) ) { + if ( that->fList ) + return *that->fList; + } + return TQStringList(); +} + +/*! + \overload + + Returns a list of TQFileInfo objects for all the files and + directories in the directory, ordered in accordance with + setSorting() and filtered in accordance with setFilter() and + setNameFilter(). + + The filter and sorting specifications can be overridden using the + \a filterSpec and \a sortSpec arguments. + + Returns 0 if the directory is unreadable or does not exist. + + The returned pointer is a const pointer to a TQFileInfoList. The + list is owned by the TQDir object and will be reused on the next + call to entryInfoList() for the same TQDir instance. If you want to + keep the entries of the list after a subsequent call to this + function you must copy them. + + Note: TQFileInfoList is really a TQPtrList. + + \sa entryList(), setNameFilter(), setSorting(), setFilter() +*/ + +const TQFileInfoList *TQDir::entryInfoList( int filterSpec, int sortSpec ) const +{ + if ( !dirty && filterSpec == (int)DefaultFilter && + sortSpec == (int)DefaultSort ) + return fiList; + return entryInfoList( nameFilt, filterSpec, sortSpec ); +} + +/*! + Returns a list of TQFileInfo objects for all the files and + directories in the directory, ordered in accordance with + setSorting() and filtered in accordance with setFilter() and + setNameFilter(). + + The filter and sorting specifications can be overridden using the + \a nameFilter, \a filterSpec and \a sortSpec arguments. + + Returns 0 if the directory is unreadable or does not exist. + + The returned pointer is a const pointer to a TQFileInfoList. The + list is owned by the TQDir object and will be reused on the next + call to entryInfoList() for the same TQDir instance. If you want to + keep the entries of the list after a subsequent call to this + function you must copy them. + + Note: TQFileInfoList is really a TQPtrList. + + \sa entryList(), setNameFilter(), setSorting(), setFilter() +*/ + +const TQFileInfoList *TQDir::entryInfoList( const TQString &nameFilter, + int filterSpec, int sortSpec ) const +{ + if ( filterSpec == (int)DefaultFilter ) + filterSpec = filtS; + if ( sortSpec == (int)DefaultSort ) + sortSpec = sortS; + TQDir *that = (TQDir*)this; // mutable function + if ( that->readDirEntries(nameFilter, filterSpec, sortSpec) ) + return that->fiList; + else + return 0; +} + +/*! + \overload + + Returns TRUE if the \e directory exists; otherwise returns FALSE. + (If a file with the same name is found this function will return + FALSE). + + \sa TQFileInfo::exists(), TQFile::exists() +*/ + +bool TQDir::exists() const +{ + TQFileInfo fi( dPath ); + return fi.exists() && fi.isDir(); +} + +/*! + Returns TRUE if the directory path is relative to the current + directory and returns FALSE if the path is absolute (e.g. under + UNIX a path is relative if it does not start with a "/"). + + \sa convertToAbs() +*/ + +bool TQDir::isRelative() const +{ + return isRelativePath( dPath ); +} + +/*! + Converts the directory path to an absolute path. If it is already + absolute nothing is done. + + \sa isRelative() +*/ + +void TQDir::convertToAbs() +{ + dPath = absPath(); +} + +/*! + Makes a copy of TQDir \a d and assigns it to this TQDir. +*/ + +TQDir &TQDir::operator=( const TQDir &d ) +{ + dPath = d.dPath; + delete fList; + fList = 0; + delete fiList; + fiList = 0; + nameFilt = d.nameFilt; + dirty = TRUE; + allDirs = d.allDirs; + filtS = d.filtS; + sortS = d.sortS; + return *this; +} + +/*! + \overload + + Sets the directory path to be the given \a path. +*/ + +TQDir &TQDir::operator=( const TQString &path ) +{ + dPath = cleanDirPath( path ); + dirty = TRUE; + return *this; +} + + +/*! + \fn bool TQDir::operator!=( const TQDir &d ) const + + Returns TRUE if directory \a d and this directory have different + paths or different sort or filter settings; otherwise returns + FALSE. + + Example: + \code + // The current directory is "/usr/local" + TQDir d1( "/usr/local/bin" ); + TQDir d2( "bin" ); + if ( d1 != d2 ) + tqDebug( "They differ" ); + \endcode +*/ + +/*! + Returns TRUE if directory \a d and this directory have the same + path and their sort and filter settings are the same; otherwise + returns FALSE. + + Example: + \code + // The current directory is "/usr/local" + TQDir d1( "/usr/local/bin" ); + TQDir d2( "bin" ); + d2.convertToAbs(); + if ( d1 == d2 ) + tqDebug( "They're the same" ); + \endcode +*/ + +bool TQDir::operator==( const TQDir &d ) const +{ + return dPath == d.dPath && + nameFilt == d.nameFilt && + allDirs == d.allDirs && + filtS == d.filtS && + sortS == d.sortS; +} + + +/*! + Removes the file, \a fileName. + + If \a acceptAbsPath is TRUE a path starting with separator "/" + will remove the file with the absolute path. If \a acceptAbsPath + is FALSE any number of separators at the beginning of \a fileName + will be removed and the resultant file name will be removed. + + Returns TRUE if the file is removed successfully; otherwise + returns FALSE. +*/ + +bool TQDir::remove( const TQString &fileName, bool acceptAbsPath ) +{ + if ( fileName.isEmpty() ) { +#if defined(QT_CHECK_NULL) + tqWarning( "TQDir::remove: Empty or null file name" ); +#endif + return FALSE; + } + TQString p = filePath( fileName, acceptAbsPath ); + return TQFile::remove( p ); +} + +/*! + Checks for the existence of the file \a name. + + If \a acceptAbsPath is TRUE a path starting with separator "/" + will check the file with the absolute path. If \a acceptAbsPath is + FALSE any number of separators at the beginning of \a name will be + removed and the resultant file name will be checked. + + Returns TRUE if the file exists; otherwise returns FALSE. + + \sa TQFileInfo::exists(), TQFile::exists() +*/ + +bool TQDir::exists( const TQString &name, bool acceptAbsPath ) //### const in 4.0 +{ + if ( name.isEmpty() ) { +#if defined(QT_CHECK_NULL) + tqWarning( "TQDir::exists: Empty or null file name" ); +#endif + return FALSE; + } + TQString tmp = filePath( name, acceptAbsPath ); + return TQFile::exists( tmp ); +} + +/*! + Returns the native directory separator; "/" under UNIX (including + Mac OS X) and "\" under Windows. + + You do not need to use this function to build file paths. If you + always use "/", TQt will translate your paths to conform to the + underlying operating system. +*/ + +char TQDir::separator() +{ +#if defined(Q_OS_UNIX) + return '/'; +#elif defined (Q_FS_FAT) || defined(TQ_WS_WIN) + return '\\'; +#elif defined (Q_OS_MAC) + return ':'; +#else + return '/'; +#endif +} + +/*! + Returns the application's current directory. + + Use path() to access a TQDir object's path. + + \sa currentDirPath(), TQDir::TQDir() +*/ + +TQDir TQDir::current() +{ + return TQDir( currentDirPath() ); +} + +/*! + Returns the home directory. + + Under Windows the \c HOME environment variable is used. If this + does not exist the \c USERPROFILE environment variable is used. If + that does not exist the path is formed by concatenating the \c + HOMEDRIVE and \c HOMEPATH environment variables. If they don't + exist the rootDirPath() is used (this uses the \c SystemDrive + environment variable). If none of these exist "C:\" is used. + + Under non-Windows operating systems the \c HOME environment + variable is used if it exists, otherwise rootDirPath() is used. + + \sa homeDirPath() +*/ + +TQDir TQDir::home() +{ + return TQDir( homeDirPath() ); +} + +/*! + Returns the root directory. + + \sa rootDirPath() drives() +*/ + +TQDir TQDir::root() +{ + return TQDir( rootDirPath() ); +} + +/*! + \fn TQString TQDir::homeDirPath() + + Returns the absolute path of the user's home directory. + + \sa home() +*/ + +TQValueList qt_makeFilterList( const TQString &filter ) +{ + TQValueList regExps; + if ( filter.isEmpty() ) + return regExps; + + TQChar sep( ';' ); + int i = filter.find( sep, 0 ); + if ( i == -1 && filter.find( ' ', 0 ) != -1 ) + sep = TQChar( ' ' ); + + TQStringList list = TQStringList::split( sep, filter ); + TQStringList::Iterator it = list.begin(); + while ( it != list.end() ) { + regExps << TQRegExp( (*it).stripWhiteSpace(), CaseSensitiveFS, TRUE ); + ++it; + } + return regExps; +} + +bool qt_matchFilterList( const TQValueList& filters, + const TQString &fileName ) +{ + TQValueList::ConstIterator rit = filters.begin(); + while ( rit != filters.end() ) { + if ( (*rit).exactMatch(fileName) ) + return TRUE; + ++rit; + } + return FALSE; +} + + +/*! + \overload + + Returns TRUE if the \a fileName matches any of the wildcard (glob) + patterns in the list of \a filters; otherwise returns FALSE. + + (See \link tqregexp.html#wildcard-matching TQRegExp wildcard + matching.\endlink) + \sa TQRegExp::match() +*/ + +bool TQDir::match( const TQStringList &filters, const TQString &fileName ) +{ + TQStringList::ConstIterator sit = filters.begin(); + while ( sit != filters.end() ) { + TQRegExp rx( *sit, CaseSensitiveFS, TRUE ); + if ( rx.exactMatch(fileName) ) + return TRUE; + ++sit; + } + return FALSE; +} + +/*! + Returns TRUE if the \a fileName matches the wildcard (glob) + pattern \a filter; otherwise returns FALSE. The \a filter may + contain multiple patterns separated by spaces or semicolons. + + (See \link tqregexp.html#wildcard-matching TQRegExp wildcard + matching.\endlink) + \sa TQRegExp::match() +*/ + +bool TQDir::match( const TQString &filter, const TQString &fileName ) +{ + return qt_matchFilterList( qt_makeFilterList(filter), fileName ); +} + + +/*! + Removes all multiple directory separators "/" and resolves any + "."s or ".."s found in the path, \a filePath. + + Symbolic links are kept. This function does not return the + canonical path, but rather the simplest version of the input. + For example, "./local" becomes "local", "local/../bin" becomes + "bin" and "/local/usr/../bin" becomes "/local/bin". + + \sa absPath() canonicalPath() +*/ + +TQString TQDir::cleanDirPath( const TQString &filePath ) +{ + TQString name = filePath; + TQString newPath; + + if ( name.isEmpty() ) + return name; + + slashify( name ); + + bool addedSeparator = isRelativePath( name ); + if ( addedSeparator ) + name.insert( 0, '/' ); + + int ePos, pos, upLevel; + + pos = ePos = name.length(); + upLevel = 0; + int len; + + while ( pos && (pos = name.findRev('/', pos - 1)) != -1 ) { + len = ePos - pos - 1; + if ( len == 2 && name.at(pos + 1) == '.' + && name.at(pos + 2) == '.' ) { + upLevel++; + } else { + if ( len != 0 && (len != 1 || name.at(pos + 1) != '.') ) { + if ( !upLevel ) + newPath = TQString::fromLatin1("/") + + name.mid(pos + 1, len) + newPath; + else + upLevel--; + } + } + ePos = pos; + } + if ( addedSeparator ) { + while ( upLevel-- ) + newPath.insert( 0, TQString::fromLatin1("/..") ); + if ( !newPath.isEmpty() ) + newPath.remove( (uint)0, (uint)1 ); + else + newPath = TQString::fromLatin1("."); + } else { + if ( newPath.isEmpty() ) + newPath = TQString::fromLatin1("/"); +#if defined(Q_FS_FAT) || defined(Q_OS_OS2EMX) + if ( name[0] == '/' ) { + if ( name[1] == '/' ) // "\\machine\x\ ..." + newPath.insert( 0, '/' ); + } else { + newPath = name.left(2) + newPath; + } +#endif + } + return newPath; +} + +int qt_cmp_si_sortSpec; + +#if defined(Q_C_CALLBACKS) +extern "C" { +#endif + +#ifdef Q_OS_TEMP +int __cdecl qt_cmp_si( const void *n1, const void *n2 ) +#else +int qt_cmp_si( const void *n1, const void *n2 ) +#endif +{ + if ( !n1 || !n2 ) + return 0; + + TQDirSortItem* f1 = (TQDirSortItem*)n1; + TQDirSortItem* f2 = (TQDirSortItem*)n2; + + if ( qt_cmp_si_sortSpec & TQDir::DirsFirst ) + if ( f1->item->isDir() != f2->item->isDir() ) + return f1->item->isDir() ? -1 : 1; + + int r = 0; + int sortBy = qt_cmp_si_sortSpec & TQDir::SortByMask; + + switch ( sortBy ) { + case TQDir::Time: + r = f1->item->lastModified().secsTo(f2->item->lastModified()); + break; + case TQDir::Size: + r = f2->item->size() - f1->item->size(); + break; + default: + ; + } + + if ( r == 0 && sortBy != TQDir::Unsorted ) { + // Still not sorted - sort by name + bool ic = qt_cmp_si_sortSpec & TQDir::IgnoreCase; + + if ( f1->filename_cache.isNull() ) + f1->filename_cache = ic ? f1->item->fileName().lower() + : f1->item->fileName(); + if ( f2->filename_cache.isNull() ) + f2->filename_cache = ic ? f2->item->fileName().lower() + : f2->item->fileName(); + + r = qt_cmp_si_sortSpec & TQDir::LocaleAware + ? f1->filename_cache.localeAwareCompare(f2->filename_cache) + : f1->filename_cache.compare(f2->filename_cache); + } + + if ( r == 0 ) { + // Enforce an order - the order the items appear in the array + r = (char*)n1 - (char*)n2; + } + + if ( qt_cmp_si_sortSpec & TQDir::Reversed ) + return -r; + else + return r; +} + +#if defined(Q_C_CALLBACKS) +} +#endif + +/*! \internal + Detaches all internal data. +*/ +void TQDir::detach() +{ + // deepcopy + dPath = TQDeepCopy(dPath); + nameFilt = TQDeepCopy(nameFilt); + + if ( fList ) + *fList = TQDeepCopy( *fList ); + + if ( fiList ) { + TQFileInfoList *newlist = new TQFileInfoList( *fiList ); + delete fiList; + fiList = newlist; + } +} + +#endif // TQT_NO_DIR diff --git a/src/tools/tqdir.h b/src/tools/tqdir.h new file mode 100644 index 000000000..41ba93e8c --- /dev/null +++ b/src/tools/tqdir.h @@ -0,0 +1,250 @@ +/**************************************************************************** +** +** Definition of TQDir class +** +** Created : 950427 +** +** Copyright (C) 1992-2008 Trolltech ASA. All rights reserved. +** +** This file is part of the tools module of the TQt GUI Toolkit. +** +** This file may be used under the terms of the GNU General +** Public License versions 2.0 or 3.0 as published by the Free +** Software Foundation and appearing in the files LICENSE.GPL2 +** and LICENSE.GPL3 included in the packaging of this file. +** Alternatively you may (at your option) use any later version +** of the GNU General Public License if such license has been +** publicly approved by Trolltech ASA (or its successors, if any) +** and the KDE Free TQt Foundation. +** +** Please review the following information to ensure GNU General +** Public Licensing requirements will be met: +** http://trolltech.com/products/qt/licenses/licensing/opensource/. +** If you are unsure which license is appropriate for your use, please +** review the following information: +** http://trolltech.com/products/qt/licenses/licensing/licensingoverview +** or contact the sales department at sales@trolltech.com. +** +** This file may be used under the terms of the Q Public License as +** defined by Trolltech ASA and appearing in the file LICENSE.TQPL +** included in the packaging of this file. Licensees holding valid TQt +** Commercial licenses may use this file in accordance with the TQt +** Commercial License Agreement provided with the Software. +** +** This file is provided "AS IS" with NO WARRANTY OF ANY KIND, +** INCLUDING THE WARRANTIES OF DESIGN, MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE. Trolltech reserves all rights not granted +** herein. +** +**********************************************************************/ + +#ifndef TQDIR_H +#define TQDIR_H + +#ifndef QT_H +#include "ntqglobal.h" +#include "tqstrlist.h" +#include "tqfileinfo.h" +#endif // QT_H + + +#ifndef TQT_NO_DIR +typedef TQPtrList TQFileInfoList; +typedef TQPtrListIterator TQFileInfoListIterator; +class TQStringList; +template class TQDeepCopy; + + +class TQ_EXPORT TQDir +{ +public: + enum FilterSpec { Dirs = 0x001, + Files = 0x002, + Drives = 0x004, + NoSymLinks = 0x008, + All = 0x007, + TypeMask = 0x00F, + + Readable = 0x010, + Writable = 0x020, + Executable = 0x040, + RWEMask = 0x070, + + Modified = 0x080, + Hidden = 0x100, + System = 0x200, + AccessMask = 0x3F0, + + DefaultFilter = -1 }; + + enum SortSpec { Name = 0x00, + Time = 0x01, + Size = 0x02, + Unsorted = 0x03, + SortByMask = 0x03, + + DirsFirst = 0x04, + Reversed = 0x08, + IgnoreCase = 0x10, + LocaleAware = 0x20, + DefaultSort = -1 }; + + TQDir(); + TQDir( const TQString &path, const TQString &nameFilter = TQString::null, + int sortSpec = Name | IgnoreCase, int filterSpec = All ); + TQDir( const TQDir & ); + + virtual ~TQDir(); + + TQDir &operator=( const TQDir & ); + TQDir &operator=( const TQString &path ); + + virtual void setPath( const TQString &path ); + virtual TQString path() const; + virtual TQString absPath() const; + virtual TQString canonicalPath() const; + + virtual TQString dirName() const; + virtual TQString filePath( const TQString &fileName, + bool acceptAbsPath = TRUE ) const; + virtual TQString absFilePath( const TQString &fileName, + bool acceptAbsPath = TRUE ) const; + + static TQString convertSeparators( const TQString &pathName ); + + virtual bool cd( const TQString &dirName, bool acceptAbsPath = TRUE ); + virtual bool cdUp(); + + TQString nameFilter() const; + virtual void setNameFilter( const TQString &nameFilter ); + FilterSpec filter() const; + virtual void setFilter( int filterSpec ); + SortSpec sorting() const; + virtual void setSorting( int sortSpec ); + + bool matchAllDirs() const; + virtual void setMatchAllDirs( bool ); + + uint count() const; + TQString operator[]( int ) const; + + virtual TQStrList encodedEntryList( int filterSpec = DefaultFilter, + int sortSpec = DefaultSort ) const; + virtual TQStrList encodedEntryList( const TQString &nameFilter, + int filterSpec = DefaultFilter, + int sortSpec = DefaultSort ) const; + virtual TQStringList entryList( int filterSpec = DefaultFilter, + int sortSpec = DefaultSort ) const; + virtual TQStringList entryList( const TQString &nameFilter, + int filterSpec = DefaultFilter, + int sortSpec = DefaultSort ) const; + + virtual const TQFileInfoList *entryInfoList( int filterSpec = DefaultFilter, + int sortSpec = DefaultSort ) const; + virtual const TQFileInfoList *entryInfoList( const TQString &nameFilter, + int filterSpec = DefaultFilter, + int sortSpec = DefaultSort ) const; + + static const TQFileInfoList *drives(); + + virtual bool mkdir( const TQString &dirName, + bool acceptAbsPath = TRUE ) const; + virtual bool rmdir( const TQString &dirName, + bool acceptAbsPath = TRUE ) const; + + virtual bool isReadable() const; + virtual bool exists() const; + virtual bool isRoot() const; + + virtual bool isRelative() const; + virtual void convertToAbs(); + + virtual bool operator==( const TQDir & ) const; + virtual bool operator!=( const TQDir & ) const; + + virtual bool remove( const TQString &fileName, + bool acceptAbsPath = TRUE ); + virtual bool rename( const TQString &name, const TQString &newName, + bool acceptAbsPaths = TRUE ); + virtual bool exists( const TQString &name, + bool acceptAbsPath = TRUE ); + + static char separator(); + + static bool setCurrent( const TQString &path ); + static TQDir current(); + static TQDir home(); + static TQDir root(); + static TQString currentDirPath(); + static TQString homeDirPath(); + static TQString rootDirPath(); + + static bool match( const TQStringList &filters, const TQString &fileName ); + static bool match( const TQString &filter, const TQString &fileName ); + static TQString cleanDirPath( const TQString &dirPath ); + static bool isRelativePath( const TQString &path ); + void refresh() const; + +private: +#ifdef Q_OS_MAC + typedef struct FSSpec FSSpec; + static FSSpec *make_spec(const TQString &); +#endif + void init(); + virtual bool readDirEntries( const TQString &nameFilter, + int FilterSpec, int SortSpec ); + + static void slashify( TQString & ); + + TQString dPath; + TQStringList *fList; + TQFileInfoList *fiList; + TQString nameFilt; + FilterSpec filtS; + SortSpec sortS; + uint dirty : 1; + uint allDirs : 1; + + void detach(); + friend class TQDeepCopy< TQDir >; +}; + + +inline TQString TQDir::path() const +{ + return dPath; +} + +inline TQString TQDir::nameFilter() const +{ + return nameFilt; +} + +inline TQDir::FilterSpec TQDir::filter() const +{ + return filtS; +} + +inline TQDir::SortSpec TQDir::sorting() const +{ + return sortS; +} + +inline bool TQDir::matchAllDirs() const +{ + return allDirs; +} + +inline bool TQDir::operator!=( const TQDir &d ) const +{ + return !(*this == d); +} + + +struct TQDirSortItem { + TQString filename_cache; + TQFileInfo* item; +}; + +#endif // TQT_NO_DIR +#endif // TQDIR_H diff --git a/src/tools/tqdir_p.h b/src/tools/tqdir_p.h new file mode 100644 index 000000000..d6c6fb2e8 --- /dev/null +++ b/src/tools/tqdir_p.h @@ -0,0 +1,82 @@ +/**************************************************************************** +** +** Definition of some private TQDir functions. +** +** Created : 001106 +** +** Copyright (C) 2005-2008 Trolltech ASA. All rights reserved. +** +** This file is part of the tools module of the TQt GUI Toolkit. +** +** This file may be used under the terms of the GNU General +** Public License versions 2.0 or 3.0 as published by the Free +** Software Foundation and appearing in the files LICENSE.GPL2 +** and LICENSE.GPL3 included in the packaging of this file. +** Alternatively you may (at your option) use any later version +** of the GNU General Public License if such license has been +** publicly approved by Trolltech ASA (or its successors, if any) +** and the KDE Free TQt Foundation. +** +** Please review the following information to ensure GNU General +** Public Licensing requirements will be met: +** http://trolltech.com/products/qt/licenses/licensing/opensource/. +** If you are unsure which license is appropriate for your use, please +** review the following information: +** http://trolltech.com/products/qt/licenses/licensing/licensingoverview +** or contact the sales department at sales@trolltech.com. +** +** This file may be used under the terms of the Q Public License as +** defined by Trolltech ASA and appearing in the file LICENSE.TQPL +** included in the packaging of this file. Licensees holding valid TQt +** Commercial licenses may use this file in accordance with the TQt +** Commercial License Agreement provided with the Software. +** +** This file is provided "AS IS" with NO WARRANTY OF ANY KIND, +** INCLUDING THE WARRANTIES OF DESIGN, MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE. Trolltech reserves all rights not granted +** herein. +** +**********************************************************************/ + +#ifndef TQDIR_P_H +#define TQDIR_P_H + +// +// W A R N I N G +// ------------- +// +// This file is not part of the TQt API. It exists for the convenience +// of tqdir.cpp and tqdir_*.cpp. +// This header file may change from version to version without notice, +// or even be removed. +// +// We mean it. +// +// + +#ifndef QT_H +#include "tqregexp.h" +#include "tqvaluelist.h" +#endif // QT_H + +extern TQValueList qt_makeFilterList( const TQString & ); +extern bool qt_matchFilterList( const TQValueList &, const TQString & ); + +extern int qt_cmp_si_sortSpec; + +#if defined(Q_C_CALLBACKS) +extern "C" { +#endif + +#ifdef Q_OS_TEMP +extern int __cdecl qt_cmp_si( const void *, const void * ); +#else +extern int qt_cmp_si( const void *, const void * ); +#endif + +#if defined(Q_C_CALLBACKS) +} +#endif + + +#endif // TQDIR_P_H diff --git a/src/tools/tqdir_unix.cpp b/src/tools/tqdir_unix.cpp new file mode 100644 index 000000000..3587a706a --- /dev/null +++ b/src/tools/tqdir_unix.cpp @@ -0,0 +1,329 @@ +/**************************************************************************** +** +** Implementation of TQDir class +** +** Created : 950628 +** +** Copyright (C) 1992-2008 Trolltech ASA. All rights reserved. +** +** This file is part of the tools module of the TQt GUI Toolkit. +** +** This file may be used under the terms of the GNU General +** Public License versions 2.0 or 3.0 as published by the Free +** Software Foundation and appearing in the files LICENSE.GPL2 +** and LICENSE.GPL3 included in the packaging of this file. +** Alternatively you may (at your option) use any later version +** of the GNU General Public License if such license has been +** publicly approved by Trolltech ASA (or its successors, if any) +** and the KDE Free TQt Foundation. +** +** Please review the following information to ensure GNU General +** Public Licensing requirements will be met: +** http://trolltech.com/products/qt/licenses/licensing/opensource/. +** If you are unsure which license is appropriate for your use, please +** review the following information: +** http://trolltech.com/products/qt/licenses/licensing/licensingoverview +** or contact the sales department at sales@trolltech.com. +** +** This file may be used under the terms of the Q Public License as +** defined by Trolltech ASA and appearing in the file LICENSE.TQPL +** included in the packaging of this file. Licensees holding valid TQt +** Commercial licenses may use this file in accordance with the TQt +** Commercial License Agreement provided with the Software. +** +** This file is provided "AS IS" with NO WARRANTY OF ANY KIND, +** INCLUDING THE WARRANTIES OF DESIGN, MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE. Trolltech reserves all rights not granted +** herein. +** +**********************************************************************/ + +#include "qplatformdefs.h" +#include "tqdir.h" + +#ifndef TQT_NO_DIR + +#include "tqdir_p.h" +#include "tqfileinfo.h" +#include "tqregexp.h" +#include "tqstringlist.h" + +#ifdef TQT_THREAD_SUPPORT +# include +#endif // TQT_THREAD_SUPPORT + +#include +#include +#include +#include + + +void TQDir::slashify( TQString& ) +{ +} + +TQString TQDir::homeDirPath() +{ + TQString d; + d = TQFile::decodeName(getenv("HOME")); + slashify( d ); + if ( d.isNull() ) + d = rootDirPath(); + return d; +} + +TQString TQDir::canonicalPath() const +{ + TQString r; +#if !defined(PATH_MAX) + char *cur = ::get_current_dir_name(); + if ( cur ) { + char *tmp = canonicalize_file_name( TQFile::encodeName( dPath ).data() ); + if ( tmp ) { + r = TQFile::decodeName( tmp ); + free( tmp ); + } + slashify( r ); + // always make sure we go back to the current dir + ::chdir( cur ); + free( cur ); + } +#else + char cur[PATH_MAX+1]; + if ( ::getcwd( cur, PATH_MAX ) ) { + char tmp[PATH_MAX+1]; + // need the cast for old solaris versions of realpath that doesn't take + // a const char*. + if( ::realpath( (char*)TQFile::encodeName( dPath ).data(), tmp ) ) + r = TQFile::decodeName( tmp ); + slashify( r ); + + // always make sure we go back to the current dir + if (::chdir( cur ) < 0) { + // Error! + // FIXME + } + } +#endif /* !PATH_MAX */ + return r; +} + +bool TQDir::mkdir( const TQString &dirName, bool acceptAbsPath ) const +{ +#if defined(Q_OS_MACX) // Mac X doesn't support trailing /'s + TQString name = dirName; + if (dirName[dirName.length() - 1] == "/") + name = dirName.left( dirName.length() - 1 ); + int status = + ::mkdir( TQFile::encodeName(filePath(name,acceptAbsPath)), 0777 ); +#else + int status = + ::mkdir( TQFile::encodeName(filePath(dirName,acceptAbsPath)), 0777 ); +#endif + return status == 0; +} + +bool TQDir::rmdir( const TQString &dirName, bool acceptAbsPath ) const +{ + return ::rmdir( TQFile::encodeName(filePath(dirName,acceptAbsPath)) ) == 0; +} + +bool TQDir::isReadable() const +{ + return ::access( TQFile::encodeName(dPath), R_OK | X_OK ) == 0; +} + +bool TQDir::isRoot() const +{ + return dPath == TQString::fromLatin1("/"); +} + +bool TQDir::rename( const TQString &name, const TQString &newName, + bool acceptAbsPaths ) +{ + if ( name.isEmpty() || newName.isEmpty() ) { +#if defined(QT_CHECK_NULL) + tqWarning( "TQDir::rename: Empty or null file name(s)" ); +#endif + return FALSE; + } + TQString fn1 = filePath( name, acceptAbsPaths ); + TQString fn2 = filePath( newName, acceptAbsPaths ); + return ::rename( TQFile::encodeName(fn1), + TQFile::encodeName(fn2) ) == 0; +} + +bool TQDir::setCurrent( const TQString &path ) +{ + int r; + r = ::chdir( TQFile::encodeName(path) ); + return r >= 0; +} + +TQString TQDir::currentDirPath() +{ + TQString result; + + struct stat st; + if ( ::stat( ".", &st ) == 0 ) { +#if !defined(PATH_MAX) + char *currentName = ::get_current_dir_name(); + if ( currentName ) { + result = TQFile::decodeName(currentName); + free( currentName ); + } +#else + char currentName[PATH_MAX+1]; + if ( ::getcwd( currentName, PATH_MAX ) ) + result = TQFile::decodeName(currentName); +#endif /* !PATH_MAX */ +#if defined(QT_DEBUG) + if ( result.isNull() ) + tqWarning( "TQDir::currentDirPath: getcwd() failed" ); +#endif + } else { +#if defined(QT_DEBUG) + tqWarning( "TQDir::currentDirPath: stat(\".\") failed" ); +#endif + } + slashify( result ); + return result; +} + +TQString TQDir::rootDirPath() +{ + TQString d = TQString::fromLatin1( "/" ); + return d; +} + +bool TQDir::isRelativePath( const TQString &path ) +{ + int len = path.length(); + if ( len == 0 ) + return TRUE; + return path[0] != '/'; +} + +bool TQDir::readDirEntries( const TQString &nameFilter, + int filterSpec, int sortSpec ) +{ + int i; + if ( !fList ) { + fList = new TQStringList; + TQ_CHECK_PTR( fList ); + fiList = new TQFileInfoList; + TQ_CHECK_PTR( fiList ); + fiList->setAutoDelete( TRUE ); + } else { + fList->clear(); + fiList->clear(); + } + + TQValueList filters = qt_makeFilterList( nameFilter ); + + bool doDirs = (filterSpec & Dirs) != 0; + bool doFiles = (filterSpec & Files) != 0; + bool noSymLinks = (filterSpec & NoSymLinks) != 0; + bool doReadable = (filterSpec & Readable) != 0; + bool doWritable = (filterSpec & Writable) != 0; + bool doExecable = (filterSpec & Executable) != 0; + bool doHidden = (filterSpec & Hidden) != 0; + bool doSystem = (filterSpec & System) != 0; + + TQFileInfo fi; + DIR *dir; + dirent *file; + + dir = opendir( TQFile::encodeName(dPath) ); + if ( !dir ) + return FALSE; // cannot read the directory + +#if defined(TQT_THREAD_SUPPORT) && defined(_POSIX_THREAD_SAFE_FUNCTIONS) && !defined(Q_OS_CYGWIN) + union { + struct dirent mt_file; + char b[sizeof(struct dirent) + MAXNAMLEN + 1]; + } u; + while ( readdir_r(dir, &u.mt_file, &file ) == 0 && file ) +#else + while ( (file = readdir(dir)) ) +#endif // TQT_THREAD_SUPPORT && _POSIX_THREAD_SAFE_FUNCTIONS + { + TQString fn = TQFile::decodeName(file->d_name); + fi.setFile( *this, fn ); + if ( !qt_matchFilterList(filters, fn) && !(allDirs && fi.isDir()) ) + continue; + if ( (doDirs && fi.isDir()) || (doFiles && fi.isFile()) || + (doSystem && (!fi.isFile() && !fi.isDir())) ) { + if ( noSymLinks && fi.isSymLink() ) + continue; + if ( (filterSpec & RWEMask) != 0 ) + if ( (doReadable && !fi.isReadable()) || + (doWritable && !fi.isWritable()) || + (doExecable && !fi.isExecutable()) ) + continue; + if ( !doHidden && fn[0] == '.' && + fn != TQString::fromLatin1(".") + && fn != TQString::fromLatin1("..") ) + continue; + fiList->append( new TQFileInfo( fi ) ); + } + } + if ( closedir(dir) != 0 ) { +#if defined(QT_CHECK_NULL) + tqWarning( "TQDir::readDirEntries: Cannot close the directory: %s", + dPath.local8Bit().data() ); +#endif + } + + // Sort... + if(fiList->count()) { + TQDirSortItem* si= new TQDirSortItem[fiList->count()]; + TQFileInfo* itm; + i=0; + for (itm = fiList->first(); itm; itm = fiList->next()) + si[i++].item = itm; + qt_cmp_si_sortSpec = sortSpec; + qsort( si, i, sizeof(si[0]), qt_cmp_si ); + // put them back in the list + fiList->setAutoDelete( FALSE ); + fiList->clear(); + int j; + for ( j=0; jappend( si[j].item ); + fList->append( si[j].item->fileName() ); + } + delete [] si; + fiList->setAutoDelete( TRUE ); + } + + if ( filterSpec == (FilterSpec)filtS && sortSpec == (SortSpec)sortS && + nameFilter == nameFilt ) + dirty = FALSE; + else + dirty = TRUE; + return TRUE; +} + +const TQFileInfoList * TQDir::drives() +{ + // at most one instance of TQFileInfoList is leaked, and this variable + // points to that list + static TQFileInfoList * knownMemoryLeak = 0; + + if ( !knownMemoryLeak ) { + +#ifdef TQT_THREAD_SUPPORT + TQMutexLocker locker( tqt_global_mutexpool ? + tqt_global_mutexpool->get( &knownMemoryLeak ) : 0 ); +#endif // TQT_THREAD_SUPPORT + + if ( !knownMemoryLeak ) { + knownMemoryLeak = new TQFileInfoList; + // non-win32 versions both use just one root directory + knownMemoryLeak->append( new TQFileInfo( rootDirPath() ) ); + } + } + + return knownMemoryLeak; +} +#endif //TQT_NO_DIR diff --git a/src/tools/tqfile.cpp b/src/tools/tqfile.cpp new file mode 100644 index 000000000..06a127fc2 --- /dev/null +++ b/src/tools/tqfile.cpp @@ -0,0 +1,747 @@ +/**************************************************************************** +** +** Implementation of TQFile class +** +** Created : 930812 +** +** Copyright (C) 1992-2008 Trolltech ASA. All rights reserved. +** +** This file is part of the tools module of the TQt GUI Toolkit. +** +** This file may be used under the terms of the GNU General +** Public License versions 2.0 or 3.0 as published by the Free +** Software Foundation and appearing in the files LICENSE.GPL2 +** and LICENSE.GPL3 included in the packaging of this file. +** Alternatively you may (at your option) use any later version +** of the GNU General Public License if such license has been +** publicly approved by Trolltech ASA (or its successors, if any) +** and the KDE Free TQt Foundation. +** +** Please review the following information to ensure GNU General +** Public Licensing requirements will be met: +** http://trolltech.com/products/qt/licenses/licensing/opensource/. +** If you are unsure which license is appropriate for your use, please +** review the following information: +** http://trolltech.com/products/qt/licenses/licensing/licensingoverview +** or contact the sales department at sales@trolltech.com. +** +** This file may be used under the terms of the Q Public License as +** defined by Trolltech ASA and appearing in the file LICENSE.TQPL +** included in the packaging of this file. Licensees holding valid TQt +** Commercial licenses may use this file in accordance with the TQt +** Commercial License Agreement provided with the Software. +** +** This file is provided "AS IS" with NO WARRANTY OF ANY KIND, +** INCLUDING THE WARRANTIES OF DESIGN, MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE. Trolltech reserves all rights not granted +** herein. +** +**********************************************************************/ + +#include "qplatformdefs.h" + +// POSIX Large File Support redefines open -> open64 +#if defined(open) +# undef open +#endif + +// POSIX Large File Support redefines truncate -> truncate64 +#if defined(truncate) +# undef truncate +#endif + +#include "tqfile.h" +#ifndef NO_ERRNO_H +#include +#endif + + +// Duplicated from tqobject.h, but we cannot include tqobject.h here since +// it causes qmake to not build on irix g++ +#define TQT_TRANSLATE_NOOP(scope,x) (x) + +const char* qt_fileerr_unknown = TQT_TRANSLATE_NOOP( "TQFile", "Unknown error" ); +const char* qt_fileerr_read = TQT_TRANSLATE_NOOP( "TQFile", "Could not read from the file" ); +const char* qt_fileerr_write = TQT_TRANSLATE_NOOP( "TQFile", "Could not write to the file" ); + +#define TQFILEERR_EACCES TQT_TRANSLATE_NOOP( "TQFile", "Permission denied" ) +#define TQFILEERR_EMFILE TQT_TRANSLATE_NOOP( "TQFile", "Too many open files" ) +#define TQFILEERR_ENOENT TQT_TRANSLATE_NOOP( "TQFile", "No such file or directory" ) +#define TQFILEERR_ENOSPC TQT_TRANSLATE_NOOP( "TQFile", "No space left on device" ) + +class TQFilePrivate +{ +public: + TQString errorString; +}; + +extern bool qt_file_access( const TQString& fn, int t ); + +/*! + \class TQFile tqfile.h + \reentrant + \brief The TQFile class is an I/O device that operates on files. + + \ingroup io + \mainclass + + TQFile is an I/O device for reading and writing binary and text + files. A TQFile may be used by itself or more conveniently with a + TQDataStream or TQTextStream. + + The file name is usually passed in the constructor but can be + changed with setName(). You can check for a file's existence with + exists() and remove a file with remove(). + + The file is opened with open(), closed with close() and flushed + with flush(). Data is usually read and written using TQDataStream + or TQTextStream, but you can read with readBlock() and readLine() + and write with writeBlock(). TQFile also supports getch(), + ungetch() and putch(). + + The size of the file is returned by size(). You can get the + current file position or move to a new file position using the + at() functions. If you've reached the end of the file, atEnd() + returns TRUE. The file handle is returned by handle(). + + Here is a code fragment that uses TQTextStream to read a text file + line by line. It prints each line with a line number. + \code + TQStringList lines; + TQFile file( "file.txt" ); + if ( file.open( IO_ReadOnly ) ) { + TQTextStream stream( &file ); + TQString line; + int i = 1; + while ( !stream.atEnd() ) { + line = stream.readLine(); // line of text excluding '\n' + printf( "%3d: %s\n", i++, line.latin1() ); + lines += line; + } + file.close(); + } + \endcode + + Writing text is just as easy. The following example shows how to + write the data we read into the string list from the previous + example: + \code + TQFile file( "file.txt" ); + if ( file.open( IO_WriteOnly ) ) { + TQTextStream stream( &file ); + for ( TQStringList::Iterator it = lines.begin(); it != lines.end(); ++it ) + stream << *it << "\n"; + file.close(); + } + \endcode + + The TQFileInfo class holds detailed information about a file, such + as access permissions, file dates and file types. + + The TQDir class manages directories and lists of file names. + + TQt uses Unicode file names. If you want to do your own I/O on Unix + systems you may want to use encodeName() (and decodeName()) to + convert the file name into the local encoding. + + \important readAll() at() + + \sa TQDataStream, TQTextStream +*/ + +/*! + \fn TQ_LONG TQFile::writeBlock( const TQByteArray& data ) + + \overload +*/ + + +/*! + Constructs a TQFile with no name. +*/ + +TQFile::TQFile() +: d(0) +{ + init(); +} + +/*! + Constructs a TQFile with a file name \a name. + + \sa setName() +*/ + +TQFile::TQFile( const TQString &name ) + : fn(name), d(0) +{ + init(); +} + + +/*! + Destroys a TQFile. Calls close(). +*/ + +TQFile::~TQFile() +{ + close(); + delete d; +} + + +/*! + \internal + Initialize internal data. +*/ + +void TQFile::init() +{ + delete d; + d = new TQFilePrivate; + setFlags( IO_Direct ); + setStatus( IO_Ok ); + setErrorString( qt_fileerr_unknown ); + fh = 0; + fd = 0; + length = 0; + ioIndex = 0; + ext_f = FALSE; // not an external file handle +} + + +/*! + \fn TQString TQFile::name() const + + Returns the name set by setName(). + + \sa setName(), TQFileInfo::fileName() +*/ + +/*! + Sets the name of the file to \a name. The name can have no path, a + relative path or an absolute absolute path. + + Do not call this function if the file has already been opened. + + If the file name has no path or a relative path, the path used + will be whatever the application's current directory path is + \e{at the time of the open()} call. + + Example: + \code + TQFile file; + TQDir::setCurrent( "/tmp" ); + file.setName( "readme.txt" ); + TQDir::setCurrent( "/home" ); + file.open( IO_ReadOnly ); // opens "/home/readme.txt" under Unix + \endcode + + Note that the directory separator "/" works for all operating + systems supported by TQt. + + \sa name(), TQFileInfo, TQDir +*/ + +void TQFile::setName( const TQString &name ) +{ + if ( isOpen() ) { +#if defined(QT_CHECK_STATE) + tqWarning( "TQFile::setName: File is open" ); +#endif + close(); + } + fn = name; +} + +/*! + \overload + + Returns TRUE if this file exists; otherwise returns FALSE. + + \sa name() +*/ + +bool TQFile::exists() const +{ + return qt_file_access( fn, F_OK ); +} + +/*! + Returns TRUE if the file given by \a fileName exists; otherwise + returns FALSE. +*/ + +bool TQFile::exists( const TQString &fileName ) +{ + return qt_file_access( fileName, F_OK ); +} + + +/*! + Removes the file specified by the file name currently set. Returns + TRUE if successful; otherwise returns FALSE. + + The file is closed before it is removed. +*/ + +bool TQFile::remove() +{ + close(); + return remove( fn ); +} + +#if defined(Q_OS_MAC) || defined(Q_OS_MSDOS) || defined(Q_OS_WIN32) || defined(Q_OS_OS2) +# define HAS_TEXT_FILEMODE // has translate/text filemode +#endif +#if defined(O_NONBLOCK) +# define HAS_ASYNC_FILEMODE +# define OPEN_ASYNC O_NONBLOCK +#elif defined(O_NDELAY) +# define HAS_ASYNC_FILEMODE +# define OPEN_ASYNC O_NDELAY +#endif + +/*! + Flushes the file buffer to the disk. + + close() also flushes the file buffer. +*/ + +void TQFile::flush() +{ + if ( isOpen() && fh ) { // can only flush open/buffered file + if ( fflush( fh ) ) { // write error + if ( errno == ENOSPC ) // disk is full + setStatus( IO_ResourceError ); + else + setStatus( IO_WriteError ); + setErrorStringErrno( errno ); + } + } +} + +/*! \reimp + \fn TQIODevice::Offset TQFile::at() const +*/ + +/*! + Returns TRUE if the end of file has been reached; otherwise returns FALSE. + If TQFile has not been open()'d, then the behavior is undefined. + + \sa size() +*/ + +bool TQFile::atEnd() const +{ + if ( !isOpen() ) { +#if defined(QT_CHECK_STATE) + tqWarning( "TQFile::atEnd: File is not open" ); +#endif + return FALSE; + } + if ( isDirectAccess() && !isTranslated() ) { + if ( at() < size() ) + return FALSE; + } + const TQString errorString = d->errorString; + const bool ret = TQIODevice::atEnd(); + if (errorString != d->errorString) + d->errorString = errorString; + return ret; +} + +/*! + Reads a line of text. + + Reads bytes from the file into the char* \a p, until end-of-line + or \a maxlen bytes have been read, whichever occurs first. Returns + the number of bytes read, or -1 if there was an error. Any + terminating newline is not stripped. + + This function is only efficient for buffered files. Avoid + readLine() for files that have been opened with the \c IO_Raw + flag. + + \sa readBlock(), TQTextStream::readLine() +*/ + +TQ_LONG TQFile::readLine( char *p, TQ_ULONG maxlen ) +{ + if ( maxlen == 0 ) // application bug? + return 0; +#if defined(QT_CHECK_STATE) + TQ_CHECK_PTR( p ); + if ( !isOpen() ) { // file not open + tqWarning( "TQFile::readLine: File not open" ); + return -1; + } + if ( !isReadable() ) { // reading not permitted + tqWarning( "TQFile::readLine: Read operation not permitted" ); + return -1; + } +#endif + TQ_LONG nread; // number of bytes read + if ( isRaw() ) { // raw file + nread = TQIODevice::readLine( p, maxlen ); + } else { // buffered file + p = fgets( p, maxlen, fh ); + if ( p ) { + nread = tqstrlen( p ); + if ( !isSequentialAccess() ) + ioIndex += nread; + } else { + nread = -1; + setStatus(IO_ReadError); + setErrorString( qt_fileerr_read ); + } + } + return nread; +} + + +/*! + \overload + + Reads a line of text. + + Reads bytes from the file into string \a s, until end-of-line or + \a maxlen bytes have been read, whichever occurs first. Returns + the number of bytes read, or -1 if there was an error, e.g. end of + file. Any terminating newline is not stripped. + + This function is only efficient for buffered files. Avoid using + readLine() for files that have been opened with the \c IO_Raw + flag. + + Note that the string is read as plain Latin1 bytes, not Unicode. + + \sa readBlock(), TQTextStream::readLine() +*/ + +TQ_LONG TQFile::readLine( TQString& s, TQ_ULONG maxlen ) +{ + TQByteArray ba(maxlen); + TQ_LONG l = readLine(ba.data(),maxlen); + if ( l >= 0 ) { + ba.truncate(l); + s = TQString(ba); + } + return l; +} + + +/*! + Reads a single byte/character from the file. + + Returns the byte/character read, or -1 if the end of the file has + been reached. + + \sa putch(), ungetch() +*/ + +int TQFile::getch() +{ +#if defined(QT_CHECK_STATE) + if ( !isOpen() ) { // file not open + tqWarning( "TQFile::getch: File not open" ); + return EOF; + } + if ( !isReadable() ) { // reading not permitted + tqWarning( "TQFile::getch: Read operation not permitted" ); + return EOF; + } +#endif + + int ch; + + if ( !ungetchBuffer.isEmpty() ) { + int len = ungetchBuffer.length(); + ch = ungetchBuffer[ len-1 ]; + ungetchBuffer.truncate( len - 1 ); + return ch; + } + + if ( isRaw() ) { // raw file (inefficient) + char buf[1]; + ch = readBlock( buf, 1 ) == 1 ? buf[0] : EOF; + } else { // buffered file + if ( (ch = getc( fh )) != EOF ) { + if ( !isSequentialAccess() ) + ioIndex++; + } else { + setStatus(IO_ReadError); + setErrorString( qt_fileerr_read ); + } + } + return ch; +} + +/*! + Writes the character \a ch to the file. + + Returns \a ch, or -1 if some error occurred. + + \sa getch(), ungetch() +*/ + +int TQFile::putch( int ch ) +{ +#if defined(QT_CHECK_STATE) + if ( !isOpen() ) { // file not open + tqWarning( "TQFile::putch: File not open" ); + return EOF; + } + if ( !isWritable() ) { // writing not permitted + tqWarning( "TQFile::putch: Write operation not permitted" ); + return EOF; + } +#endif + if ( isRaw() ) { // raw file (inefficient) + char buf[1]; + buf[0] = ch; + ch = writeBlock( buf, 1 ) == 1 ? ch : EOF; + } else { // buffered file + if ( (ch = putc( ch, fh )) != EOF ) { + if ( !isSequentialAccess() ) + ioIndex++; + if ( ioIndex > length ) // update file length + length = ioIndex; + } else { + setStatus(IO_WriteError); + setErrorString( qt_fileerr_write ); + } + } + return ch; +} + +/*! + Puts the character \a ch back into the file and decrements the + index if it is not zero. + + This function is normally called to "undo" a getch() operation. + + Returns \a ch, or -1 if an error occurred. + + \sa getch(), putch() +*/ + +int TQFile::ungetch( int ch ) +{ +#if defined(QT_CHECK_STATE) + if ( !isOpen() ) { // file not open + tqWarning( "TQFile::ungetch: File not open" ); + return EOF; + } + if ( !isReadable() ) { // reading not permitted + tqWarning( "TQFile::ungetch: Read operation not permitted" ); + return EOF; + } +#endif + if ( ch == EOF ) // cannot unget EOF + return ch; + + if ( isSequentialAccess() && !fh) { + // pipe or similar => we cannot ungetch, so do it manually + ungetchBuffer += TQChar(ch); + return ch; + } + + if ( isRaw() ) { // raw file (very inefficient) + char buf[1]; + at( ioIndex-1 ); + buf[0] = ch; + if ( writeBlock(buf, 1) == 1 ) + at ( ioIndex-1 ); + else + ch = EOF; + } else { // buffered file + if ( (ch = ungetc(ch, fh)) != EOF ) { + if ( !isSequentialAccess() ) + ioIndex--; + } else { + setStatus( IO_ReadError ); + setErrorString( qt_fileerr_read ); + } + } + return ch; +} + + +static TQCString locale_encoder( const TQString &fileName ) +{ + return fileName.local8Bit(); +} + + +static TQFile::EncoderFn encoder = locale_encoder; + +/*! + When you use TQFile, TQFileInfo, and TQDir to access the file system + with TQt, you can use Unicode file names. On Unix, these file names + are converted to an 8-bit encoding. If you want to do your own + file I/O on Unix, you should convert the file name using this + function. On Windows NT/2000, Unicode file names are supported + directly in the file system and this function should be avoided. + On Windows 95, non-Latin1 locales are not supported. + + By default, this function converts \a fileName to the local 8-bit + encoding determined by the user's locale. This is sufficient for + file names that the user chooses. File names hard-coded into the + application should only use 7-bit ASCII filename characters. + + The conversion scheme can be changed using setEncodingFunction(). + This might be useful if you wish to give the user an option to + store file names in UTF-8, etc., but be aware that such file names + would probably then be unrecognizable when seen by other programs. + + \sa decodeName() +*/ + +TQCString TQFile::encodeName( const TQString &fileName ) +{ + return (*encoder)(fileName); +} + +/*! + \enum TQFile::EncoderFn + + This is used by TQFile::setEncodingFunction(). +*/ + +/*! + \nonreentrant + + Sets the function for encoding Unicode file names to \a f. The + default encodes in the locale-specific 8-bit encoding. + + \sa encodeName() +*/ +void TQFile::setEncodingFunction( EncoderFn f ) +{ + encoder = f; +} + +static +TQString locale_decoder( const TQCString &localFileName ) +{ +#ifndef TQ_WS_MAC + return TQString::fromLocal8Bit(localFileName); +#else + extern TQString qt_mac_precomposeFileName(const TQString &); // qglobal.cpp + return qt_mac_precomposeFileName(TQString::fromLocal8Bit(localFileName)); +#endif +} + +static TQFile::DecoderFn decoder = locale_decoder; + +/*! + This does the reverse of TQFile::encodeName() using \a localFileName. + + \sa setDecodingFunction() +*/ +TQString TQFile::decodeName( const TQCString &localFileName ) +{ + return (*decoder)(localFileName); +} + +/*! + \enum TQFile::DecoderFn + + This is used by TQFile::setDecodingFunction(). +*/ + +/*! + \nonreentrant + + Sets the function for decoding 8-bit file names to \a f. The + default uses the locale-specific 8-bit encoding. + + \sa encodeName(), decodeName() +*/ + +void TQFile::setDecodingFunction( DecoderFn f ) +{ + decoder = f; +} + +/*! + Returns a human-readable description of the reason of an error that occurred + on the device. The error described by the string corresponds to changes of + TQIODevice::status(). If the status is reset, the error string is also reset. + + The returned strings are not translated with the TQObject::tr() or + TQApplication::translate() functions. They are marked as translatable + strings in the "TQFile" context. Before you show the string to the user you + should translate it first, for example: + + \code + TQFile f( "address.dat" ); + if ( !f.open( IO_ReadOnly ) { + TQMessageBox::critical( + this, + tr("Open failed"), + tr("Could not open file for reading: %1").arg( tqApp->translate("TQFile",f.errorString()) ) + ); + return; + } + \endcode + + \sa TQIODevice::status(), TQIODevice::resetStatus(), setErrorString() +*/ + +TQString TQFile::errorString() const +{ + if ( status() == IO_Ok ) + return qt_fileerr_unknown; + return d->errorString; +} + +/*! + \nonreentrant + + Sets the error string returned by the errorString() function to \a str. + + \sa errorString(), TQIODevice::status() +*/ + +void TQFile::setErrorString( const TQString& str ) +{ + d->errorString = str; +} + +void TQFile::setErrorStringErrno( int errnum ) +{ + switch ( errnum ) { + case EACCES: + d->errorString = TQFILEERR_EACCES; + break; + case EMFILE: + d->errorString = TQFILEERR_EMFILE; + break; + case ENOENT: + d->errorString = TQFILEERR_ENOENT; + break; + case ENOSPC: + d->errorString = TQFILEERR_ENOSPC; + break; + default: +#ifndef Q_OS_TEMP + d->errorString = TQString::fromLocal8Bit( strerror( errnum ) ); +#else + { + unsigned short *string; + FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_SYSTEM, + NULL, + errnum, + MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), + (LPTSTR)&string, + 0, + NULL ); + d->errorString = TQString::fromUcs2( string ); + LocalFree( (HLOCAL)string ); + } +#endif + break; + } +} diff --git a/src/tools/tqfile.h b/src/tools/tqfile.h new file mode 100644 index 000000000..f40e1e585 --- /dev/null +++ b/src/tools/tqfile.h @@ -0,0 +1,131 @@ +/**************************************************************************** +** +** Definition of TQFile class +** +** Created : 930831 +** +** Copyright (C) 1992-2008 Trolltech ASA. All rights reserved. +** +** This file is part of the tools module of the TQt GUI Toolkit. +** +** This file may be used under the terms of the GNU General +** Public License versions 2.0 or 3.0 as published by the Free +** Software Foundation and appearing in the files LICENSE.GPL2 +** and LICENSE.GPL3 included in the packaging of this file. +** Alternatively you may (at your option) use any later version +** of the GNU General Public License if such license has been +** publicly approved by Trolltech ASA (or its successors, if any) +** and the KDE Free TQt Foundation. +** +** Please review the following information to ensure GNU General +** Public Licensing requirements will be met: +** http://trolltech.com/products/qt/licenses/licensing/opensource/. +** If you are unsure which license is appropriate for your use, please +** review the following information: +** http://trolltech.com/products/qt/licenses/licensing/licensingoverview +** or contact the sales department at sales@trolltech.com. +** +** This file may be used under the terms of the Q Public License as +** defined by Trolltech ASA and appearing in the file LICENSE.TQPL +** included in the packaging of this file. Licensees holding valid TQt +** Commercial licenses may use this file in accordance with the TQt +** Commercial License Agreement provided with the Software. +** +** This file is provided "AS IS" with NO WARRANTY OF ANY KIND, +** INCLUDING THE WARRANTIES OF DESIGN, MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE. Trolltech reserves all rights not granted +** herein. +** +**********************************************************************/ + +#ifndef TQFILE_H +#define TQFILE_H + +#ifndef QT_H +#include "tqiodevice.h" +#include "tqstring.h" +#include +#endif // QT_H + +class TQDir; +class TQFilePrivate; + +class TQ_EXPORT TQFile : public TQIODevice // file I/O device class +{ +public: + TQFile(); + TQFile( const TQString &name ); + ~TQFile(); + + TQString name() const; + void setName( const TQString &name ); + + typedef TQCString (*EncoderFn)( const TQString &fileName ); + typedef TQString (*DecoderFn)( const TQCString &localfileName ); + static TQCString encodeName( const TQString &fileName ); + static TQString decodeName( const TQCString &localFileName ); + static void setEncodingFunction( EncoderFn ); + static void setDecodingFunction( DecoderFn ); + + bool exists() const; + static bool exists( const TQString &fileName ); + + bool remove(); + static bool remove( const TQString &fileName ); + + bool open( int ); + bool open( int, FILE * ); + bool open( int, int ); + void close(); + void flush(); + + Offset size() const; + Offset at() const; + bool at( Offset ); + bool atEnd() const; + + TQ_LONG readBlock( char *data, TQ_ULONG len ); + TQ_LONG writeBlock( const char *data, TQ_ULONG len ); + TQ_LONG writeBlock( const TQByteArray& data ) + { return TQIODevice::writeBlock(data); } + TQ_LONG readLine( char *data, TQ_ULONG maxlen ); + TQ_LONG readLine( TQString &, TQ_ULONG maxlen ); + + int getch(); + int putch( int ); + int ungetch( int ); + + int handle() const; + + TQString errorString() const; // ### TQt 4: move into TQIODevice + +protected: + void setErrorString( const TQString& ); // ### TQt 4: move into TQIODevice + TQString fn; + FILE *fh; + int fd; + Offset length; + bool ext_f; + TQFilePrivate *d; // ### TQt 4: make private + +private: + void init(); + void setErrorStringErrno( int ); + TQCString ungetchBuffer; + +private: // Disabled copy constructor and operator= +#if defined(TQ_DISABLE_COPY) + TQFile( const TQFile & ); + TQFile &operator=( const TQFile & ); +#endif +}; + + +inline TQString TQFile::name() const +{ return fn; } + +inline TQIODevice::Offset TQFile::at() const +{ return ioIndex; } + + +#endif // TQFILE_H diff --git a/src/tools/tqfile_unix.cpp b/src/tools/tqfile_unix.cpp new file mode 100644 index 000000000..a56466cda --- /dev/null +++ b/src/tools/tqfile_unix.cpp @@ -0,0 +1,734 @@ +/**************************************************************************** +** +** Implementation of TQFile class +** +** Created : 950628 +** +** Copyright (C) 1992-2008 Trolltech ASA. All rights reserved. +** +** This file is part of the tools module of the TQt GUI Toolkit. +** +** This file may be used under the terms of the GNU General +** Public License versions 2.0 or 3.0 as published by the Free +** Software Foundation and appearing in the files LICENSE.GPL2 +** and LICENSE.GPL3 included in the packaging of this file. +** Alternatively you may (at your option) use any later version +** of the GNU General Public License if such license has been +** publicly approved by Trolltech ASA (or its successors, if any) +** and the KDE Free TQt Foundation. +** +** Please review the following information to ensure GNU General +** Public Licensing requirements will be met: +** http://trolltech.com/products/qt/licenses/licensing/opensource/. +** If you are unsure which license is appropriate for your use, please +** review the following information: +** http://trolltech.com/products/qt/licenses/licensing/licensingoverview +** or contact the sales department at sales@trolltech.com. +** +** This file may be used under the terms of the Q Public License as +** defined by Trolltech ASA and appearing in the file LICENSE.TQPL +** included in the packaging of this file. Licensees holding valid TQt +** Commercial licenses may use this file in accordance with the TQt +** Commercial License Agreement provided with the Software. +** +** This file is provided "AS IS" with NO WARRANTY OF ANY KIND, +** INCLUDING THE WARRANTIES OF DESIGN, MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE. Trolltech reserves all rights not granted +** herein. +** +**********************************************************************/ + +#include "qplatformdefs.h" + +// POSIX Large File Support redefines open -> open64 +static inline int qt_open(const char *pathname, int flags, mode_t mode) +{ return ::open(pathname, flags, mode); } +#if defined(open) +# undef open +#endif + +// POSIX Large File Support redefines truncate -> truncate64 +#if defined(truncate) +# undef truncate +#endif + +#include "tqfile.h" +#include +#include + +extern const char* qt_fileerr_read; + +bool qt_file_access( const TQString& fn, int t ) +{ + if ( fn.isEmpty() ) + return FALSE; + return ::access( TQFile::encodeName(fn), t ) == 0; +} + +/*! + \overload + Removes the file \a fileName. + Returns TRUE if successful, otherwise FALSE. +*/ + +bool TQFile::remove( const TQString &fileName ) +{ + if ( fileName.isEmpty() ) { +#if defined(QT_CHECK_NULL) + tqWarning( "TQFile::remove: Empty or null file name" ); +#endif + return FALSE; + } + return unlink( TQFile::encodeName(fileName) ) == 0; +} + +#if defined(O_NONBLOCK) +# define HAS_ASYNC_FILEMODE +# define OPEN_ASYNC O_NONBLOCK +#elif defined(O_NDELAY) +# define HAS_ASYNC_FILEMODE +# define OPEN_ASYNC O_NDELAY +#endif + +/*! + Opens the file specified by the file name currently set, using the + mode \a m. Returns TRUE if successful, otherwise FALSE. + + \keyword IO_Raw + \keyword IO_ReadOnly + \keyword IO_WriteOnly + \keyword IO_ReadWrite + \keyword IO_Append + \keyword IO_Truncate + \keyword IO_Translate + + The mode parameter \a m must be a combination of the following flags: + \table + \header \i Flag \i Meaning + \row \i IO_Raw + \i Raw (non-buffered) file access. + \row \i IO_ReadOnly + \i Opens the file in read-only mode. + \row \i IO_WriteOnly + \i Opens the file in write-only mode. If this flag is used + with another flag, e.g. \c IO_ReadOnly or \c IO_Raw or \c + IO_Append, the file is \e not truncated; but if used on + its own (or with \c IO_Truncate), the file is truncated. + \row \i IO_ReadWrite + \i Opens the file in read/write mode, equivalent to \c + (IO_ReadOnly | IO_WriteOnly). + \row \i IO_Append + \i Opens the file in append mode. (You must actually use \c + (IO_WriteOnly | IO_Append) to make the file writable and + to go into append mode.) This mode is very useful when you + want to write something to a log file. The file index is + set to the end of the file. Note that the result is + undefined if you position the file index manually using + at() in append mode. + \row \i IO_Truncate + \i Truncates the file. + \row \i IO_Translate + \i Enables carriage returns and linefeed translation for text + files under Windows. + \endtable + + The raw access mode is best when I/O is block-operated using a 4KB + block size or greater. Buffered access works better when reading + small portions of data at a time. + + \warning When working with buffered files, data may not be written + to the file at once. Call flush() to make sure that the data is + really written. + + \warning If you have a buffered file opened for both reading and + writing you must not perform an input operation immediately after + an output operation or vice versa. You should always call flush() + or a file positioning operation, e.g. at(), between input and + output operations, otherwise the buffer may contain garbage. + + If the file does not exist and \c IO_WriteOnly or \c IO_ReadWrite + is specified, it is created. + + Example: + \code + TQFile f1( "/tmp/data.bin" ); + f1.open( IO_Raw | IO_ReadWrite ); + + TQFile f2( "readme.txt" ); + f2.open( IO_ReadOnly | IO_Translate ); + + TQFile f3( "audit.log" ); + f3.open( IO_WriteOnly | IO_Append ); + \endcode + + \sa name(), close(), isOpen(), flush() +*/ + +bool TQFile::open( int m ) +{ + if ( isOpen() ) { // file already open +#if defined(QT_CHECK_STATE) + tqWarning( "TQFile::open: File (%s) already open", fn.latin1() ); +#endif + return FALSE; + } + if ( fn.isEmpty() ) { // no file name defined +#if defined(QT_CHECK_NULL) + tqWarning( "TQFile::open: No file name specified" ); +#endif + return FALSE; + } + init(); // reset params + setMode( m ); + if ( !(isReadable() || isWritable()) ) { +#if defined(QT_CHECK_RANGE) + tqWarning( "TQFile::open: File access (%s) not specified", fn.latin1() ); +#endif + return FALSE; + } + bool ok = TRUE; + struct stat st; + if ( isRaw() ) { + int oflags = O_RDONLY; + if ( isReadable() && isWritable() ) + oflags = O_RDWR; + else if ( isWritable() ) + oflags = O_WRONLY; + if ( flags() & IO_Append ) { // append to end of file? + if ( flags() & IO_Truncate ) + oflags |= (O_CREAT | O_TRUNC); + else + oflags |= (O_APPEND | O_CREAT); + setFlags( flags() | IO_WriteOnly ); // append implies write + } else if ( isWritable() ) { // create/trunc if writable + if ( flags() & IO_Truncate ) + oflags |= (O_CREAT | O_TRUNC); + else + oflags |= O_CREAT; + } +#if defined(HAS_TEXT_FILEMODE) + if ( isTranslated() ) + oflags |= OPEN_TEXT; + else + oflags |= OPEN_BINARY; +#endif +#if defined(HAS_ASYNC_FILEMODE) + if ( isAsynchronous() ) + oflags |= OPEN_ASYNC; +#endif + fd = qt_open( TQFile::encodeName(fn), oflags, 0666 ); + + if ( fd != -1 ) { // open successful + ::fstat( fd, &st ); // get the stat for later usage + } else { + ok = FALSE; + } + } else { // buffered file I/O + TQCString perm; + char perm2[4]; + bool try_create = FALSE; + if ( flags() & IO_Append ) { // append to end of file? + setFlags( flags() | IO_WriteOnly ); // append implies write + perm = isReadable() ? "a+" : "a"; + } else { + if ( isReadWrite() ) { + if ( flags() & IO_Truncate ) { + perm = "w+"; + } else { + perm = "r+"; + try_create = TRUE; // try to create if not exists + } + } else if ( isReadable() ) { + perm = "r"; + } else if ( isWritable() ) { + perm = "w"; + } + } + qstrcpy( perm2, perm ); +#if defined(HAS_TEXT_FILEMODE) + if ( isTranslated() ) + strcat( perm2, "t" ); + else + strcat( perm2, "b" ); +#endif + for (;;) { // At most twice + + fh = fopen( TQFile::encodeName(fn), perm2 ); + + if ( !fh && try_create ) { + perm2[0] = 'w'; // try "w+" instead of "r+" + try_create = FALSE; + } else { + break; + } + } + if ( fh ) { + ::fstat( fileno(fh), &st ); // get the stat for later usage + } else { + ok = FALSE; + } + } + if ( ok ) { + setState( IO_Open ); + // on successful open the file stat was got; now test what type + // of file we have + if ( (st.st_mode & S_IFMT) != S_IFREG ) { + // non-seekable + setType( IO_Sequential ); + length = INT_MAX; + ioIndex = 0; + } else { +#if defined(QT_LARGEFILE_SUPPORT) + length = st.st_size > UINT_MAX ? UINT_MAX : (Offset)st.st_size; +#else + length = (Offset)st.st_size; +#endif + ioIndex = (flags() & IO_Append) == 0 ? 0 : length; + if ( !(flags()&IO_Truncate) && length == 0 && isReadable() ) { + // try if you can read from it (if you can, it's a sequential + // device; e.g. a file in the /proc filesystem) + int c = getch(); + if ( c != -1 ) { + ungetch(c); + setType( IO_Sequential ); + length = INT_MAX; + ioIndex = 0; + } + resetStatus(); + } + } + } else { + init(); + if ( errno == EMFILE ) // no more file handles/descrs + setStatus( IO_ResourceError ); + else + setStatus( IO_OpenError ); + setErrorStringErrno( errno ); + } + return ok; +} + +/*! + \overload + Opens a file in the mode \a m using an existing file handle \a f. + Returns TRUE if successful, otherwise FALSE. + + Example: + \code + #include + + void printError( const char* msg ) + { + TQFile f; + f.open( IO_WriteOnly, stderr ); + f.writeBlock( msg, tqstrlen(msg) ); // write to stderr + f.close(); + } + \endcode + + When a TQFile is opened using this function, close() does not actually + close the file, only flushes it. + + \warning If \a f is \c stdin, \c stdout, \c stderr, you may not + be able to seek. See TQIODevice::isSequentialAccess() for more + information. + + \sa close() +*/ + +bool TQFile::open( int m, FILE *f ) +{ + if ( isOpen() ) { +#if defined(QT_CHECK_RANGE) + tqWarning( "TQFile::open: File (%s) already open", fn.latin1() ); +#endif + return FALSE; + } + init(); + setMode( m &~IO_Raw ); + setState( IO_Open ); + fh = f; + ext_f = TRUE; + struct stat st; + ::fstat( fileno(fh), &st ); +#if defined(QT_LARGEFILE_SUPPORT) + off_t tmp = ftello( fh ); + ioIndex = tmp > UINT_MAX ? UINT_MAX : (Offset)tmp; +#else + ioIndex = (Offset)ftell( fh ); +#endif + if ( (st.st_mode & S_IFMT) != S_IFREG || f == stdin ) { //stdin is non seekable + // non-seekable + setType( IO_Sequential ); + length = INT_MAX; + ioIndex = 0; + } else { +#if defined(QT_LARGEFILE_SUPPORT) + length = st.st_size > UINT_MAX ? UINT_MAX : (Offset)st.st_size; +#else + length = (Offset)st.st_size; +#endif + if ( !(flags()&IO_Truncate) && length == 0 && isReadable() ) { + // try if you can read from it (if you can, it's a sequential + // device; e.g. a file in the /proc filesystem) + int c = getch(); + if ( c != -1 ) { + ungetch(c); + setType( IO_Sequential ); + length = INT_MAX; + ioIndex = 0; + } + resetStatus(); + } + } + return TRUE; +} + +/*! + \overload + Opens a file in the mode \a m using an existing file descriptor \a f. + Returns TRUE if successful, otherwise FALSE. + + When a TQFile is opened using this function, close() does not actually + close the file. + + The TQFile that is opened using this function, is automatically set to be in + raw mode; this means that the file input/output functions are slow. If you + run into performance issues, you should try to use one of the other open + functions. + + \warning If \a f is one of 0 (stdin), 1 (stdout) or 2 (stderr), you may not + be able to seek. size() is set to \c INT_MAX (in limits.h). + + \sa close() +*/ + + +bool TQFile::open( int m, int f ) +{ + if ( isOpen() ) { +#if defined(QT_CHECK_RANGE) + tqWarning( "TQFile::open: File (%s) already open", fn.latin1() ); +#endif + return FALSE; + } + init(); + setMode( m |IO_Raw ); + setState( IO_Open ); + fd = f; + ext_f = TRUE; + struct stat st; + ::fstat( fd, &st ); +#if defined(QT_LARGEFILE_SUPPORT) + off_t tmp = ::lseek(fd, 0, SEEK_CUR); + ioIndex = tmp > UINT_MAX ? UINT_MAX : (Offset)tmp; +#else + ioIndex = (Offset)::lseek(fd, 0, SEEK_CUR); +#endif + if ( (st.st_mode & S_IFMT) != S_IFREG || f == 0 ) { // stdin is not seekable... + // non-seekable + setType( IO_Sequential ); + length = INT_MAX; + ioIndex = 0; + } else { +#if defined(QT_LARGEFILE_SUPPORT) + length = st.st_size > UINT_MAX ? UINT_MAX : (Offset)st.st_size; +#else + length = (Offset)st.st_size; +#endif + if ( length == 0 && isReadable() ) { + // try if you can read from it (if you can, it's a sequential + // device; e.g. a file in the /proc filesystem) + int c = getch(); + if ( c != -1 ) { + ungetch(c); + setType( IO_Sequential ); + length = INT_MAX; + ioIndex = 0; + } + resetStatus(); + } + } + return TRUE; +} + +/*! + Returns the file size. + \sa at() +*/ + +TQIODevice::Offset TQFile::size() const +{ + struct stat st; + int ret = 0; + if ( isOpen() ) { + ret = ::fstat( fh ? fileno(fh) : fd, &st ); + } else { + ret = ::stat( TQFile::encodeName(fn), &st ); + } + if ( ret == -1 ) + return 0; +#if defined(QT_LARGEFILE_SUPPORT) + return (uint)st.st_size > UINT_MAX ? UINT_MAX : (Offset)st.st_size; +#else + return st.st_size; +#endif +} + + +/*! + \overload + + Sets the file index to \a pos. Returns TRUE if successful; + otherwise returns FALSE. + + Example: + \code + TQFile f( "data.bin" ); + f.open( IO_ReadOnly ); // index set to 0 + f.at( 100 ); // set index to 100 + f.at( f.at()+50 ); // set index to 150 + f.at( f.size()-80 ); // set index to 80 before EOF + f.close(); + \endcode + + Use \c at() without arguments to retrieve the file offset. + + \warning The result is undefined if the file was open()'ed using + the \c IO_Append specifier. + + \sa size(), open() +*/ + +bool TQFile::at( Offset pos ) +{ + if ( !isOpen() ) { +#if defined(QT_CHECK_STATE) + tqWarning( "TQFile::at: File (%s) is not open", fn.latin1() ); +#endif + return FALSE; + } + if ( isSequentialAccess() ) + return FALSE; + bool ok; + if ( isRaw() ) { + off_t l = ::lseek( fd, pos, SEEK_SET ); + ok = ( l != -1 ); + pos = (Offset)l; + } else { // buffered file +#if defined(QT_LARGEFILE_SUPPORT) + ok = ( ::fseeko(fh, pos, SEEK_SET) == 0 ); +#else + ok = ( ::fseek(fh, pos, SEEK_SET) == 0 ); +#endif + } + if ( ok ) +#if defined(QT_LARGEFILE_SUPPORT) + ioIndex = pos > UINT_MAX ? UINT_MAX : (Offset)pos; +#else + ioIndex = (Offset)pos; +#endif +#if defined(QT_CHECK_RANGE) + else + tqWarning( "TQFile::at: Cannot set file position %lu", pos ); +#endif + return ok; +} + +/*! + \reimp + + \warning We have experienced problems with some C libraries when a buffered + file is opened for both reading and writing. If a read operation takes place + immediately after a write operation, the read buffer contains garbage data. + Worse, the same garbage is written to the file. Calling flush() before + readBlock() solved this problem. +*/ + +TQ_LONG TQFile::readBlock( char *p, TQ_ULONG len ) +{ + if ( !len ) // nothing to do + return 0; + +#if defined(QT_CHECK_NULL) + if ( !p ) + tqWarning( "TQFile::readBlock: Null pointer error" ); +#endif +#if defined(QT_CHECK_STATE) + if ( !isOpen() ) { + tqWarning( "TQFile::readBlock: File (%s) not open", fn.latin1() ); + return -1; + } + if ( !isReadable() ) { + tqWarning( "TQFile::readBlock: Read operation not permitted in file %s ", fn.latin1() ); + return -1; + } +#endif + TQ_ULONG nread = 0; // number of bytes read + if ( !ungetchBuffer.isEmpty() ) { + // need to add these to the returned string. + uint l = ungetchBuffer.length(); + while( nread < l ) { + *p = ungetchBuffer.at( l - nread - 1 ); + p++; + nread++; + } + ungetchBuffer.truncate( l - nread ); + } + + if ( nread < len ) { + if ( isRaw() ) { // raw file + nread += ::read( fd, p, len-nread ); + if ( len && nread <= 0 ) { + nread = 0; + setStatus(IO_ReadError); + setErrorStringErrno( errno ); + } + } else { // buffered file + nread += fread( p, 1, len-nread, fh ); + if ( (uint)nread != len ) { + if ( ferror( fh ) || nread==0 ) { + setStatus(IO_ReadError); + setErrorString( qt_fileerr_read ); + } + } + } + } + if ( !isSequentialAccess() ) + ioIndex += nread; + return nread; +} + + +/*! \reimp + + Writes \a len bytes from \a p to the file and returns the number of + bytes actually written. + + Returns -1 if a serious error occurred. + + \warning When working with buffered files, data may not be written + to the file at once. Call flush() to make sure the data is really + written. + + \sa readBlock() +*/ + +TQ_LONG TQFile::writeBlock( const char *p, TQ_ULONG len ) +{ + if ( !len ) // nothing to do + return 0; + +#if defined(QT_CHECK_NULL) + if ( p == 0 && len != 0 ) + tqWarning( "TQFile::writeBlock: Null pointer error" ); +#endif +#if defined(QT_CHECK_STATE) + if ( !isOpen() ) { // file not open + tqWarning( "TQFile::writeBlock: File (%s) not open", fn.latin1() ); + return -1; + } + if ( !isWritable() ) { // writing not permitted + tqWarning( "TQFile::writeBlock: Write operation not permitted in file %s ", fn.latin1() ); + return -1; + } +#endif + TQ_ULONG nwritten; // number of bytes written + if ( isRaw() ) // raw file + nwritten = ::write( fd, (void *)p, len ); + else // buffered file + nwritten = fwrite( p, 1, len, fh ); + if ( nwritten != len ) { // write error + if ( errno == ENOSPC ) // disk is full + setStatus( IO_ResourceError ); + else + setStatus( IO_WriteError ); + setErrorStringErrno( errno ); + if ( !isSequentialAccess() ) { + if ( isRaw() ) { // recalc file position +#if defined(QT_LARGEFILE_SUPPORT) + off_t tmp = ::lseek( fd, 0, SEEK_CUR ); + ioIndex = tmp > UINT_MAX ? UINT_MAX : (Offset)tmp; +#else + ioIndex = (Offset)::lseek( fd, 0, SEEK_CUR ); +#endif + } else { +#if defined(QT_LARGEFILE_SUPPORT) + off_t tmp = (Offset)::fseeko( fh, 0, SEEK_CUR ); + ioIndex = tmp > UINT_MAX ? UINT_MAX : (Offset)tmp; +#else + ioIndex = (Offset)::fseek( fh, 0, SEEK_CUR ); +#endif + } + } + } else { + if ( !isSequentialAccess() ) + ioIndex += nwritten; + } + if ( ioIndex > length ) // update file length + length = ioIndex; + return nwritten; +} + +/*! + Returns the file handle of the file. + + This is a small positive integer, suitable for use with C library + functions such as fdopen() and fcntl(). On systems that use file + descriptors for sockets (ie. Unix systems, but not Windows) the handle + can be used with TQSocketNotifier as well. + + If the file is not open or there is an error, handle() returns -1. + + \sa TQSocketNotifier +*/ + +int TQFile::handle() const +{ + if ( !isOpen() ) + return -1; + else if ( fh ) + return fileno( fh ); + else + return fd; +} + +/*! + Closes an open file. + + The file is not closed if it was opened with an existing file handle. + If the existing file handle is a \c FILE*, the file is flushed. + If the existing file handle is an \c int file descriptor, nothing + is done to the file. + + Some "write-behind" filesystems may report an unspecified error on + closing the file. These errors only indicate that something may + have gone wrong since the previous open(). In such a case status() + reports IO_UnspecifiedError after close(), otherwise IO_Ok. + + \sa open(), flush() +*/ + + +void TQFile::close() +{ + bool ok = FALSE; + if ( isOpen() ) { // file is not open + if ( fh ) { // buffered file + if ( ext_f ) + ok = fflush( fh ) != -1; // flush instead of closing + else + ok = fclose( fh ) != -1; + } else { // raw file + if ( ext_f ) + ok = TRUE; // cannot close + else + ok = ::close( fd ) != -1; + } + init(); // restore internal state + } + if (!ok) { + setStatus( IO_UnspecifiedError ); + setErrorStringErrno( errno ); + } +} diff --git a/src/tools/tqfiledefs_p.h b/src/tools/tqfiledefs_p.h new file mode 100644 index 000000000..83f84d47b --- /dev/null +++ b/src/tools/tqfiledefs_p.h @@ -0,0 +1,67 @@ +/**************************************************************************** +** +** Common macros and system include files for TQFile, TQFileInfo and TQDir. +** +** Created : 930812 +** +** Copyright (C) 1992-2008 Trolltech ASA. All rights reserved. +** +** This file is part of the tools module of the TQt GUI Toolkit. +** +** This file may be used under the terms of the GNU General +** Public License versions 2.0 or 3.0 as published by the Free +** Software Foundation and appearing in the files LICENSE.GPL2 +** and LICENSE.GPL3 included in the packaging of this file. +** Alternatively you may (at your option) use any later version +** of the GNU General Public License if such license has been +** publicly approved by Trolltech ASA (or its successors, if any) +** and the KDE Free TQt Foundation. +** +** Please review the following information to ensure GNU General +** Public Licensing requirements will be met: +** http://trolltech.com/products/qt/licenses/licensing/opensource/. +** If you are unsure which license is appropriate for your use, please +** review the following information: +** http://trolltech.com/products/qt/licenses/licensing/licensingoverview +** or contact the sales department at sales@trolltech.com. +** +** This file may be used under the terms of the Q Public License as +** defined by Trolltech ASA and appearing in the file LICENSE.TQPL +** included in the packaging of this file. Licensees holding valid TQt +** Commercial licenses may use this file in accordance with the TQt +** Commercial License Agreement provided with the Software. +** +** This file is provided "AS IS" with NO WARRANTY OF ANY KIND, +** INCLUDING THE WARRANTIES OF DESIGN, MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE. Trolltech reserves all rights not granted +** herein. +** +**********************************************************************/ + +#ifndef TQFILEDEFS_P_H +#define TQFILEDEFS_P_H + +// +// W A R N I N G +// ------------- +// +// This file is not part of the TQt API. It exists for the convenience +// of tqfileinfo*.cpp. This header file may change from version to version +// without notice, or even be removed. +// +// We mean it. +// +// + +// Be sure to include qplatformdefs.h first! +struct TQFileInfoCache +{ +#if defined(TQ_WS_WIN) + QT_STATBUF st; +#else + struct stat st; +#endif +}; + + +#endif diff --git a/src/tools/tqfileinfo.cpp b/src/tools/tqfileinfo.cpp new file mode 100644 index 000000000..e9ba95680 --- /dev/null +++ b/src/tools/tqfileinfo.cpp @@ -0,0 +1,704 @@ +/**************************************************************************** +** +** Implementation of TQFileInfo class +** +** Created : 950628 +** +** Copyright (C) 1992-2008 Trolltech ASA. All rights reserved. +** +** This file is part of the tools module of the TQt GUI Toolkit. +** +** This file may be used under the terms of the GNU General +** Public License versions 2.0 or 3.0 as published by the Free +** Software Foundation and appearing in the files LICENSE.GPL2 +** and LICENSE.GPL3 included in the packaging of this file. +** Alternatively you may (at your option) use any later version +** of the GNU General Public License if such license has been +** publicly approved by Trolltech ASA (or its successors, if any) +** and the KDE Free TQt Foundation. +** +** Please review the following information to ensure GNU General +** Public Licensing requirements will be met: +** http://trolltech.com/products/qt/licenses/licensing/opensource/. +** If you are unsure which license is appropriate for your use, please +** review the following information: +** http://trolltech.com/products/qt/licenses/licensing/licensingoverview +** or contact the sales department at sales@trolltech.com. +** +** This file may be used under the terms of the Q Public License as +** defined by Trolltech ASA and appearing in the file LICENSE.TQPL +** included in the packaging of this file. Licensees holding valid TQt +** Commercial licenses may use this file in accordance with the TQt +** Commercial License Agreement provided with the Software. +** +** This file is provided "AS IS" with NO WARRANTY OF ANY KIND, +** INCLUDING THE WARRANTIES OF DESIGN, MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE. Trolltech reserves all rights not granted +** herein. +** +**********************************************************************/ + +#include "qplatformdefs.h" + +#include "tqfileinfo.h" +#include "tqdatetime.h" +#include "tqdir.h" +#include "tqfiledefs_p.h" +#include "tqdeepcopy.h" +#if defined(QT_LARGEFILE_SUPPORT) +#include +#endif + + +extern bool qt_file_access( const TQString& fn, int t ); + +/*! + \class TQFileInfo + \reentrant + \brief The TQFileInfo class provides system-independent file information. + + \ingroup io + + TQFileInfo provides information about a file's name and position + (path) in the file system, its access rights and whether it is a + directory or symbolic link, etc. The file's size and last + modified/read times are also available. + + A TQFileInfo can point to a file with either a relative or an + absolute file path. Absolute file paths begin with the directory + separator "/" (or with a drive specification on Windows). Relative + file names begin with a directory name or a file name and specify + a path relative to the current working directory. An example of an + absolute path is the string "/tmp/quartz". A relative path might + look like "src/fatlib". You can use the function isRelative() to + check whether a TQFileInfo is using a relative or an absolute file + path. You can call the function convertToAbs() to convert a + relative TQFileInfo's path to an absolute path. + + The file that the TQFileInfo works on is set in the constructor or + later with setFile(). Use exists() to see if the file exists and + size() to get its size. + + To speed up performance, TQFileInfo caches information about the + file. Because files can be changed by other users or programs, or + even by other parts of the same program, there is a function that + refreshes the file information: refresh(). If you want to switch + off a TQFileInfo's caching and force it to access the file system + every time you request information from it call setCaching(FALSE). + + The file's type is obtained with isFile(), isDir() and + isSymLink(). The readLink() function provides the name of the file + the symlink points to. + + Elements of the file's name can be extracted with dirPath() and + fileName(). The fileName()'s parts can be extracted with + baseName() and extension(). + + The file's dates are returned by created(), lastModified() and + lastRead(). Information about the file's access permissions is + obtained with isReadable(), isWritable() and isExecutable(). The + file's ownership is available from owner(), ownerId(), group() and + groupId(). You can examine a file's permissions and ownership in a + single statement using the permission() function. + + If you need to read and traverse directories, see the TQDir class. +*/ + +/*! + \enum TQFileInfo::PermissionSpec + + This enum is used by the permission() function to report the + permissions and ownership of a file. The values may be OR-ed + together to test multiple permissions and ownership values. + + \value ReadOwner The file is readable by the owner of the file. + \value WriteOwner The file is writable by the owner of the file. + \value ExeOwner The file is executable by the owner of the file. + \value ReadUser The file is readable by the user. + \value WriteUser The file is writable by the user. + \value ExeUser The file is executable by the user. + \value ReadGroup The file is readable by the group. + \value WriteGroup The file is writable by the group. + \value ExeGroup The file is executable by the group. + \value ReadOther The file is readable by anyone. + \value WriteOther The file is writable by anyone. + \value ExeOther The file is executable by anyone. + + \warning The semantics of \c ReadUser, \c WriteUser and \c ExeUser are + unfortunately not platform independent: on Unix, the rights of the owner of + the file are returned and on Windows the rights of the current user are + returned. This behavior might change in a future TQt version. If you want to + find the rights of the owner of the file, you should use the flags \c + ReadOwner, \c WriteOwner and \c ExeOwner. If you want to find out the + rights of the current user, you should use isReadable(), isWritable() and + isExecutable(). +*/ + + +/*! + Constructs a new empty TQFileInfo. +*/ + +TQFileInfo::TQFileInfo() +{ + fic = 0; + cache = TRUE; +#if defined(Q_OS_UNIX) + symLink = FALSE; +#endif +} + +/*! + Constructs a new TQFileInfo that gives information about the given + file. The \a file can also include an absolute or relative path. + + \warning Some functions might behave in a counter-intuitive way + if \a file has a trailing directory separator. + + \sa setFile(), isRelative(), TQDir::setCurrent(), TQDir::isRelativePath() +*/ + +TQFileInfo::TQFileInfo( const TQString &file ) +{ + fn = file; + slashify( fn ); + fic = 0; + cache = TRUE; +#if defined(Q_OS_UNIX) + symLink = FALSE; +#endif +} + +/*! + Constructs a new TQFileInfo that gives information about file \a + file. + + If the \a file has a relative path, the TQFileInfo will also have a + relative path. + + \sa isRelative() +*/ + +TQFileInfo::TQFileInfo( const TQFile &file ) +{ + fn = file.name(); + slashify( fn ); + fic = 0; + cache = TRUE; +#if defined(Q_OS_UNIX) + symLink = FALSE; +#endif +} + +/*! + Constructs a new TQFileInfo that gives information about the file + called \a fileName in the directory \a d. + + If \a d has a relative path, the TQFileInfo will also have a + relative path. + + \sa isRelative() +*/ +#ifndef TQT_NO_DIR +TQFileInfo::TQFileInfo( const TQDir &d, const TQString &fileName ) +{ + fn = d.filePath( fileName ); + slashify( fn ); + fic = 0; + cache = TRUE; +#if defined(Q_OS_UNIX) + symLink = FALSE; +#endif +} +#endif +/*! + Constructs a new TQFileInfo that is a copy of \a fi. +*/ + +TQFileInfo::TQFileInfo( const TQFileInfo &fi ) +{ + fn = fi.fn; + if ( fi.fic ) { + fic = new TQFileInfoCache; + *fic = *fi.fic; + } else { + fic = 0; + } + cache = fi.cache; +#if defined(Q_OS_UNIX) + symLink = fi.symLink; +#endif +} + +/*! + Destroys the TQFileInfo and frees its resources. +*/ + +TQFileInfo::~TQFileInfo() +{ + delete fic; +} + + +/*! + Makes a copy of \a fi and assigns it to this TQFileInfo. +*/ + +TQFileInfo &TQFileInfo::operator=( const TQFileInfo &fi ) +{ + fn = fi.fn; + if ( !fi.fic ) { + delete fic; + fic = 0; + } else { + if ( !fic ) { + fic = new TQFileInfoCache; + TQ_CHECK_PTR( fic ); + } + *fic = *fi.fic; + } + cache = fi.cache; +#if defined(Q_OS_UNIX) + symLink = fi.symLink; +#endif + return *this; +} + + +/*! + Sets the file that the TQFileInfo provides information about to \a + file. + + The \a file can also include an absolute or relative file path. + Absolute paths begin with the directory separator (e.g. "/" under + Unix) or a drive specification (under Windows). Relative file + names begin with a directory name or a file name and specify a + path relative to the current directory. + + Example: + \code + TQString absolute = "/local/bin"; + TQString relative = "local/bin"; + TQFileInfo absFile( absolute ); + TQFileInfo relFile( relative ); + + TQDir::setCurrent( TQDir::rootDirPath() ); + // absFile and relFile now point to the same file + + TQDir::setCurrent( "/tmp" ); + // absFile now points to "/local/bin", + // while relFile points to "/tmp/local/bin" + \endcode + + \sa isRelative(), TQDir::setCurrent(), TQDir::isRelativePath() +*/ + +void TQFileInfo::setFile( const TQString &file ) +{ + fn = file; + slashify( fn ); + delete fic; + fic = 0; +} + +/*! + \overload + + Sets the file that the TQFileInfo provides information about to \a + file. + + If \a file includes a relative path, the TQFileInfo will also have + a relative path. + + \sa isRelative() +*/ + +void TQFileInfo::setFile( const TQFile &file ) +{ + fn = file.name(); + slashify( fn ); + delete fic; + fic = 0; +} + +/*! + \overload + + Sets the file that the TQFileInfo provides information about to \a + fileName in directory \a d. + + If \a fileName includes a relative path, the TQFileInfo will also + have a relative path. + + \sa isRelative() +*/ +#ifndef TQT_NO_DIR +void TQFileInfo::setFile( const TQDir &d, const TQString &fileName ) +{ + fn = d.filePath( fileName ); + slashify( fn ); + delete fic; + fic = 0; +} +#endif + +/*! + Returns TRUE if the file exists; otherwise returns FALSE. +*/ + +bool TQFileInfo::exists() const +{ + return qt_file_access( fn, F_OK ); +} + +/*! + Refreshes the information about the file, i.e. reads in information + from the file system the next time a cached property is fetched. + + \sa setCaching() +*/ + +void TQFileInfo::refresh() const +{ + TQFileInfo *that = (TQFileInfo*)this; // Mutable function + delete that->fic; + that->fic = 0; +} + +/*! + \fn bool TQFileInfo::caching() const + + Returns TRUE if caching is enabled; otherwise returns FALSE. + + \sa setCaching(), refresh() +*/ + +/*! + If \a enable is TRUE, enables caching of file information. If \a + enable is FALSE caching is disabled. + + When caching is enabled, TQFileInfo reads the file information from + the file system the first time it's needed, but generally not + later. + + Caching is enabled by default. + + \sa refresh(), caching() +*/ + +void TQFileInfo::setCaching( bool enable ) +{ + if ( cache == enable ) + return; + cache = enable; + if ( cache ) { + delete fic; + fic = 0; + } +} + + +/*! + Returns the file name, including the path (which may be absolute + or relative). + + \sa isRelative(), absFilePath() +*/ + +TQString TQFileInfo::filePath() const +{ + return fn; +} + +/*! + Returns the base name of the file. + + If \a complete is FALSE (the default) the base name consists of + all characters in the file name up to (but not including) the \e + first '.' character. + + If \a complete is TRUE the base name consists of all characters in + the file up to (but not including) the \e last '.' character. + + The path is not included in either case. + + Example: + \code + TQFileInfo fi( "/tmp/archive.tar.gz" ); + TQString base = fi.baseName(); // base = "archive" + base = fi.baseName( TRUE ); // base = "archive.tar" + \endcode + + \sa fileName(), extension() +*/ + +TQString TQFileInfo::baseName( bool complete ) const +{ + TQString tmp = fileName(); + int pos = complete ? tmp.findRev( '.' ) : tmp.find( '.' ); + if ( pos == -1 ) + return tmp; + else + return tmp.left( pos ); +} + +/*! + Returns the file's extension name. + + If \a complete is TRUE (the default), extension() returns the + string of all characters in the file name after (but not + including) the first '.' character. + + If \a complete is FALSE, extension() returns the string of all + characters in the file name after (but not including) the last '.' + character. + + Example: + \code + TQFileInfo fi( "/tmp/archive.tar.gz" ); + TQString ext = fi.extension(); // ext = "tar.gz" + ext = fi.extension( FALSE ); // ext = "gz" + \endcode + + \sa fileName(), baseName() +*/ + +TQString TQFileInfo::extension( bool complete ) const +{ + TQString s = fileName(); + int pos = complete ? s.find( '.' ) : s.findRev( '.' ); + if ( pos < 0 ) + return TQString::fromLatin1( "" ); + else + return s.right( s.length() - pos - 1 ); +} + +/*! + Returns the file's path as a TQDir object. + + If the TQFileInfo is relative and \a absPath is FALSE, the TQDir + will be relative; otherwise it will be absolute. + + \sa dirPath(), filePath(), fileName(), isRelative() +*/ +#ifndef TQT_NO_DIR +TQDir TQFileInfo::dir( bool absPath ) const +{ + return TQDir( dirPath(absPath) ); +} +#endif + + +/*! + Returns TRUE if the file is readable; otherwise returns FALSE. + + \sa isWritable(), isExecutable(), permission() +*/ + +bool TQFileInfo::isReadable() const +{ +#ifdef TQ_WS_WIN + return qt_file_access( fn, R_OK ) && permission( ReadUser ); +#else + return qt_file_access( fn, R_OK ); +#endif +} + +/*! + Returns TRUE if the file is writable; otherwise returns FALSE. + + \sa isReadable(), isExecutable(), permission() +*/ + +bool TQFileInfo::isWritable() const +{ +#ifdef TQ_WS_WIN + return qt_file_access( fn, W_OK ) && permission( WriteUser ); +#else + return qt_file_access( fn, W_OK ); +#endif +} + +/*! + Returns TRUE if the file is executable; otherwise returns FALSE. + + \sa isReadable(), isWritable(), permission() +*/ + +bool TQFileInfo::isExecutable() const +{ +#ifdef TQ_WS_WIN +#if defined(_MSC_VER) && _MSC_VER >= 1400 + return permission( ExeUser ); +#else + return qt_file_access( fn, X_OK ) && permission( ExeUser ); +#endif //_MSC_VER >= 1400 +#else + return qt_file_access( fn, X_OK ); +#endif +} + +#ifndef TQ_WS_WIN +bool TQFileInfo::isHidden() const +{ + return fileName()[ 0 ] == TQChar( '.' ); +} +#endif + +/*! + Returns TRUE if the file path name is relative. Returns FALSE if + the path is absolute (e.g. under Unix a path is absolute if it + begins with a "/"). +*/ +#ifndef TQT_NO_DIR +bool TQFileInfo::isRelative() const +{ + return TQDir::isRelativePath( fn ); +} + +/*! + Converts the file's path to an absolute path. + + If it is already absolute, nothing is done. + + \sa filePath(), isRelative() +*/ + +bool TQFileInfo::convertToAbs() +{ + if ( isRelative() ) + fn = absFilePath(); + return TQDir::isRelativePath( fn ); +} +#endif + +/*! + Returns the file size in bytes, or 0 if the file does not exist or + if the size is 0 or if the size cannot be fetched. +*/ +uint TQFileInfo::size() const +{ + if ( !fic || !cache ) + doStat(); + if ( fic ) +#if defined(QT_LARGEFILE_SUPPORT) + return (uint)fic->st.st_size > UINT_MAX ? UINT_MAX : (uint)fic->st.st_size; +#else + return (uint)fic->st.st_size; +#endif + else + return 0; +} + +/*! + Returns the date and time when the file was created. + + On platforms where this information is not available, returns the + same as lastModified(). + + \sa created() lastModified() lastRead() +*/ + +TQDateTime TQFileInfo::created() const +{ + TQDateTime dt; + if ( !fic || !cache ) + doStat(); + if ( fic && fic->st.st_ctime != 0 ) { + dt.setTime_t( fic->st.st_ctime ); + return dt; + } else { + return lastModified(); + } +} + +/*! + Returns the date and time when the file was last modified. + + \sa created() lastModified() lastRead() +*/ + +TQDateTime TQFileInfo::lastModified() const +{ + TQDateTime dt; + if ( !fic || !cache ) + doStat(); + if ( fic ) + dt.setTime_t( fic->st.st_mtime ); + return dt; +} + +/*! + Returns the date and time when the file was last read (accessed). + + On platforms where this information is not available, returns the + same as lastModified(). + + \sa created() lastModified() lastRead() +*/ + +TQDateTime TQFileInfo::lastRead() const +{ + TQDateTime dt; + if ( !fic || !cache ) + doStat(); + if ( fic && fic->st.st_atime != 0 ) { + dt.setTime_t( fic->st.st_atime ); + return dt; + } else { + return lastModified(); + } +} + +#ifndef TQT_NO_DIR + +/*! + Returns the absolute path including the file name. + + The absolute path name consists of the full path and the file + name. On Unix this will always begin with the root, '/', + directory. On Windows this will always begin 'D:/' where D is a + drive letter, except for network shares that are not mapped to a + drive letter, in which case the path will begin '//sharename/'. + + This function returns the same as filePath(), unless isRelative() + is TRUE. + + If the TQFileInfo is empty it returns TQDir::currentDirPath(). + + This function can be time consuming under Unix (in the order of + milliseconds). + + \sa isRelative(), filePath() +*/ +TQString TQFileInfo::absFilePath() const +{ + TQString tmp; + if ( TQDir::isRelativePath(fn) +#if defined(Q_OS_WIN32) + && fn[1] != ':' +#endif + ) { + tmp = TQDir::currentDirPath(); + tmp += '/'; + } + tmp += fn; + makeAbs( tmp ); + return TQDir::cleanDirPath( tmp ); +} + +/*! \internal + Detaches all internal data. +*/ +void TQFileInfo::detach() +{ + fn = TQDeepCopy( fn ); + if ( fic ) { + TQFileInfoCache *cur = fic; + fic = new TQFileInfoCache; + *fic = *cur; + delete cur; + } +} + +#endif diff --git a/src/tools/tqfileinfo.h b/src/tools/tqfileinfo.h new file mode 100644 index 000000000..41a764481 --- /dev/null +++ b/src/tools/tqfileinfo.h @@ -0,0 +1,151 @@ +/**************************************************************************** +** +** Definition of TQFileInfo class +** +** Created : 950628 +** +** Copyright (C) 1992-2008 Trolltech ASA. All rights reserved. +** +** This file is part of the tools module of the TQt GUI Toolkit. +** +** This file may be used under the terms of the GNU General +** Public License versions 2.0 or 3.0 as published by the Free +** Software Foundation and appearing in the files LICENSE.GPL2 +** and LICENSE.GPL3 included in the packaging of this file. +** Alternatively you may (at your option) use any later version +** of the GNU General Public License if such license has been +** publicly approved by Trolltech ASA (or its successors, if any) +** and the KDE Free TQt Foundation. +** +** Please review the following information to ensure GNU General +** Public Licensing requirements will be met: +** http://trolltech.com/products/qt/licenses/licensing/opensource/. +** If you are unsure which license is appropriate for your use, please +** review the following information: +** http://trolltech.com/products/qt/licenses/licensing/licensingoverview +** or contact the sales department at sales@trolltech.com. +** +** This file may be used under the terms of the Q Public License as +** defined by Trolltech ASA and appearing in the file LICENSE.TQPL +** included in the packaging of this file. Licensees holding valid TQt +** Commercial licenses may use this file in accordance with the TQt +** Commercial License Agreement provided with the Software. +** +** This file is provided "AS IS" with NO WARRANTY OF ANY KIND, +** INCLUDING THE WARRANTIES OF DESIGN, MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE. Trolltech reserves all rights not granted +** herein. +** +**********************************************************************/ + +#ifndef TQFILEINFO_H +#define TQFILEINFO_H + +#ifndef QT_H +#include "tqfile.h" +#include "tqdatetime.h" +#endif // QT_H + + +class TQDir; +struct TQFileInfoCache; +template class TQDeepCopy; + + +class TQ_EXPORT TQFileInfo +{ +public: + enum PermissionSpec { + ReadOwner = 04000, WriteOwner = 02000, ExeOwner = 01000, + ReadUser = 00400, WriteUser = 00200, ExeUser = 00100, + ReadGroup = 00040, WriteGroup = 00020, ExeGroup = 00010, + ReadOther = 00004, WriteOther = 00002, ExeOther = 00001 }; + + TQFileInfo(); + TQFileInfo( const TQString &file ); + TQFileInfo( const TQFile & ); +#ifndef TQT_NO_DIR + TQFileInfo( const TQDir &, const TQString &fileName ); +#endif + TQFileInfo( const TQFileInfo & ); + ~TQFileInfo(); + + TQFileInfo &operator=( const TQFileInfo & ); + + void setFile( const TQString &file ); + void setFile( const TQFile & ); +#ifndef TQT_NO_DIR + void setFile( const TQDir &, const TQString &fileName ); +#endif + bool exists() const; + void refresh() const; + bool caching() const; + void setCaching( bool ); + + TQString filePath() const; + TQString fileName() const; +#ifndef TQT_NO_DIR //### + TQString absFilePath() const; +#endif + TQString baseName( bool complete = FALSE ) const; + TQString extension( bool complete = TRUE ) const; + +#ifndef TQT_NO_DIR //### + TQString dirPath( bool absPath = FALSE ) const; +#endif +#ifndef TQT_NO_DIR + TQDir dir( bool absPath = FALSE ) const; +#endif + bool isReadable() const; + bool isWritable() const; + bool isExecutable() const; + bool isHidden() const; + +#ifndef TQT_NO_DIR //### + bool isRelative() const; + bool convertToAbs(); +#endif + + bool isFile() const; + bool isDir() const; + bool isSymLink() const; + + TQString readLink() const; + + TQString owner() const; + uint ownerId() const; + TQString group() const; + uint groupId() const; + + bool permission( int permissionSpec ) const; + + uint size() const; + + TQDateTime created() const; + TQDateTime lastModified() const; + TQDateTime lastRead() const; + +private: + void doStat() const; + static void slashify( TQString & ); + static void makeAbs( TQString & ); + + TQString fn; + TQFileInfoCache *fic; + bool cache; +#if defined(Q_OS_UNIX) + bool symLink; +#endif + + void detach(); + friend class TQDeepCopy< TQFileInfo >; +}; + + +inline bool TQFileInfo::caching() const +{ + return cache; +} + + +#endif // TQFILEINFO_H diff --git a/src/tools/tqfileinfo_unix.cpp b/src/tools/tqfileinfo_unix.cpp new file mode 100644 index 000000000..300515e3a --- /dev/null +++ b/src/tools/tqfileinfo_unix.cpp @@ -0,0 +1,400 @@ +/**************************************************************************** +** +** Implementation of TQFileInfo class +** +** Created : 950628 +** +** Copyright (C) 1992-2008 Trolltech ASA. All rights reserved. +** +** This file is part of the tools module of the TQt GUI Toolkit. +** +** This file may be used under the terms of the GNU General +** Public License versions 2.0 or 3.0 as published by the Free +** Software Foundation and appearing in the files LICENSE.GPL2 +** and LICENSE.GPL3 included in the packaging of this file. +** Alternatively you may (at your option) use any later version +** of the GNU General Public License if such license has been +** publicly approved by Trolltech ASA (or its successors, if any) +** and the KDE Free TQt Foundation. +** +** Please review the following information to ensure GNU General +** Public Licensing requirements will be met: +** http://trolltech.com/products/qt/licenses/licensing/opensource/. +** If you are unsure which license is appropriate for your use, please +** review the following information: +** http://trolltech.com/products/qt/licenses/licensing/licensingoverview +** or contact the sales department at sales@trolltech.com. +** +** This file may be used under the terms of the Q Public License as +** defined by Trolltech ASA and appearing in the file LICENSE.TQPL +** included in the packaging of this file. Licensees holding valid TQt +** Commercial licenses may use this file in accordance with the TQt +** Commercial License Agreement provided with the Software. +** +** This file is provided "AS IS" with NO WARRANTY OF ANY KIND, +** INCLUDING THE WARRANTIES OF DESIGN, MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE. Trolltech reserves all rights not granted +** herein. +** +**********************************************************************/ + +#include "qplatformdefs.h" +#include "tqfileinfo.h" +#include "tqfiledefs_p.h" +#include "tqdatetime.h" +#include "tqdir.h" + +#include +#if defined(Q_OS_MAC) +# include +#endif +#if defined(Q_OS_HURD) +# include +#endif + +void TQFileInfo::slashify( TQString& ) +{ + return; +} + + +void TQFileInfo::makeAbs( TQString & ) +{ + return; +} + +/*! + Returns TRUE if this object points to a file. Returns FALSE if the + object points to something which isn't a file, e.g. a directory or + a symlink. + + \sa isDir(), isSymLink() +*/ +bool TQFileInfo::isFile() const +{ + if ( !fic || !cache ) + doStat(); + return fic ? (fic->st.st_mode & S_IFMT) == S_IFREG : FALSE; +} + +/*! + Returns TRUE if this object points to a directory or to a symbolic + link to a directory; otherwise returns FALSE. + + \sa isFile(), isSymLink() +*/ +bool TQFileInfo::isDir() const +{ + if ( !fic || !cache ) + doStat(); + return fic ? (fic->st.st_mode & S_IFMT) == S_IFDIR : FALSE; +} + +/*! + Returns TRUE if this object points to a symbolic link (or to a + shortcut on Windows, or an alias on Mac OS X); otherwise returns + FALSE. + + \sa isFile(), isDir(), readLink() +*/ + +bool TQFileInfo::isSymLink() const +{ + if ( !fic || !cache ) + doStat(); + if(symLink) + return TRUE; +#if defined(Q_OS_MAC) + { + FSRef fref; + if(FSPathMakeRef((const UInt8 *)TQFile::encodeName(fn).data(), &fref, NULL) == noErr) { + Boolean isAlias, isFolder; + if(FSIsAliasFile(&fref, &isAlias, &isFolder) == noErr) + return isAlias; + } + } +#endif + return FALSE; +} + +/*! + Returns the name a symlink (or shortcut on Windows) points to, or + a TQString::null if the object isn't a symbolic link. + + This name may not represent an existing file; it is only a string. + TQFileInfo::exists() returns TRUE if the symlink points to an + existing file. + + \sa exists(), isSymLink(), isDir(), isFile() +*/ + +TQString TQFileInfo::readLink() const +{ + if ( !isSymLink() ) + return TQString(); +#if defined(Q_OS_UNIX) && !defined(Q_OS_OS2EMX) +#if !defined(PATH_MAX) + int size = 256; + char *s = NULL, *s2; + + while (1) + { + s2 = (char *) realloc (s, size); + if (s2 == NULL) { + free( s ); + return TQString(); + } + s = s2; + int len = readlink ( TQFile::encodeName(fn).data(), s, size ); + if ( len < 0 ) { + free( s ); + return TQString(); + } + if ( len < size ) { + s[len] = '\0'; + TQString str = TQFile::decodeName(s); + free(s); + return str; + } + size *= 2; + } +#else + char s[PATH_MAX+1]; + int len = readlink( TQFile::encodeName(fn).data(), s, PATH_MAX ); + if ( len >= 0 ) { + s[len] = '\0'; + return TQFile::decodeName(s); + } +#endif /* !PATH_MAX */ +#endif /* Q_OS_UNIX && !Q_OS_OS2EMX */ +#if defined(Q_OS_MAC) + { + FSRef fref; + if(FSPathMakeRef((const UInt8 *)TQFile::encodeName(fn).data(), &fref, NULL) == noErr) { + Boolean isAlias, isFolder; + if(FSResolveAliasFile(&fref, TRUE, &isFolder, &isAlias) == noErr && isAlias) { + AliasHandle alias; + if(FSNewAlias(0, &fref, &alias) == noErr && alias) { + CFStringRef cfstr; + if(FSCopyAliasInfo(alias, 0, 0, &cfstr, 0, 0) == noErr) { + TQString cfstring2qstring(CFStringRef str); //qglobal.cpp + return cfstring2qstring(cfstr); + } + } + } + } + } +#endif + return TQString(); +} + +static const uint nobodyID = (uint) -2; + +/*! + Returns the owner of the file. On systems where files + do not have owners, or if an error occurs, TQString::null is + returned. + + This function can be time consuming under Unix (in the order of + milliseconds). + + \sa ownerId(), group(), groupId() +*/ + +TQString TQFileInfo::owner() const +{ + passwd *pw = getpwuid( ownerId() ); + if ( pw ) + return TQFile::decodeName( pw->pw_name ); + return TQString::null; +} + +/*! + Returns the id of the owner of the file. + + On Windows and on systems where files do not have owners this + function returns ((uint) -2). + + \sa owner(), group(), groupId() +*/ + +uint TQFileInfo::ownerId() const +{ + if ( !fic || !cache ) + doStat(); + if ( fic ) + return fic->st.st_uid; + return nobodyID; +} + +/*! + Returns the group of the file. On Windows, on systems where files + do not have groups, or if an error occurs, TQString::null is + returned. + + This function can be time consuming under Unix (in the order of + milliseconds). + + \sa groupId(), owner(), ownerId() +*/ + +TQString TQFileInfo::group() const +{ + struct group *gr = getgrgid( groupId() ); + if ( gr ) + return TQFile::decodeName( gr->gr_name ); + return TQString::null; +} + +/*! + Returns the id of the group the file belongs to. + + On Windows and on systems where files do not have groups this + function always returns (uint) -2. + + \sa group(), owner(), ownerId() +*/ + +uint TQFileInfo::groupId() const +{ + if ( !fic || !cache ) + doStat(); + if ( fic ) + return fic->st.st_gid; + return nobodyID; +} + + +/*! + Tests for file permissions. The \a permissionSpec argument can be + several flags of type \c PermissionSpec OR-ed together to check + for permission combinations. + + On systems where files do not have permissions this function + always returns TRUE. + + Example: + \code + TQFileInfo fi( "/tmp/archive.tar.gz" ); + if ( fi.permission( TQFileInfo::WriteUser | TQFileInfo::ReadGroup ) ) + tqWarning( "I can change the file; my group can read the file" ); + if ( fi.permission( TQFileInfo::WriteGroup | TQFileInfo::WriteOther ) ) + tqWarning( "The group or others can change the file" ); + \endcode + + \sa isReadable(), isWritable(), isExecutable() +*/ + +bool TQFileInfo::permission( int permissionSpec ) const +{ + if ( !fic || !cache ) + doStat(); + if ( fic ) { + uint mask = 0; + if ( permissionSpec & ReadOwner ) + mask |= S_IRUSR; + if ( permissionSpec & WriteOwner ) + mask |= S_IWUSR; + if ( permissionSpec & ExeOwner ) + mask |= S_IXUSR; + if ( permissionSpec & ReadUser ) + mask |= S_IRUSR; + if ( permissionSpec & WriteUser ) + mask |= S_IWUSR; + if ( permissionSpec & ExeUser ) + mask |= S_IXUSR; + if ( permissionSpec & ReadGroup ) + mask |= S_IRGRP; + if ( permissionSpec & WriteGroup ) + mask |= S_IWGRP; + if ( permissionSpec & ExeGroup ) + mask |= S_IXGRP; + if ( permissionSpec & ReadOther ) + mask |= S_IROTH; + if ( permissionSpec & WriteOther ) + mask |= S_IWOTH; + if ( permissionSpec & ExeOther ) + mask |= S_IXOTH; + if ( mask ) { + return (fic->st.st_mode & mask) == mask; + } else { +#if defined(QT_CHECK_NULL) + tqWarning( "TQFileInfo::permission: permissionSpec is 0" ); +#endif + return TRUE; + } + } else { + return FALSE; + } +} + +void TQFileInfo::doStat() const +{ + TQFileInfo *that = ((TQFileInfo*)this); // mutable function + if ( !that->fic ) + that->fic = new TQFileInfoCache; + that->symLink = FALSE; + struct stat *b = &that->fic->st; +#if defined(Q_OS_UNIX) && defined(S_IFLNK) + if ( ::lstat( TQFile::encodeName(fn), b ) == 0 ) { + if ( S_ISLNK( b->st_mode ) ) + that->symLink = TRUE; + else + return; + } +#endif + + int r = ::stat( TQFile::encodeName(fn), b ); + if ( r != 0 && !that->symLink ) { + delete that->fic; + that->fic = 0; + } +} + +/*! + Returns the file's path. + + If \a absPath is TRUE an absolute path is returned. + + \sa dir(), filePath(), fileName(), isRelative() +*/ +#ifndef TQT_NO_DIR +TQString TQFileInfo::dirPath( bool absPath ) const +{ + TQString s; + if ( absPath ) + s = absFilePath(); + else + s = fn; + int pos = s.findRev( '/' ); + if ( pos == -1 ) { + return TQString::fromLatin1( "." ); + } else { + if ( pos == 0 ) + return TQString::fromLatin1( "/" ); + return s.left( pos ); + } +} +#endif + +/*! + Returns the name of the file, excluding the path. + + Example: + \code + TQFileInfo fi( "/tmp/archive.tar.gz" ); + TQString name = fi.fileName(); // name = "archive.tar.gz" + \endcode + + \sa isRelative(), filePath(), baseName(), extension() +*/ + +TQString TQFileInfo::fileName() const +{ + int p = fn.findRev( '/' ); + if ( p == -1 ) { + return fn; + } else { + return fn.mid( p + 1 ); + } +} diff --git a/src/tools/tqiodevice.cpp b/src/tools/tqiodevice.cpp new file mode 100644 index 000000000..014a18d46 --- /dev/null +++ b/src/tools/tqiodevice.cpp @@ -0,0 +1,759 @@ +/**************************************************************************** +** +** Implementation of TQIODevice class +** +** Created : 940913 +** +** Copyright (C) 1992-2008 Trolltech ASA. All rights reserved. +** +** This file is part of the tools module of the TQt GUI Toolkit. +** +** This file may be used under the terms of the GNU General +** Public License versions 2.0 or 3.0 as published by the Free +** Software Foundation and appearing in the files LICENSE.GPL2 +** and LICENSE.GPL3 included in the packaging of this file. +** Alternatively you may (at your option) use any later version +** of the GNU General Public License if such license has been +** publicly approved by Trolltech ASA (or its successors, if any) +** and the KDE Free TQt Foundation. +** +** Please review the following information to ensure GNU General +** Public Licensing requirements will be met: +** http://trolltech.com/products/qt/licenses/licensing/opensource/. +** If you are unsure which license is appropriate for your use, please +** review the following information: +** http://trolltech.com/products/qt/licenses/licensing/licensingoverview +** or contact the sales department at sales@trolltech.com. +** +** This file may be used under the terms of the Q Public License as +** defined by Trolltech ASA and appearing in the file LICENSE.TQPL +** included in the packaging of this file. Licensees holding valid TQt +** Commercial licenses may use this file in accordance with the TQt +** Commercial License Agreement provided with the Software. +** +** This file is provided "AS IS" with NO WARRANTY OF ANY KIND, +** INCLUDING THE WARRANTIES OF DESIGN, MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE. Trolltech reserves all rights not granted +** herein. +** +**********************************************************************/ + +#include "tqiodevice.h" + +/*! + \class TQIODevice tqiodevice.h + \reentrant + + \brief The TQIODevice class is the base class of I/O devices. + + \ingroup io + + An I/O device represents a medium that one can read bytes from + and/or write bytes to. The TQIODevice class is the abstract + superclass of all such devices; classes such as TQFile, TQBuffer and + TQSocket inherit TQIODevice and implement virtual functions such as + write() appropriately. + + Although applications sometimes use TQIODevice directly, it is + usually better to use TQTextStream and TQDataStream, which provide + stream operations on any TQIODevice subclass. TQTextStream provides + text-oriented stream functionality (for human-readable ASCII + files, for example), whereas TQDataStream deals with binary data in + a totally platform-independent manner. + + The public member functions in TQIODevice roughly fall into two + groups: the action functions and the state access functions. The + most important action functions are: + + \list + + \i open() opens a device for reading and/or writing, depending on + the mode argument. + + \i close() closes the device and tidies up (e.g. flushes buffered + data) + + \i readBlock() reads a block of data from the device. + + \i writeBlock() writes a block of data to the device. + + \i readLine() reads a line (of text, usually) from the device. + + \i flush() ensures that all buffered data are written to the real device. + + \endlist + + There are also some other, less used, action functions: + + \list + + \i getch() reads a single character. + + \i ungetch() forgets the last call to getch(), if possible. + + \i putch() writes a single character. + + \i size() returns the size of the device, if there is one. + + \i at() returns the current read/write pointer's position, if there + is one for this device, or it moves the pointer if given an offset. + + \i atEnd() indicates whether there is more to read, if this is + meaningful for this device. + + \i reset() moves the read/write pointer to the start of the + device, if that is possible for this device. + + \endlist + + The state access are all "get" functions. The TQIODevice subclass + calls setState() to update the state, and simple access functions + tell the user of the device what the device's state is. Here are + the settings, and their associated access functions: + + \list + + \i Access type. Some devices are direct access (it is possible + to read/write anywhere), whereas others are sequential. TQIODevice + provides the access functions (isDirectAccess(), + isSequentialAccess(), and isCombinedAccess()) to tell users what a + given I/O device supports. + + \i Buffering. Some devices are accessed in raw mode, whereas + others are buffered. Buffering usually provides greater + efficiency, particularly for small read/write operations. + isBuffered() tells the user whether a given device is buffered. + (This can often be set by the application in the call to open().) + + \i Synchronicity. Synchronous devices work immediately (for + example, files). When you read from a file, the file delivers its + data straight away. Other kinds of device, such as a socket + connected to a HTTP server, may not deliver the data until seconds + after you ask to read it. isSynchronous() and isAsynchronous() + tell the user how this device operates. + + \i CR/LF translation. For simplicity, applications often like to + see just a single CR/LF style, and TQIODevice subclasses can + provide this. isTranslated() returns TRUE if this object + translates CR/LF to just LF. (This can often be set by the + application in the call to open().) + + \i Permissions. Some files cannot be written. For example, + isReadable(), isWritable() and isReadWrite() tell the application + whether it can read from and write to a given device. (This can + often be set by the application in the call to open().) + + \i Finally, isOpen() returns TRUE if the device is open, i.e. + after an open() call. + + \endlist + + TQIODevice provides numerous pure virtual functions that you need + to implement when subclassing it. Here is a skeleton subclass with + all the members you are sure to need and some that you will + probably need: + + \code + class MyDevice : public TQIODevice + { + public: + MyDevice(); + ~MyDevice(); + + bool open( int mode ); + void close(); + void flush(); + + uint size() const; + int at() const; // non-pure virtual + bool at( int ); // non-pure virtual + bool atEnd() const; // non-pure virtual + + int readBlock( char *data, uint maxlen ); + int writeBlock( const char *data, uint len ); + int readLine( char *data, uint maxlen ); + + int getch(); + int putch( int ); + int ungetch( int ); + }; + \endcode + + The three non-pure virtual functions need not be reimplemented for + sequential devices. + + \sa TQDataStream, TQTextStream +*/ + +/*! + \enum TQIODevice::Offset + + The offset within the device. +*/ + + +/*! + Constructs an I/O device. +*/ + +TQIODevice::TQIODevice() +{ + ioMode = 0; // initial mode + ioSt = IO_Ok; + ioIndex = 0; +} + +/*! + Destroys the I/O device. +*/ + +TQIODevice::~TQIODevice() +{ +} + + +/*! + \fn int TQIODevice::flags() const + + Returns the current I/O device flags setting. + + Flags consists of mode flags and state flags. + + \sa mode(), state() +*/ + +/*! + \fn int TQIODevice::mode() const + + Returns bits OR'ed together that specify the current operation + mode. + + These are the flags that were given to the open() function. + + The flags are \c IO_ReadOnly, \c IO_WriteOnly, \c IO_ReadWrite, + \c IO_Append, \c IO_Truncate and \c IO_Translate. +*/ + +/*! + \fn int TQIODevice::state() const + + Returns bits OR'ed together that specify the current state. + + The flags are: \c IO_Open. + + Subclasses may define additional flags. +*/ + +/*! + \fn bool TQIODevice::isDirectAccess() const + + Returns TRUE if the I/O device is a direct access device; + otherwise returns FALSE, i.e. if the device is a sequential access + device. + + \sa isSequentialAccess() +*/ + +/*! + \fn bool TQIODevice::isSequentialAccess() const + + Returns TRUE if the device is a sequential access device; + otherwise returns FALSE, i.e. if the device is a direct access + device. + + Operations involving size() and at(int) are not valid on + sequential devices. + + \sa isDirectAccess() +*/ + +/*! + \fn bool TQIODevice::isCombinedAccess() const + + Returns TRUE if the I/O device is a combined access (both direct + and sequential) device; otherwise returns FALSE. + + This access method is currently not in use. +*/ + +/*! + \fn bool TQIODevice::isBuffered() const + + Returns TRUE if the I/O device is a buffered device; otherwise + returns FALSE, i.e. the device is a raw device. + + \sa isRaw() +*/ + +/*! + \fn bool TQIODevice::isRaw() const + + Returns TRUE if the device is a raw device; otherwise returns + FALSE, i.e. if the device is a buffered device. + + \sa isBuffered() +*/ + +/*! + \fn bool TQIODevice::isSynchronous() const + + Returns TRUE if the I/O device is a synchronous device; otherwise + returns FALSE, i.e. the device is an asynchronous device. + + \sa isAsynchronous() +*/ + +/*! + \fn bool TQIODevice::isAsynchronous() const + + Returns TRUE if the device is an asynchronous device; otherwise + returns FALSE, i.e. if the device is a synchronous device. + + This mode is currently not in use. + + \sa isSynchronous() +*/ + +/*! + \fn bool TQIODevice::isTranslated() const + + Returns TRUE if the I/O device translates carriage-return and + linefeed characters; otherwise returns FALSE. + + A TQFile is translated if it is opened with the \c IO_Translate + mode flag. +*/ + +/*! + \fn bool TQIODevice::isReadable() const + + Returns TRUE if the I/O device was opened using \c IO_ReadOnly or + \c IO_ReadWrite mode; otherwise returns FALSE. + + \sa isWritable(), isReadWrite() +*/ + +/*! + \fn bool TQIODevice::isWritable() const + + Returns TRUE if the I/O device was opened using \c IO_WriteOnly or + \c IO_ReadWrite mode; otherwise returns FALSE. + + \sa isReadable(), isReadWrite() +*/ + +/*! + \fn bool TQIODevice::isReadWrite() const + + Returns TRUE if the I/O device was opened using \c IO_ReadWrite + mode; otherwise returns FALSE. + + \sa isReadable(), isWritable() +*/ + +/*! + \fn bool TQIODevice::isInactive() const + + Returns TRUE if the I/O device state is 0, i.e. the device is not + open; otherwise returns FALSE. + + \sa isOpen() +*/ + +/*! + \fn bool TQIODevice::isOpen() const + + Returns TRUE if the I/O device has been opened; otherwise returns + FALSE. + + \sa isInactive() +*/ + + +/*! + \fn int TQIODevice::status() const + + Returns the I/O device status. + + The I/O device status returns an error code. If open() returns + FALSE or readBlock() or writeBlock() return -1, this function can + be called to find out the reason why the operation failed. + + \keyword IO_Ok + \keyword IO_ReadError + \keyword IO_WriteError + \keyword IO_FatalError + \keyword IO_OpenError + \keyword IO_ConnectError + \keyword IO_AbortError + \keyword IO_TimeOutError + \keyword IO_UnspecifiedError + + The status codes are: + \table + \header \i Status code \i Meaning + \row \i \c IO_Ok \i The operation was successful. + \row \i \c IO_ReadError \i Could not read from the device. + \row \i \c IO_WriteError \i Could not write to the device. + \row \i \c IO_FatalError \i A fatal unrecoverable error occurred. + \row \i \c IO_OpenError \i Could not open the device. + \row \i \c IO_ConnectError \i Could not connect to the device. + \row \i \c IO_AbortError \i The operation was unexpectedly aborted. + \row \i \c IO_TimeOutError \i The operation timed out. + \row \i \c IO_UnspecifiedError \i An unspecified error happened on close. + \endtable + + \sa resetStatus() +*/ + +/*! + \fn void TQIODevice::resetStatus() + + Sets the I/O device status to \c IO_Ok. + + \sa status() +*/ + + +/*! + \fn void TQIODevice::setFlags( int flags ) + + Used by subclasses to set the device flags to the \a flags specified. +*/ + +/*! + \fn void TQIODevice::setType( int type ) + + Used by subclasses to set the device type to the \a type specified. +*/ + +void TQIODevice::setType( int t ) +{ +#if defined(QT_CHECK_RANGE) + if ( (t & IO_TypeMask) != t ) + tqWarning( "TQIODevice::setType: Specified type out of range" ); +#endif + ioMode &= ~IO_TypeMask; // reset type bits + ioMode |= t; +} + +/*! + \fn void TQIODevice::setMode( int mode ) + + Used by subclasses to set the device mode to the \a mode specified. +*/ + +void TQIODevice::setMode( int m ) +{ +#if defined(QT_CHECK_RANGE) + if ( (m & IO_ModeMask) != m ) + tqWarning( "TQIODevice::setMode: Specified mode out of range" ); +#endif + ioMode &= ~IO_ModeMask; // reset mode bits + ioMode |= m; +} + +/*! + \fn void TQIODevice::setState( int state ) + + Used by subclasses to set the device state to the \a state specified. +*/ + +void TQIODevice::setState( int s ) +{ +#if defined(QT_CHECK_RANGE) + if ( ((uint)s & IO_StateMask) != (uint)s ) + tqWarning( "TQIODevice::setState: Specified state out of range" ); +#endif + ioMode &= ~IO_StateMask; // reset state bits + ioMode |= (uint)s; +} + +/*! + Used by subclasses to set the device status (not state) to \a s. +*/ + +void TQIODevice::setStatus( int s ) +{ + ioSt = s; +} + + +/*! + \fn bool TQIODevice::open( int mode ) + + Opens the I/O device using the specified \a mode. Returns TRUE if + the device was successfully opened; otherwise returns FALSE. + + The mode parameter \a mode must be an OR'ed combination of the + following flags. + \table + \header \i Mode flags \i Meaning + \row \i \c IO_Raw \i specifies raw (unbuffered) file access. + \row \i \c IO_ReadOnly \i opens a file in read-only mode. + \row \i \c IO_WriteOnly \i opens a file in write-only mode. + \row \i \c IO_ReadWrite \i opens a file in read/write mode. + \row \i \c IO_Append \i sets the file index to the end of the file. + \row \i \c IO_Truncate \i truncates the file. + \row \i \c IO_Translate \i enables carriage returns and linefeed + translation for text files under MS-DOS, Windows and Macintosh. On + Unix systems this flag has no effect. Use with caution as it will + also transform every linefeed written to the file into a CRLF + pair. This is likely to corrupt your file if you write write + binary data. Cannot be combined with \c IO_Raw. + \endtable + + This virtual function must be reimplemented by all subclasses. + + \sa close() +*/ + +/*! + \fn void TQIODevice::close() + + Closes the I/O device. + + This virtual function must be reimplemented by all subclasses. + + \sa open() +*/ + +/*! + \fn void TQIODevice::flush() + + Flushes an open I/O device. + + This virtual function must be reimplemented by all subclasses. +*/ + + +/*! + \fn TQIODevice::Offset TQIODevice::size() const + + Virtual function that returns the size of the I/O device. + + \sa at() +*/ + +/*! + Virtual function that returns the current I/O device position. + + This is the position of the data read/write head of the I/O + device. + + \sa size() +*/ + +TQIODevice::Offset TQIODevice::at() const +{ + return ioIndex; +} + + +/* + The following is a "bad" overload, since it does "not behave essentially + the same" like the above. So don't use \overload in the documentation of + this function and we have to live with the qdoc warning which is generated + for this. +*/ +/*! + Virtual function that sets the I/O device position to \a pos. + Returns TRUE if the position was successfully set, i.e. \a pos is + within range and the seek was successful; otherwise returns FALSE. + + \sa size() +*/ + +bool TQIODevice::at( Offset pos ) +{ +#if defined(QT_CHECK_RANGE) + if ( pos > size() ) { + tqWarning( "TQIODevice::at: Index %lu out of range", pos ); + return FALSE; + } +#endif + ioIndex = pos; + return TRUE; +} + +/*! + Virtual function that returns TRUE if the I/O device position is + at the end of the input; otherwise returns FALSE. +*/ + +bool TQIODevice::atEnd() const +{ + if ( isSequentialAccess() || isTranslated() ) { + TQIODevice* that = (TQIODevice*)this; + const int oldStatus = ioSt; + int c = that->getch(); + bool result = c < 0; + that->ungetch(c); + if (ioSt != oldStatus) + that->ioSt = oldStatus; + return result; + } else { + return at() == size(); + } +} + +/*! + \fn bool TQIODevice::reset() + + Sets the device index position to 0. + + \sa at() +*/ + + +/*! + \fn int TQIODevice::readBlock( char *data, TQ_ULONG maxlen ) + + Reads at most \a maxlen bytes from the I/O device into \a data and + returns the number of bytes actually read. + + This function should return -1 if a fatal error occurs and should + return 0 if there are no bytes to read. + + The device must be opened for reading, and \a data must not be 0. + + This virtual function must be reimplemented by all subclasses. + + \sa writeBlock() isOpen() isReadable() +*/ + +/*! + This convenience function returns all of the remaining data in the + device. +*/ +TQByteArray TQIODevice::readAll() +{ + if ( isDirectAccess() ) { + // we know the size + int n = size()-at(); // ### fix for 64-bit or large files? + int totalRead = 0; + TQByteArray ba( n ); + char* c = ba.data(); + while ( n ) { + int r = readBlock( c, n ); + if ( r < 0 ) + return TQByteArray(); + n -= r; + c += r; + totalRead += r; + // If we have a translated file, then it is possible that + // we read less bytes than size() reports + if ( atEnd() ) { + ba.resize( totalRead ); + break; + } + } + return ba; + } else { + // read until we reach the end + const int blocksize = 512; + int nread = 0; + TQByteArray ba; + while ( !atEnd() ) { + ba.resize( nread + blocksize ); + int r = readBlock( ba.data()+nread, blocksize ); + if ( r < 0 ) + return TQByteArray(); + nread += r; + } + ba.resize( nread ); + return ba; + } +} + +/*! + \fn int TQIODevice::writeBlock( const char *data, TQ_ULONG len ) + + Writes \a len bytes from \a data to the I/O device and returns the + number of bytes actually written. + + This function should return -1 if a fatal error occurs. + + This virtual function must be reimplemented by all subclasses. + + \sa readBlock() +*/ + +/*! + \overload + + This convenience function is the same as calling writeBlock( + data.data(), data.size() ). +*/ +TQ_LONG TQIODevice::writeBlock( const TQByteArray& data ) +{ + return writeBlock( data.data(), data.size() ); +} + +/*! + Reads a line of text, (or up to \a maxlen bytes if a newline isn't + encountered) plus a terminating '\0' into \a data. If there is a + newline at the end if the line, it is not stripped. + + Returns the number of bytes read including the terminating '\0', + or -1 if an error occurred. + + This virtual function can be reimplemented much more efficiently + by the most subclasses. + + \sa readBlock(), TQTextStream::readLine() +*/ + +TQ_LONG TQIODevice::readLine( char *data, TQ_ULONG maxlen ) +{ + if ( maxlen == 0 ) // application bug? + return 0; + char *p = data; + while ( --maxlen && (readBlock(p,1)>0) ) { // read one byte at a time + if ( *p++ == '\n' ) // end of line + break; + } + *p++ = '\0'; + return p - data; +} + + +/*! + \fn int TQIODevice::getch() + + Reads a single byte/character from the I/O device. + + Returns the byte/character read, or -1 if the end of the I/O + device has been reached. + + This virtual function must be reimplemented by all subclasses. + + \sa putch(), ungetch() +*/ + +/*! + \fn int TQIODevice::putch( int ch ) + + Writes the character \a ch to the I/O device. + + Returns \a ch, or -1 if an error occurred. + + This virtual function must be reimplemented by all subclasses. + + \sa getch(), ungetch() +*/ + +/*! + \fn int TQIODevice::ungetch( int ch ) + + Puts the character \a ch back into the I/O device and decrements + the index position if it is not zero. + + This function is normally called to "undo" a getch() operation. + + Returns \a ch, or -1 if an error occurred. + + This virtual function must be reimplemented by all subclasses. + + \sa getch(), putch() +*/ diff --git a/src/tools/tqiodevice.h b/src/tools/tqiodevice.h new file mode 100644 index 000000000..712288d8e --- /dev/null +++ b/src/tools/tqiodevice.h @@ -0,0 +1,160 @@ +/**************************************************************************** +** +** Definition of TQIODevice class +** +** Created : 940913 +** +** Copyright (C) 1992-2008 Trolltech ASA. All rights reserved. +** +** This file is part of the tools module of the TQt GUI Toolkit. +** +** This file may be used under the terms of the GNU General +** Public License versions 2.0 or 3.0 as published by the Free +** Software Foundation and appearing in the files LICENSE.GPL2 +** and LICENSE.GPL3 included in the packaging of this file. +** Alternatively you may (at your option) use any later version +** of the GNU General Public License if such license has been +** publicly approved by Trolltech ASA (or its successors, if any) +** and the KDE Free TQt Foundation. +** +** Please review the following information to ensure GNU General +** Public Licensing requirements will be met: +** http://trolltech.com/products/qt/licenses/licensing/opensource/. +** If you are unsure which license is appropriate for your use, please +** review the following information: +** http://trolltech.com/products/qt/licenses/licensing/licensingoverview +** or contact the sales department at sales@trolltech.com. +** +** This file may be used under the terms of the Q Public License as +** defined by Trolltech ASA and appearing in the file LICENSE.TQPL +** included in the packaging of this file. Licensees holding valid TQt +** Commercial licenses may use this file in accordance with the TQt +** Commercial License Agreement provided with the Software. +** +** This file is provided "AS IS" with NO WARRANTY OF ANY KIND, +** INCLUDING THE WARRANTIES OF DESIGN, MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE. Trolltech reserves all rights not granted +** herein. +** +**********************************************************************/ + +#ifndef TQIODEVICE_H +#define TQIODEVICE_H + +#ifndef QT_H +#include "ntqglobal.h" +#include "tqcstring.h" +#endif // QT_H + + +// IO device access types + +#define IO_Direct 0x0100 // direct access device +#define IO_Sequential 0x0200 // sequential access device +#define IO_Combined 0x0300 // combined direct/sequential +#define IO_TypeMask 0x0f00 + +// IO handling modes + +#define IO_Raw 0x0040 // raw access (not buffered) +#define IO_Async 0x0080 // asynchronous mode + +// IO device open modes + +#define IO_ReadOnly 0x0001 // readable device +#define IO_WriteOnly 0x0002 // writable device +#define IO_ReadWrite 0x0003 // read+write device +#define IO_Append 0x0004 // append +#define IO_Truncate 0x0008 // truncate device +#define IO_Translate 0x0010 // translate CR+LF +#define IO_ModeMask 0x00ff + +// IO device state + +#define IO_Open 0x1000 // device is open +#define IO_StateMask 0xf000 + +// IO device status + +#define IO_Ok 0 +#define IO_ReadError 1 // read error +#define IO_WriteError 2 // write error +#define IO_FatalError 3 // fatal unrecoverable error +#define IO_ResourceError 4 // resource limitation +#define IO_OpenError 5 // cannot open device +#define IO_ConnectError 5 // cannot connect to device +#define IO_AbortError 6 // abort error +#define IO_TimeOutError 7 // time out +#define IO_UnspecifiedError 8 // unspecified error + + +class TQ_EXPORT TQIODevice +{ +public: + typedef TQ_ULONG Offset; + + TQIODevice(); + virtual ~TQIODevice(); + + int flags() const { return ioMode; } + int mode() const { return ioMode & IO_ModeMask; } + int state() const { return ioMode & IO_StateMask; } + + bool isDirectAccess() const { return ((ioMode & IO_Direct) == IO_Direct); } + bool isSequentialAccess() const { return ((ioMode & IO_Sequential) == IO_Sequential); } + bool isCombinedAccess() const { return ((ioMode & IO_Combined) == IO_Combined); } + bool isBuffered() const { return ((ioMode & IO_Raw) != IO_Raw); } + bool isRaw() const { return ((ioMode & IO_Raw) == IO_Raw); } + bool isSynchronous() const { return ((ioMode & IO_Async) != IO_Async); } + bool isAsynchronous() const { return ((ioMode & IO_Async) == IO_Async); } + bool isTranslated() const { return ((ioMode & IO_Translate) == IO_Translate); } + bool isReadable() const { return ((ioMode & IO_ReadOnly) == IO_ReadOnly); } + bool isWritable() const { return ((ioMode & IO_WriteOnly) == IO_WriteOnly); } + bool isReadWrite() const { return ((ioMode & IO_ReadWrite) == IO_ReadWrite); } + bool isInactive() const { return state() == 0; } + bool isOpen() const { return state() == IO_Open; } + + int status() const { return ioSt; } + void resetStatus() { ioSt = IO_Ok; } + + virtual bool open( int mode ) = 0; + virtual void close() = 0; + virtual void flush() = 0; + + virtual Offset size() const = 0; + virtual Offset at() const; + virtual bool at( Offset ); + virtual bool atEnd() const; + bool reset() { return at(0); } + + virtual TQ_LONG readBlock( char *data, TQ_ULONG maxlen ) = 0; + virtual TQ_LONG writeBlock( const char *data, TQ_ULONG len ) = 0; + virtual TQ_LONG readLine( char *data, TQ_ULONG maxlen ); + TQ_LONG writeBlock( const TQByteArray& data ); + virtual TQByteArray readAll(); + + virtual int getch() = 0; + virtual int putch( int ) = 0; + virtual int ungetch( int ) = 0; + +protected: + void setFlags( int f ) { ioMode = f; } + void setType( int ); + void setMode( int ); + void setState( int ); + void setStatus( int ); + Offset ioIndex; + +private: + int ioMode; + int ioSt; + +private: // Disabled copy constructor and operator= +#if defined(TQ_DISABLE_COPY) + TQIODevice( const TQIODevice & ); + TQIODevice &operator=( const TQIODevice & ); +#endif +}; + + +#endif // TQIODEVICE_H diff --git a/src/tools/tqmap.h b/src/tools/tqmap.h index 97a21883a..a173e7575 100644 --- a/src/tools/tqmap.h +++ b/src/tools/tqmap.h @@ -44,7 +44,7 @@ #ifndef QT_H #include "ntqglobal.h" #include "ntqshared.h" -#include "ntqdatastream.h" +#include "tqdatastream.h" #include "tqpair.h" #include "tqvaluelist.h" #endif // QT_H diff --git a/src/tools/tqpair.h b/src/tools/tqpair.h index cd1614685..5b197d8d4 100644 --- a/src/tools/tqpair.h +++ b/src/tools/tqpair.h @@ -42,7 +42,7 @@ #ifndef QT_H #include "ntqglobal.h" -#include "ntqdatastream.h" +#include "tqdatastream.h" #endif // QT_H template diff --git a/src/tools/tqsettings.cpp b/src/tools/tqsettings.cpp new file mode 100644 index 000000000..a2ef55da7 --- /dev/null +++ b/src/tools/tqsettings.cpp @@ -0,0 +1,2128 @@ +/**************************************************************************** +** +** Implementation of TQSettings class +** +** Created : 000626 +** +** Copyright (C) 2000-2008 Trolltech ASA. All rights reserved. +** +** This file is part of the tools module of the TQt GUI Toolkit. +** +** This file may be used under the terms of the GNU General +** Public License versions 2.0 or 3.0 as published by the Free +** Software Foundation and appearing in the files LICENSE.GPL2 +** and LICENSE.GPL3 included in the packaging of this file. +** Alternatively you may (at your option) use any later version +** of the GNU General Public License if such license has been +** publicly approved by Trolltech ASA (or its successors, if any) +** and the KDE Free TQt Foundation. +** +** Please review the following information to ensure GNU General +** Public Licensing requirements will be met: +** http://trolltech.com/products/qt/licenses/licensing/opensource/. +** If you are unsure which license is appropriate for your use, please +** review the following information: +** http://trolltech.com/products/qt/licenses/licensing/licensingoverview +** or contact the sales department at sales@trolltech.com. +** +** This file may be used under the terms of the Q Public License as +** defined by Trolltech ASA and appearing in the file LICENSE.TQPL +** included in the packaging of this file. Licensees holding valid TQt +** Commercial licenses may use this file in accordance with the TQt +** Commercial License Agreement provided with the Software. +** +** This file is provided "AS IS" with NO WARRANTY OF ANY KIND, +** INCLUDING THE WARRANTIES OF DESIGN, MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE. Trolltech reserves all rights not granted +** herein. +** +**********************************************************************/ + +#include "qplatformdefs.h" +#include + +// POSIX Large File Support redefines open -> open64 +static inline int qt_open( const char *pathname, int flags, mode_t mode ) +{ return ::open( pathname, flags, mode ); } +#if defined(open) +# undef open +#endif + +// POSIX Large File Support redefines truncate -> truncate64 +#if defined(truncate) +# undef truncate +#endif + +#include "tqsettings.h" + +#ifndef TQT_NO_SETTINGS + +#include "tqdir.h" +#include "tqfile.h" +#include "tqfileinfo.h" +#include "tqmap.h" +#include "tqtextstream.h" +#include "tqregexp.h" +#include +#ifndef NO_ERRNO_H +#include +#endif + +/*! + \class TQSettings + \brief The TQSettings class provides persistent platform-independent application settings. + + \ingroup io + \ingroup misc + \mainclass + + On Unix systems, TQSettings uses text files to store settings. On Windows + systems, TQSettings uses the system registry. On Mac OS X, TQSettings uses + the Carbon preferences API. + + Each setting comprises an identifying key and the data associated with + the key. A key is a unicode string which consists of \e two or more + subkeys. A subkey is a slash, '/', followed by one or more unicode + characters (excluding slashes, newlines, carriage returns and equals, + '=', signs). The associated data, called the entry or value, may be a + boolean, an integer, a double, a string or a list of strings. Entry + strings may contain any unicode characters. + + If you want to save and restore the entire desktop's settings, i.e. + which applications are running, use TQSettings to save the settings + for each individual application and TQSessionManager to save the + desktop's session. + + Example settings: + \code + /MyCompany/MyApplication/background color + /MyCompany/MyApplication/foreground color + /MyCompany/MyApplication/geometry/x + /MyCompany/MyApplication/geometry/y + /MyCompany/MyApplication/geometry/width + /MyCompany/MyApplication/geometry/height + /MyCompany/MyApplication/recent files/1 + /MyCompany/MyApplication/recent files/2 + /MyCompany/MyApplication/recent files/3 + \endcode + Each line above is a complete key, made up of subkeys. + + A typical usage pattern for reading settings at application + startup: + \code + TQSettings settings; + settings.setPath( "MyCompany.com", "MyApplication" ); + + TQString bgColor = settings.readEntry( "/colors/background", "white" ); + int width = settings.readNumEntry( "/geometry/width", 640 ); + // ... + \endcode + + A typical usage pattern for saving settings at application exit or + 'save preferences': + \code + TQSettings settings; + settings.setPath( "MyCompany.com", "MyApplication" ); + + settings.writeEntry( "/colors/background", bgColor ); + settings.writeEntry( "/geometry/width", width ); + // ... + \endcode + + A key prefix can be prepended to all keys using beginGroup(). The + application of the prefix is stopped using endGroup(). For + example: + \code + TQSettings settings; + + settings.beginGroup( "/MainWindow" ); + settings.beginGroup( "/Geometry" ); + int x = settings.readEntry( "/x" ); + // ... + settings.endGroup(); + settings.beginGroup( "/Toolbars" ); + // ... + settings.endGroup(); + settings.endGroup(); + \endcode + + You can get a list of entry-holding keys by calling entryList(), and + a list of key-holding keys using subkeyList(). + + \code + TQStringList keys = settings.entryList( "/MyApplication" ); + // keys contains 'background color' and 'foreground color'. + + TQStringList keys = settings.entryList( "/MyApplication/recent files" ); + // keys contains '1', '2' and '3'. + + TQStringList subkeys = settings.subkeyList( "/MyApplication" ); + // subkeys contains 'geometry' and 'recent files' + + TQStringList subkeys = settings.subkeyList( "/MyApplication/recent files" ); + // subkeys is empty. + \endcode + + Since settings for Windows are stored in the registry there are + some size limitations as follows: + \list + \i A subkey may not exceed 255 characters. + \i An entry's value may not exceed 16,300 characters. + \i All the values of a key (for example, all the 'recent files' + subkeys values), may not exceed 65,535 characters. + \endlist + + These limitations are not enforced on Unix or Mac OS X. + + \warning Creating multiple, simultaneous instances of TQSettings writing + to a text file may lead to data loss! This is a known issue which will + be fixed in a future release of TQt. + + \section1 Notes for Mac OS X Applications + + The location where settings are stored is not formally defined by + the CFPreferences API. + + At the time of writing settings are stored (either on a global or + user basis, preferring locally) into a plist file in \c + $ROOT/System/Library/Preferences (in XML format). TQSettings will + create an appropriate plist file (\c{com..plist}) + out of the full path to a key. + + For further information on CFPreferences see + \link http://developer.apple.com/documentation/CoreFoundation/Conceptual/CFPreferences/index.html + Apple's Specifications\endlink + + \section1 Notes for Unix Applications + + There is no universally accepted place for storing application + settings under Unix. In the examples the settings file will be + searched for in the following directories: + \list 1 + \i \c SYSCONF - the default value is \c INSTALL/etc/settings + \i \c /opt/MyCompany/share/etc + \i \c /opt/MyCompany/share/MyApplication/etc + \i \c $HOME/.qt + \endlist + When reading settings the files are searched in the order shown + above, with later settings overriding earlier settings. Files for + which the user doesn't have read permission are ignored. When saving + settings TQSettings works in the order shown above, writing + to the first settings file for which the user has write permission. + (\c INSTALL is the directory where TQt was installed. This can be + modified by using the configure script's -prefix argument ) + + If you want to put the settings in a particular place in the + filesystem you could do this: + \code + settings.insertSearchPath( TQSettings::Unix, "/opt/MyCompany/share" ); + \endcode + + But in practice you may prefer not to use a search path for Unix. + For example the following code: + \code + settings.writeEntry( "/MyApplication/geometry/width", width ); + \endcode + will end up writing the "geometry/width" setting to the file + \c{$HOME/.qt/myapplicationrc} (assuming that the application is + being run by an ordinary user, i.e. not by root). + + For cross-platform applications you should ensure that the + \link #sizelimit Windows size limitations \endlink are not exceeded. + + \warning TQSettings doesn't write the settings until it is destroyed so + you should construct the TQSettings object on the stack. +*/ + +/*! + \enum TQSettings::System + + \value Mac Macintosh execution environments + \value Unix Mac OS X, Unix, Linux and Unix-like execution environments + \value Windows Windows execution environments +*/ + +/*! + \enum TQSettings::Format + + \value Native Store the settings in a platform dependent location + \value Ini Store the settings in a text file +*/ + +/*! + \enum TQSettings::Scope + + \value Global Save settings as global as possible + \value User Save settings in user space +*/ + +#if defined(Q_OS_UNIX) +typedef int HANDLE; +#define Q_LOCKREAD F_RDLCK +#define Q_LOCKWRITE F_WRLCK +/* + Locks the file specified by name. The lockfile is created as a + hidden file in the same directory as the target file, with .lock + appended to the name. For example, "/etc/settings/onerc" uses a + lockfile named "/etc/settings/.onerc.lock". The type argument + controls the type of the lock, it can be either F_RDLCK for a read + lock, or F_WRLCK for a write lock. + + A file descriptor for the lock file is returned, and should be + closed with closelock() when the lock is no longer needed. + */ +static HANDLE openlock( const TQString &name, int type ) +{ + TQFileInfo info( name ); + // lockfile should be hidden, and never removed + TQString lockfile = info.dirPath() + "/." + info.fileName() + ".lock"; + + // open the lockfile + HANDLE fd = qt_open( TQFile::encodeName( lockfile ), + O_RDWR | O_CREAT, S_IRUSR | S_IWUSR ); + + if ( fd < 0 ) { + // failed to open the lock file, most likely because of permissions + return fd; + } + + struct flock fl; + fl.l_type = type; + fl.l_whence = SEEK_SET; + fl.l_start = 0; + fl.l_len = 0; + if ( fcntl( fd, F_SETLKW, &fl ) == -1 ) { + // the lock failed, so we should fail silently, so that people + // using filesystems that do not support locking don't see + // numerous warnings about a failed lock + close( fd ); + fd = -1; + } + + return fd; +} + +/* + Closes the lock file specified by fd. fd is the file descriptor + returned by the openlock() function. +*/ +static void closelock( HANDLE fd ) +{ + if ( fd < 0 ) { + // the lock file is not open + return; + } + + struct flock fl; + fl.l_type = F_UNLCK; + fl.l_whence = SEEK_SET; + fl.l_start = 0; + fl.l_len = 0; + // ignore the return value, so that the unlock fails silently + (void) fcntl( fd, F_SETLKW, &fl ); + + close( fd ); +} +#endif + + +TQSettingsGroup::TQSettingsGroup() + : modified(FALSE) +{ +} + + + + +void TQSettingsHeading::read(const TQString &filename) +{ + if (! TQFileInfo(filename).exists()) + return; + +#ifndef TQ_WS_WIN + HANDLE lockfd = openlock( filename, Q_LOCKREAD ); +#endif + + TQFile file(filename); + if (! file.open(IO_ReadOnly)) { +#if defined(QT_CHECK_STATE) + tqWarning("TQSettings: failed to open file '%s'", filename.latin1()); +#endif + return; + } + + git = end(); + + TQTextStream stream(&file); + stream.setEncoding(TQTextStream::UnicodeUTF8); + while (! stream.atEnd()) + parseLine(stream); + + git = end(); + + file.close(); + +#ifndef TQ_WS_WIN + closelock( lockfd ); +#endif +} + + +void TQSettingsHeading::parseLine(TQTextStream &stream) +{ + TQString line = stream.readLine(); + if (line.isEmpty()) + // empty line... we'll allow it + return; + + if (line[0] == TQChar('#')) + // commented line + return; + + if (line[0] == TQChar('[')) { + TQString gname = line; + + gname = gname.remove((uint)0, 1); + if (gname[(int)gname.length() - 1] == TQChar(']')) + gname = gname.remove(gname.length() - 1, 1); + + git = find(gname); + if (git == end()) + git = replace(gname, TQSettingsGroup()); + } else { + if (git == end()) { +#if defined(QT_CHECK_STATE) + tqWarning("TQSettings: line '%s' out of group", line.latin1()); +#endif + return; + } + + int i = line.find('='); + if (i == -1) { +#if defined(QT_CHECK_STATE) + tqWarning("TQSettings: malformed line '%s' in group '%s'", + line.latin1(), git.key().latin1()); +#endif + return; + } else { + TQString key, value; + key = line.left(i); + value = ""; + bool esc=TRUE; + i++; + while (esc) { + esc = FALSE; + for ( ; i < (int)line.length(); i++ ) { + if ( esc ) { + if ( line[i] == 'n' ) + value.append('\n'); // escaped newline + else if ( line[i] == '0' ) + value = TQString::null; // escaped empty string + else + value.append(line[i]); + esc = FALSE; + } else if ( line[i] == '\\' ) + esc = TRUE; + else + value.append(line[i]); + } + if ( esc ) { + // Backwards-compatiblity... + // still escaped at EOL - manually escaped "newline" + if (stream.atEnd()) { +#if defined(QT_CHECK_STATE) + tqWarning("TQSettings: reached end of file, expected continued line"); +#endif + break; + } + value.append('\n'); + line = stream.readLine(); + i = 0; + } + } + + (*git).insert(key, value); + } + } +} + +#ifdef TQ_WS_WIN // for homedirpath reading from registry +#include "qt_windows.h" +#include "ntqlibrary.h" + +#ifndef CSIDL_APPDATA +#define CSIDL_APPDATA 0x001a // \Application Data +#endif +#ifndef CSIDL_COMMON_APPDATA +#define CSIDL_COMMON_APPDATA 0x0023 // All Users\Application Data +#endif + +#endif + +TQSettingsPrivate::TQSettingsPrivate( TQSettings::Format format ) + : groupDirty( TRUE ), modified(FALSE), globalScope(TRUE) +{ +#if defined(TQ_WS_WIN) || defined(Q_OS_MAC) + if ( format != TQSettings::Ini ) + return; +#else + Q_UNUSED( format ); +#endif + + TQString home; + home = getenv("QT_HOME_DIR"); + if ( !home.isEmpty() ) { + home += "/"; + TQFileInfo i( home + "qtrc" ); + if ( !i.isReadable() ) { + home = TQDir::homeDirPath() + "/.qt/"; + } + } else { + home = TQDir::homeDirPath() + "/.qt/"; + } + TQString appSettings(home); + + TQString defPath; +#ifdef TQ_WS_WIN +#ifdef Q_OS_TEMP + TCHAR path[MAX_PATH]; + SHGetSpecialFolderPath( 0, path, CSIDL_APPDATA, FALSE ); + appSettings = TQString::fromUcs2( path ); + SHGetSpecialFolderPath( 0, path, CSIDL_COMMON_APPDATA, FALSE ); + defPath = TQString::fromUcs2( path ); +#else + TQLibrary library( "shell32" ); + library.setAutoUnload( FALSE ); + QT_WA( { + typedef BOOL (WINAPI*GetSpecialFolderPath)(HWND, LPTSTR, int, BOOL); + GetSpecialFolderPath SHGetSpecialFolderPath = (GetSpecialFolderPath)library.resolve( "SHGetSpecialFolderPathW" ); + if ( SHGetSpecialFolderPath ) { + TCHAR path[MAX_PATH]; + SHGetSpecialFolderPath( 0, path, CSIDL_APPDATA, FALSE ); + appSettings = TQString::fromUcs2( (ushort*)path ); + SHGetSpecialFolderPath( 0, path, CSIDL_COMMON_APPDATA, FALSE ); + defPath = TQString::fromUcs2( (ushort*)path ); + } + } , { + typedef BOOL (WINAPI*GetSpecialFolderPath)(HWND, char*, int, BOOL); + GetSpecialFolderPath SHGetSpecialFolderPath = (GetSpecialFolderPath)library.resolve( "SHGetSpecialFolderPathA" ); + if ( SHGetSpecialFolderPath ) { + char path[MAX_PATH]; + SHGetSpecialFolderPath( 0, path, CSIDL_APPDATA, FALSE ); + appSettings = TQString::fromLocal8Bit( path ); + SHGetSpecialFolderPath( 0, path, CSIDL_COMMON_APPDATA, FALSE ); + defPath = TQString::fromLocal8Bit( path ); + } + } ); +#endif // Q_OS_TEMP +#else + defPath = tqInstallPathSysconf(); +#endif + TQDir dir(appSettings); + if (! dir.exists()) { + if (! dir.mkdir(dir.path())) +#if defined(QT_CHECK_STATE) + tqWarning("TQSettings: error creating %s", dir.path().latin1()); +#else + ; +#endif + } + + if ( !!defPath ) + searchPaths.append(defPath); + + TQString system; + system = getenv("QT_SYSTEM_DIR"); + if ( !system.isEmpty() && system[0] == '/') { + TQFileInfo i( system + "/qtrc" ); + if ( i.isReadable() ) { + searchPaths.append(system); + } + } + + searchPaths.append(dir.path()); +} + +TQSettingsPrivate::~TQSettingsPrivate() +{ +} + +TQSettingsGroup TQSettingsPrivate::readGroup() +{ + TQSettingsHeading hd; + TQSettingsGroup grp; + + TQMap::Iterator headingsit = headings.find(heading); + if (headingsit != headings.end()) + hd = *headingsit; + + TQSettingsHeading::Iterator grpit = hd.find(group); + if (grpit == hd.end()) { + TQStringList::Iterator it = searchPaths.begin(); + if ( !globalScope ) + ++it; + while (it != searchPaths.end()) { + TQString filebase = heading.lower().replace(TQRegExp(TQString::fromLatin1("\\s+")), "_"); + TQString fn((*it++) + "/" + filebase + "rc"); + if (! hd.contains(fn + "cached")) { + hd.read(fn); + hd.insert(fn + "cached", TQSettingsGroup()); + } + } + + headings.replace(heading, hd); + + grpit = hd.find(group); + if (grpit != hd.end()) + grp = *grpit; + } else if (hd.count() != 0) + grp = *grpit; + + return grp; +} + + +void TQSettingsPrivate::removeGroup(const TQString &key) +{ + TQSettingsHeading hd; + TQSettingsGroup grp; + bool found = FALSE; + + TQMap::Iterator headingsit = headings.find(heading); + if (headingsit != headings.end()) + hd = *headingsit; + + TQSettingsHeading::Iterator grpit = hd.find(group); + if (grpit == hd.end()) { + TQStringList::Iterator it = searchPaths.begin(); + if ( !globalScope ) + ++it; + while (it != searchPaths.end()) { + TQString filebase = heading.lower().replace(TQRegExp(TQString::fromLatin1("\\s+")), "_"); + TQString fn((*it++) + "/" + filebase + "rc"); + if (! hd.contains(fn + "cached")) { + hd.read(fn); + hd.insert(fn + "cached", TQSettingsGroup()); + } + } + + headings.replace(heading, hd); + + grpit = hd.find(group); + if (grpit != hd.end()) { + found = TRUE; + grp = *grpit; + } + } else if (hd.count() != 0) { + found = TRUE; + grp = *grpit; + } + + if (found) { + grp.remove(key); + + if (grp.count() > 0) + hd.replace(group, grp); + else + hd.remove(group); + + if (hd.count() > 0) + headings.replace(heading, hd); + else + headings.remove(heading); + + modified = TRUE; + } +} + + +void TQSettingsPrivate::writeGroup(const TQString &key, const TQString &value) +{ + TQSettingsHeading hd; + TQSettingsGroup grp; + + TQMap::Iterator headingsit = headings.find(heading); + if (headingsit != headings.end()) + hd = *headingsit; + + TQSettingsHeading::Iterator grpit = hd.find(group); + if (grpit == hd.end()) { + TQStringList::Iterator it = searchPaths.begin(); + if ( !globalScope ) + ++it; + while (it != searchPaths.end()) { + TQString filebase = heading.lower().replace(TQRegExp(TQString::fromLatin1("\\s+")), "_"); + TQString fn((*it++) + "/" + filebase + "rc"); + if (! hd.contains(fn + "cached")) { + hd.read(fn); + hd.insert(fn + "cached", TQSettingsGroup()); + } + } + + headings.replace(heading, hd); + + grpit = hd.find(group); + if (grpit != hd.end()) + grp = *grpit; + } else if (hd.count() != 0) + grp = *grpit; + + grp.modified = TRUE; + grp.replace(key, value); + hd.replace(group, grp); + headings.replace(heading, hd); + + modified = TRUE; +} + + +TQDateTime TQSettingsPrivate::modificationTime() +{ + TQSettingsHeading hd = headings[heading]; + TQSettingsGroup grp = hd[group]; + + TQDateTime datetime; + + TQStringList::Iterator it = searchPaths.begin(); + if ( !globalScope ) + ++it; + while (it != searchPaths.end()) { + TQFileInfo fi((*it++) + "/" + heading + "rc"); + if (fi.exists() && fi.lastModified() > datetime) + datetime = fi.lastModified(); + } + + return datetime; +} + +bool qt_verify_key( const TQString &key ) +{ + if ( key.isEmpty() || key[0] != '/' || key.contains( TQRegExp(TQString::fromLatin1("[=\\r\\n]")) ) ) + return FALSE; + return TRUE; +} + +static TQString groupKey( const TQString &group, const TQString &key ) +{ + TQString grp_key; + if ( group.isEmpty() || ( group.length() == 1 && group[0] == '/' ) ) { + // group is empty, or it contains a single '/', so we just return the key + if ( key.startsWith( "/" ) ) + grp_key = key; + else + grp_key = "/" + key; + } else if ( group.endsWith( "/" ) || key.startsWith( "/" ) ) { + grp_key = group + key; + } else { + grp_key = group + "/" + key; + } + return grp_key; +} + +/*! + Inserts \a path into the settings search path. The semantics of \a + path depends on the system \a s. It is usually easier and better to + use setPath() instead of this function. + + When \a s is \e Windows and the execution environment is \e not + Windows the function does nothing. Similarly when \a s is \e Unix and + the execution environment is \e not Unix the function does nothing. + + When \a s is \e Windows, and the execution environment is Windows, the + search path list will be used as the first subfolder of the "Software" + folder in the registry. + + When reading settings the folders are searched forwards from the + first folder (listed below) to the last, returning the first + settings found, and ignoring any folders for which the user doesn't + have read permission. + \list 1 + \i HKEY_CURRENT_USER/Software/MyCompany/MyApplication + \i HKEY_LOCAL_MACHINE/Software/MyCompany/MyApplication + \i HKEY_CURRENT_USER/Software/MyApplication + \i HKEY_LOCAL_MACHINE/Software/MyApplication + \endlist + + \code + TQSettings settings; + settings.insertSearchPath( TQSettings::Windows, "/MyCompany" ); + settings.writeEntry( "/MyApplication/Tip of the day", TRUE ); + \endcode + The code above will write the subkey "Tip of the day" into the \e + first of the registry folders listed below that is found and for + which the user has write permission. + \list 1 + \i HKEY_LOCAL_MACHINE/Software/MyCompany/MyApplication + \i HKEY_CURRENT_USER/Software/MyCompany/MyApplication + \i HKEY_LOCAL_MACHINE/Software/MyApplication + \i HKEY_CURRENT_USER/Software/MyApplication + \endlist + If a setting is found in the HKEY_CURRENT_USER space, this setting + is overwritten independently of write permissions in the + HKEY_LOCAL_MACHINE space. + + When \a s is \e Unix, and the execution environment is Unix, the + search path list will be used when trying to determine a suitable + filename for reading and writing settings files. By default, there are + two entries in the search path: + + \list 1 + \i \c SYSCONF - where \c SYSCONF is a directory specified when + configuring TQt; by default it is INSTALL/etc/settings. + \i \c $HOME/.qt/ - where \c $HOME is the user's home directory. + \endlist + + All insertions into the search path will go before $HOME/.qt/. + For example: + \code + TQSettings settings; + settings.insertSearchPath( TQSettings::Unix, "/opt/MyCompany/share/etc" ); + settings.insertSearchPath( TQSettings::Unix, "/opt/MyCompany/share/MyApplication/etc" ); + // ... + \endcode + Will result in a search path of: + \list 1 + \i SYSCONF + \i /opt/MyCompany/share/etc + \i /opt/MyCompany/share/MyApplication/etc + \i $HOME/.qt + \endlist + When reading settings the files are searched in the order shown + above, with later settings overriding earlier settings. Files for + which the user doesn't have read permission are ignored. When saving + settings TQSettings works in the order shown above, writing + to the first settings file for which the user has write permission. + + Note that paths in the file system are not created by this + function, so they must already exist to be useful. + + Settings under Unix are stored in files whose names are based on the + first subkey of the key (not including the search path). The algorithm + for creating names is essentially: lowercase the first subkey, replace + spaces with underscores and add 'rc', e.g. + /MyCompany/MyApplication/background color will be stored in + myapplicationrc (assuming that /MyCompany is part of + the search path). + + \sa removeSearchPath() + +*/ +void TQSettings::insertSearchPath( System s, const TQString &path) +{ +#if defined(TQ_WS_WIN) || defined(Q_OS_MAC) + if ( d->sysd ) { + d->sysInsertSearchPath( s, path ); + return; + } +#endif + +#if !defined(TQ_WS_WIN) + if ( s == Windows ) + return; +#endif +#if !defined(Q_OS_MAC) + if ( s == Mac ) + return; +#endif + + if ( !qt_verify_key( path ) ) { +#if defined(QT_CHECK_STATE) + tqWarning( "TQSettings::insertSearchPath: Invalid key: '%s'", path.isNull() ? "(null)" : path.latin1() ); +#endif + return; + } + +#if defined(TQ_WS_WIN) || defined(Q_OS_MAC) + if ( d->sysd && s != Unix ) { +#else + if ( s != Unix ) { +#endif +#if defined(Q_OS_MAC) + if(s != Mac) //mac is respected on the mac as well +#endif + return; + } + + TQString realPath = path; +#if defined(TQ_WS_WIN) + TQString defPath = d->globalScope ? d->searchPaths.first() : d->searchPaths.last(); + realPath = defPath + path; +#endif + + TQStringList::Iterator it = d->searchPaths.find(d->searchPaths.last()); + if (it != d->searchPaths.end()) { + d->searchPaths.insert(it, realPath); + } +} + + +/*! + Removes all occurrences of \a path (using exact matching) from the + settings search path for system \a s. Note that the default search + paths cannot be removed. + + \sa insertSearchPath() +*/ +void TQSettings::removeSearchPath( System s, const TQString &path) +{ + if ( !qt_verify_key( path ) ) { +#if defined(QT_CHECK_STATE) + tqWarning( "TQSettings::insertSearchPath: Invalid key: '%s'", path.isNull() ? "(null)" : path.latin1() ); +#endif + return; + } + +#ifdef TQ_WS_WIN + if ( d->sysd ) { + d->sysRemoveSearchPath( s, path ); + return; + } +#endif +#if defined(TQ_WS_WIN) || defined(Q_OS_MAC) + if ( d->sysd && s != Unix ) { +#else + if ( s != Unix ) { +#endif +#if defined(Q_OS_MAC) + if(s != Mac) //mac is respected on the mac as well +#endif + return; + } + + if (path == d->searchPaths.first() || path == d->searchPaths.last()) + return; + + d->searchPaths.remove(path); +} + + +/*! + Creates a settings object. + + Be aware that you must call setPath() or insertSearchPath() before + you can use the TQSettings object. +*/ +TQSettings::TQSettings() +{ + d = new TQSettingsPrivate( Native ); + TQ_CHECK_PTR(d); + +#if defined(TQ_WS_WIN) || defined(Q_OS_MAC) + d->sysd = 0; + d->sysInit(); +#endif +} + +/*! + Creates a settings object. If \a format is 'Ini' the settings will + be stored in a text file, using the Unix strategy (see above). If \a format + is 'Native', the settings will be stored in a platform specific way + (ie. the Windows registry). + + Be aware that you must call setPath() or insertSearchPath() before + you can use the TQSettings object. +*/ +TQSettings::TQSettings( Format format ) +{ + d = new TQSettingsPrivate( format ); + TQ_CHECK_PTR(d); + +#if defined(TQ_WS_WIN) || defined(Q_OS_MAC) + d->sysd = 0; + if ( format == Native ) + d->sysInit(); +#else + Q_UNUSED(format); +#endif +} + +/*! + Destroys the settings object. All modifications made to the settings + will automatically be saved. + +*/ +TQSettings::~TQSettings() +{ + sync(); + +#if defined(TQ_WS_WIN) || defined(Q_OS_MAC) + if ( d->sysd ) + d->sysClear(); +#endif + + delete d; +} + + +/*! \internal + Writes all modifications to the settings to disk. If any errors are + encountered, this function returns FALSE, otherwise it will return TRUE. +*/ +bool TQSettings::sync() +{ +#if defined(TQ_WS_WIN) || defined(Q_OS_MAC) + if ( d->sysd ) + return d->sysSync(); +#endif + if (! d->modified) + // fake success + return TRUE; + + bool success = TRUE; + TQMap::Iterator it = d->headings.begin(); + + while (it != d->headings.end()) { + // determine filename + TQSettingsHeading hd(*it); + TQSettingsHeading::Iterator hdit = hd.begin(); + TQString filename; + + TQStringList::Iterator pit = d->searchPaths.begin(); + if ( !d->globalScope ) + ++pit; + while (pit != d->searchPaths.end()) { + TQString filebase = it.key().lower().replace(TQRegExp(TQString::fromLatin1("\\s+")), "_"); + TQFileInfo di(*pit); + if ( !di.exists() ) { + TQDir dir; + dir.mkdir( *pit ); + } + + TQFileInfo fi((*pit++) + "/" + filebase + "rc"); + + if ((fi.exists() && fi.isFile() && fi.isWritable()) || + (! fi.exists() && di.isDir() +#ifndef TQ_WS_WIN + && di.isWritable() +#else + && ((qWinVersion()&TQt::WV_NT_based) > TQt::WV_2000 || di.isWritable()) +#endif + )) { + filename = fi.filePath(); + break; + } + } + + ++it; + + if ( filename.isEmpty() ) { + +#ifdef QT_CHECK_STATE + tqWarning("TQSettings::sync: filename is null/empty"); +#endif // QT_CHECK_STATE + + success = FALSE; + continue; + } + +#ifndef TQ_WS_WIN + HANDLE lockfd = openlock( filename, Q_LOCKWRITE ); +#endif + + TQFile file( filename + ".tmp" ); + if (! file.open(IO_WriteOnly)) { + +#ifdef QT_CHECK_STATE + tqWarning("TQSettings::sync: failed to open '%s' for writing", + file.name().latin1()); +#endif // QT_CHECK_STATE + + success = FALSE; + continue; + } + + // spew to file + TQTextStream stream(&file); + stream.setEncoding(TQTextStream::UnicodeUTF8); + + while (hdit != hd.end()) { + if ((*hdit).count() > 0) { + stream << "[" << hdit.key() << "]" << endl; + + TQSettingsGroup grp(*hdit); + TQSettingsGroup::Iterator grpit = grp.begin(); + + while (grpit != grp.end()) { + TQString v = grpit.data(); + if ( v.isNull() ) { + v = TQString::fromLatin1("\\0"); // escape null string + } else { + v.replace('\\', TQString::fromLatin1("\\\\")); // escape backslash + v.replace('\n', TQString::fromLatin1("\\n")); // escape newlines + } + + stream << grpit.key() << "=" << v << endl; + ++grpit; + } + + stream << endl; + } + + ++hdit; + } + + if (file.status() != IO_Ok) { + +#ifdef QT_CHECK_STATE + tqWarning("TQSettings::sync: error at end of write"); +#endif // QT_CHECK_STATE + + success = FALSE; + } + + file.close(); + + if ( success ) { + TQDir dir( TQFileInfo( file ).dir( TRUE ) ); + if ( ( dir.exists( filename ) && !dir.remove( filename ) ) || + !dir.rename( file.name(), filename, TRUE ) ) { + +#ifdef QT_CHECK_STATE + tqWarning( "TQSettings::sync: error writing file '%s'", + TQFile::encodeName( filename ).data() ); +#endif // QT_CHECK_STATE + + success = FALSE; + } + } + + // remove temporary file + file.remove(); + +#ifndef TQ_WS_WIN + closelock( lockfd ); +#endif + } + + d->modified = FALSE; + + return success; +} + + +/*! + \fn bool TQSettings::readBoolEntry(const TQString &key, bool def, bool *ok ) const + + Reads the entry specified by \a key, and returns a bool, or the + default value, \a def, if the entry couldn't be read. + If \a ok is non-null, *ok is set to TRUE if the key was read, FALSE + otherwise. + + \sa readEntry(), readNumEntry(), readDoubleEntry(), writeEntry(), removeEntry() +*/ + +/*! + \internal +*/ +bool TQSettings::readBoolEntry(const TQString &key, bool def, bool *ok ) +{ + TQString grp_key( groupKey( group(), key ) ); + if ( !qt_verify_key( grp_key ) ) { +#if defined(QT_CHECK_STATE) + tqWarning( "TQSettings::readBoolEntry: Invalid key: '%s'", grp_key.isNull() ? "(null)" : grp_key.latin1() ); +#endif + if ( ok ) + *ok = FALSE; + + return def; + } + +#if defined(TQ_WS_WIN) || defined(Q_OS_MAC) + if ( d->sysd ) + return d->sysReadBoolEntry( grp_key, def, ok ); +#endif + + TQString value = readEntry( key, ( def ? "true" : "false" ), ok ); + + if (value.lower() == "true") + return TRUE; + else if (value.lower() == "false") + return FALSE; + else if (value == "1") + return TRUE; + else if (value == "0") + return FALSE; + + if (! value.isEmpty()) + tqWarning("TQSettings::readBoolEntry: '%s' is not 'true' or 'false'", + value.latin1()); + if ( ok ) + *ok = FALSE; + return def; +} + + +/*! + \fn double TQSettings::readDoubleEntry(const TQString &key, double def, bool *ok ) const + + Reads the entry specified by \a key, and returns a double, or the + default value, \a def, if the entry couldn't be read. + If \a ok is non-null, *ok is set to TRUE if the key was read, FALSE + otherwise. + + \sa readEntry(), readNumEntry(), readBoolEntry(), writeEntry(), removeEntry() +*/ + +/*! + \internal +*/ +double TQSettings::readDoubleEntry(const TQString &key, double def, bool *ok ) +{ + TQString grp_key( groupKey( group(), key ) ); + if ( !qt_verify_key( grp_key ) ) { +#if defined(QT_CHECK_STATE) + tqWarning( "TQSettings::readDoubleEntry: Invalid key: '%s'", grp_key.isNull() ? "(null)" : grp_key.latin1() ); +#endif + if ( ok ) + *ok = FALSE; + + return def; + } + +#if defined(TQ_WS_WIN) || defined(Q_OS_MAC) + if ( d->sysd ) + return d->sysReadDoubleEntry( grp_key, def, ok ); +#endif + + TQString value = readEntry( key, TQString::number(def), ok ); + bool conv_ok; + double retval = value.toDouble( &conv_ok ); + if ( conv_ok ) + return retval; + if ( ! value.isEmpty() ) + tqWarning( "TQSettings::readDoubleEntry: '%s' is not a number", + value.latin1() ); + if ( ok ) + *ok = FALSE; + return def; +} + + +/*! + \fn int TQSettings::readNumEntry(const TQString &key, int def, bool *ok ) const + + Reads the entry specified by \a key, and returns an integer, or the + default value, \a def, if the entry couldn't be read. + If \a ok is non-null, *ok is set to TRUE if the key was read, FALSE + otherwise. + + \sa readEntry(), readDoubleEntry(), readBoolEntry(), writeEntry(), removeEntry() +*/ + +/*! + \internal +*/ +int TQSettings::readNumEntry(const TQString &key, int def, bool *ok ) +{ + TQString grp_key( groupKey( group(), key ) ); + if ( !qt_verify_key( grp_key ) ) { +#if defined(QT_CHECK_STATE) + tqWarning( "TQSettings::readNumEntry: Invalid key: '%s'", grp_key.isNull() ? "(null)" : grp_key.latin1() ); +#endif + if ( ok ) + *ok = FALSE; + return def; + } + +#if defined(TQ_WS_WIN) || defined(Q_OS_MAC) + if ( d->sysd ) + return d->sysReadNumEntry( grp_key, def, ok ); +#endif + + TQString value = readEntry( key, TQString::number( def ), ok ); + bool conv_ok; + int retval = value.toInt( &conv_ok ); + if ( conv_ok ) + return retval; + if ( ! value.isEmpty() ) + tqWarning( "TQSettings::readNumEntry: '%s' is not a number", + value.latin1() ); + if ( ok ) + *ok = FALSE; + return def; +} + + +/*! + \fn TQString TQSettings::readEntry(const TQString &key, const TQString &def, bool *ok ) const + + Reads the entry specified by \a key, and returns a TQString, or the + default value, \a def, if the entry couldn't be read. + If \a ok is non-null, *ok is set to TRUE if the key was read, FALSE + otherwise. + + \sa readListEntry(), readNumEntry(), readDoubleEntry(), readBoolEntry(), writeEntry(), removeEntry() +*/ + +/*! + \internal +*/ +TQString TQSettings::readEntry(const TQString &key, const TQString &def, bool *ok ) +{ + TQString grp_key( groupKey( group(), key ) ); + if ( !qt_verify_key( grp_key ) ) { +#if defined(QT_CHECK_STATE) + tqWarning( "TQSettings::readEntry: Invalid key: '%s'", grp_key.isNull() ? "(null)" : grp_key.latin1() ); +#endif + if ( ok ) + *ok = FALSE; + + return def; + } + +#if defined(TQ_WS_WIN) || defined(Q_OS_MAC) + if ( d->sysd ) + return d->sysReadEntry( grp_key, def, ok ); +#endif + + if ( ok ) // no, everything is not ok + *ok = FALSE; + + TQString realkey; + + if (grp_key[0] == '/') { + // parse our key + TQStringList list(TQStringList::split('/', grp_key)); + + if (list.count() < 2) { +#ifdef QT_CHECK_STATE + tqWarning("TQSettings::readEntry: invalid key '%s'", grp_key.latin1()); +#endif // QT_CHECK_STATE + if ( ok ) + *ok = FALSE; + return def; + } + + if (list.count() == 2) { + d->heading = list[0]; + d->group = "General"; + realkey = list[1]; + } else { + d->heading = list[0]; + d->group = list[1]; + + // remove the group from the list + list.remove(list.at(1)); + // remove the heading from the list + list.remove(list.at(0)); + + realkey = list.join("/"); + } + } else { + realkey = grp_key; + } + + TQSettingsGroup grp = d->readGroup(); + TQSettingsGroup::const_iterator it = grp.find( realkey ), end = grp.end(); + TQString retval = def; + if ( it != end ) { + // found the value we needed + retval = *it; + if ( ok ) *ok = TRUE; + } + return retval; +} + + +#if !defined(Q_NO_BOOL_TYPE) +/*! + Writes the boolean entry \a value into key \a key. The \a key is + created if it doesn't exist. Any previous value is overwritten by \a + value. + + If an error occurs the settings are left unchanged and FALSE is + returned; otherwise TRUE is returned. + + \warning On certain platforms, keys are required to contain at least + two components (e.g., "/foo/bar"). This limitation does not apply to + TQt 4. + + \sa readListEntry(), readNumEntry(), readDoubleEntry(), readBoolEntry(), removeEntry() +*/ +bool TQSettings::writeEntry(const TQString &key, bool value) +{ + TQString grp_key( groupKey( group(), key ) ); + if ( !qt_verify_key( grp_key ) ) { +#if defined(QT_CHECK_STATE) + tqWarning( "TQSettings::writeEntry: Invalid key: '%s'", grp_key.isNull() ? "(null)" : grp_key.latin1() ); +#endif + return FALSE; + } + +#if defined(TQ_WS_WIN) || defined(Q_OS_MAC) + if ( d->sysd ) + return d->sysWriteEntry( grp_key, value ); +#endif + TQString s(value ? "true" : "false"); + return writeEntry(key, s); +} +#endif + + +/*! + \overload + Writes the double entry \a value into key \a key. The \a key is + created if it doesn't exist. Any previous value is overwritten by \a + value. + + If an error occurs the settings are left unchanged and FALSE is + returned; otherwise TRUE is returned. + + \sa readListEntry(), readNumEntry(), readDoubleEntry(), readBoolEntry(), removeEntry() +*/ +bool TQSettings::writeEntry(const TQString &key, double value) +{ + TQString grp_key( groupKey( group(), key ) ); + if ( !qt_verify_key( grp_key ) ) { +#if defined(QT_CHECK_STATE) + tqWarning( "TQSettings::writeEntry: Invalid key: '%s'", grp_key.isNull() ? "(null)" : grp_key.latin1() ); +#endif + return FALSE; + } + +#if defined(TQ_WS_WIN) || defined(Q_OS_MAC) + if ( d->sysd ) + return d->sysWriteEntry( grp_key, value ); +#endif + TQString s(TQString::number(value)); + return writeEntry(key, s); +} + + +/*! + \overload + Writes the integer entry \a value into key \a key. The \a key is + created if it doesn't exist. Any previous value is overwritten by \a + value. + + If an error occurs the settings are left unchanged and FALSE is + returned; otherwise TRUE is returned. + + \sa readListEntry(), readNumEntry(), readDoubleEntry(), readBoolEntry(), removeEntry() +*/ +bool TQSettings::writeEntry(const TQString &key, int value) +{ + TQString grp_key( groupKey( group(), key ) ); + if ( !qt_verify_key( grp_key ) ) { +#if defined(QT_CHECK_STATE) + tqWarning( "TQSettings::writeEntry: Invalid key: '%s'", grp_key.isNull() ? "(null)" : grp_key.latin1() ); +#endif + return FALSE; + } + +#if defined(TQ_WS_WIN) || defined(Q_OS_MAC) + if ( d->sysd ) + return d->sysWriteEntry( grp_key, value ); +#endif + TQString s(TQString::number(value)); + return writeEntry(key, s); +} + + +/*! + \internal + + Writes the entry specified by \a key with the string-literal \a value, + replacing any previous setting. If \a value is zero-length or null, the + entry is replaced by an empty setting. + + \e NOTE: This function is provided because some compilers use the + writeEntry (const TQString &, bool) overload for this code: + writeEntry ("/foo/bar", "baz") + + If an error occurs, this functions returns FALSE and the object is left + unchanged. + + \sa readEntry(), removeEntry() +*/ +bool TQSettings::writeEntry(const TQString &key, const char *value) +{ + return writeEntry(key, TQString(value)); +} + + +/*! + \overload + Writes the string entry \a value into key \a key. The \a key is + created if it doesn't exist. Any previous value is overwritten by \a + value. If \a value is an empty string or a null string the key's + value will be an empty string. + + If an error occurs the settings are left unchanged and FALSE is + returned; otherwise TRUE is returned. + + \sa readListEntry(), readNumEntry(), readDoubleEntry(), readBoolEntry(), removeEntry() +*/ +bool TQSettings::writeEntry(const TQString &key, const TQString &value) +{ + TQString grp_key( groupKey( group(), key ) ); + if ( !qt_verify_key( grp_key ) ) { +#if defined(QT_CHECK_STATE) + tqWarning( "TQSettings::writeEntry: Invalid key: '%s'", grp_key.isNull() ? "(null)" : grp_key.latin1() ); +#endif + return FALSE; + } + +#if defined(TQ_WS_WIN) || defined(Q_OS_MAC) + if ( d->sysd ) + return d->sysWriteEntry( grp_key, value ); +#endif + // NOTE: we *do* allow value to be a null/empty string + + TQString realkey; + + if (grp_key[0] == '/') { + // parse our key + TQStringList list(TQStringList::split('/', grp_key)); + + if (list.count() < 2) { +#ifdef QT_CHECK_STATE + tqWarning("TQSettings::writeEntry: invalid key '%s'", grp_key.latin1()); +#endif // QT_CHECK_STATE + + return FALSE; + } + + if (list.count() == 2) { + d->heading = list[0]; + d->group = "General"; + realkey = list[1]; + } else { + d->heading = list[0]; + d->group = list[1]; + + // remove the group from the list + list.remove(list.at(1)); + // remove the heading from the list + list.remove(list.at(0)); + + realkey = list.join("/"); + } + } else { + realkey = grp_key; + } + + d->writeGroup(realkey, value); + return TRUE; +} + + +/*! + Removes the entry specified by \a key. + + Returns true if the entry was successfully removed; otherwise + returns false. Note that removing the last entry in any given + folder, will also remove the folder. + + \sa readEntry(), writeEntry() +*/ +bool TQSettings::removeEntry(const TQString &key) +{ + TQString grp_key( groupKey( group(), key ) ); + if ( !qt_verify_key( grp_key ) ) { +#if defined(QT_CHECK_STATE) + tqWarning( "TQSettings::removeEntry: Invalid key: '%s'", grp_key.isNull() ? "(null)" : grp_key.latin1() ); +#endif + return FALSE; + } + +#if defined(TQ_WS_WIN) || defined(Q_OS_MAC) + if ( d->sysd ) + return d->sysRemoveEntry( grp_key ); +#endif + + TQString realkey; + if (grp_key[0] == '/') { + // parse our key + TQStringList list(TQStringList::split('/', grp_key)); + + if (list.count() < 2) { +#ifdef QT_CHECK_STATE + tqWarning("TQSettings::removeEntry: invalid key '%s'", grp_key.latin1()); +#endif // QT_CHECK_STATE + + return FALSE; + } + + if (list.count() == 2) { + d->heading = list[0]; + d->group = "General"; + realkey = list[1]; + } else { + d->heading = list[0]; + d->group = list[1]; + + // remove the group from the list + list.remove(list.at(1)); + // remove the heading from the list + list.remove(list.at(0)); + + realkey = list.join("/"); + } + } else { + realkey = grp_key; + } + + d->removeGroup(realkey); + return TRUE; +} + + +/*! + Returns a list of the keys which contain entries under \a key. Does \e + not return any keys that contain subkeys. + + Example settings: + \code + /MyCompany/MyApplication/background color + /MyCompany/MyApplication/foreground color + /MyCompany/MyApplication/geometry/x + /MyCompany/MyApplication/geometry/y + /MyCompany/MyApplication/geometry/width + /MyCompany/MyApplication/geometry/height + \endcode + \code + TQStringList keys = settings.entryList( "/MyCompany/MyApplication" ); + \endcode + + In the above example, \c keys will contain 'background color' and + 'foreground color'. It will not contain 'geometry' because this key + contains subkeys not entries. + + To access the geometry values, you could either use subkeyList() + to read the keys then read each entry, or simply read each entry + directly by specifying its full key, e.g. + "/MyCompany/MyApplication/geometry/y". + + \sa subkeyList() +*/ +TQStringList TQSettings::entryList(const TQString &key) const +{ + TQString grp_key( groupKey( group(), key ) ); + if ( !qt_verify_key( grp_key ) ) { +#if defined(QT_CHECK_STATE) + tqWarning( "TQSettings::entryList: Invalid key: %s", grp_key.isNull() ? "(null)" : grp_key.latin1() ); +#endif + return TQStringList(); + } + +#if defined(TQ_WS_WIN) || defined(Q_OS_MAC) + if ( d->sysd ) + return d->sysEntryList( grp_key ); +#endif + + TQString realkey; + if (grp_key[0] == '/') { + // parse our key + TQStringList list(TQStringList::split('/', grp_key)); + + if (list.count() < 1) { +#ifdef QT_CHECK_STATE + tqWarning("TQSettings::listEntries: invalid key '%s'", grp_key.latin1()); +#endif // QT_CHECK_STATE + + return TQStringList(); + } + + if (list.count() == 1) { + d->heading = list[0]; + d->group = "General"; + } else { + d->heading = list[0]; + d->group = list[1]; + + // remove the group from the list + list.remove(list.at(1)); + // remove the heading from the list + list.remove(list.at(0)); + + realkey = list.join("/"); + } + } else + realkey = grp_key; + + TQSettingsGroup grp = d->readGroup(); + TQSettingsGroup::Iterator it = grp.begin(); + TQStringList ret; + TQString itkey; + while (it != grp.end()) { + itkey = it.key(); + ++it; + + if ( realkey.length() > 0 ) { + if ( itkey.left( realkey.length() ) != realkey ) + continue; + else + itkey.remove( 0, realkey.length() + 1 ); + } + + if ( itkey.find( '/' ) != -1 ) + continue; + + ret << itkey; + } + + return ret; +} + + +/*! + Returns a list of the keys which contain subkeys under \a key. Does \e + not return any keys that contain entries. + + Example settings: + \code + /MyCompany/MyApplication/background color + /MyCompany/MyApplication/foreground color + /MyCompany/MyApplication/geometry/x + /MyCompany/MyApplication/geometry/y + /MyCompany/MyApplication/geometry/width + /MyCompany/MyApplication/geometry/height + /MyCompany/MyApplication/recent files/1 + /MyCompany/MyApplication/recent files/2 + /MyCompany/MyApplication/recent files/3 + \endcode + \code + TQStringList keys = settings.subkeyList( "/MyCompany/MyApplication" ); + \endcode + + In the above example, \c keys will contain 'geometry' and + 'recent files'. It will not contain 'background color' or + 'foreground color' because those keys contain entries not + subkeys. To get a list of keys that contain entries rather than + subkeys use entryList() instead. + + \warning In the above example, if TQSettings is writing to an Ini file, + then a call to + \code subkeyList("/MyCompany") \endcode + will return an empty list. This happens because a key like + \code /MyCompany/MyApplication/background color \endcode + is written to the file \e{"mycompanyrc"}, under the section \e{[MyApplication]}. + This call is therefore a request to list the sections in an ini file, which + is not supported in this version of TQSettings. This is a known issue which + will be fixed in TQt-4. + + \sa entryList() +*/ +TQStringList TQSettings::subkeyList(const TQString &key) const +{ + TQString grp_key( groupKey( group(), key ) ); + if ( !qt_verify_key( grp_key ) ) { +#if defined(QT_CHECK_STATE) + tqWarning( "TQSettings::subkeyList: Invalid key: %s", grp_key.isNull() ? "(null)" : grp_key.latin1() ); +#endif + return TQStringList(); + } + +#if defined(TQ_WS_WIN) || defined(Q_OS_MAC) + if ( d->sysd ) + return d->sysSubkeyList( grp_key ); +#endif + + TQString realkey; + int subkeycount = 2; + if (grp_key[0] == '/') { + // parse our key + TQStringList list(TQStringList::split('/', grp_key)); + + if (list.count() < 1) { +#ifdef QT_CHECK_STATE + tqWarning("TQSettings::subkeyList: invalid key '%s'", grp_key.latin1()); +#endif // QT_CHECK_STATE + + return TQStringList(); + } + + subkeycount = (int)list.count(); + + if (list.count() == 1) { + d->heading = list[0]; + d->group = "General"; + } else { + d->heading = list[0]; + d->group = list[1]; + + // remove the group from the list + list.remove(list.at(1)); + // remove the heading from the list + list.remove(list.at(0)); + + realkey = list.join("/"); + } + + } else + realkey = grp_key; + + TQStringList ret; + if ( subkeycount == 1 ) { + TQMap::Iterator it = d->headings.begin(); + while ( it != d->headings.end() ) { + if ( it.key() != "General" && ! ret.contains( it.key() ) ) + ret << it.key(); + ++it; + } + + return ret; + } + + TQSettingsGroup grp = d->readGroup(); + TQSettingsGroup::Iterator it = grp.begin(); + TQString itkey; + while (it != grp.end()) { + itkey = it.key(); + ++it; + + if ( realkey.length() > 0 ) { + if ( itkey.left( realkey.length() ) != realkey + || itkey.length()+1 < realkey.length() + || itkey[(int)realkey.length()] != '/') + continue; + else + itkey.remove( 0, realkey.length() + 1 ); + } + + int slash = itkey.find( '/' ); + if ( slash == -1 ) + continue; + itkey.truncate( slash ); + + if ( ! ret.contains( itkey ) ) + ret << itkey; + } + + return ret; +} + + +/*! + \internal + + This function returns the time of last modification for \a key. +*/ +TQDateTime TQSettings::lastModificationTime( const TQString &key ) +{ + TQString grp_key( groupKey( group(), key ) ); + if ( !qt_verify_key( grp_key ) ) { +#if defined(QT_CHECK_STATE) + tqWarning( "TQSettings::lastModificationTime: Invalid key '%s'", grp_key.isNull() ? "(null)" : grp_key.latin1() ); +#endif + return TQDateTime(); + } + +#if defined(TQ_WS_WIN) || defined(Q_OS_MAC) + if ( d->sysd ) + return TQDateTime(); +#endif + + if (grp_key[0] == '/') { + // parse our key + TQStringList list(TQStringList::split('/', grp_key)); + + if (list.count() < 2) { +#ifdef QT_CHECK_STATE + tqWarning("TQSettings::lastModificationTime: Invalid key '%s'", grp_key.latin1()); +#endif // QT_CHECK_STATE + + return TQDateTime(); + } + + if (list.count() == 2) { + d->heading = list[0]; + d->group = "General"; + } else { + d->heading = list[0]; + d->group = list[1]; + } + } + + return d->modificationTime(); +} + + +/*! + \overload + \obsolete + + Writes the string list entry \a value into key \a key. The \a key + is created if it doesn't exist. Any previous value is overwritten + by \a value. The list is stored as a sequence of strings separated + by \a separator (using TQStringList::join()), so none of the + strings in the list should contain the separator. If the list is + empty or null the key's value will be an empty string. + + \warning The list should not contain empty or null strings, as + readListEntry() will use TQStringList::split() to recreate the + list. As the documentation states, TQStringList::split() will omit + empty strings from the list. Because of this, it is impossible to + retrieve identical list data that is stored with this function. + We recommend using the writeEntry() and readListEntry() overloads + that do not take a \a separator argument. + + + If an error occurs the settings are left unchanged and FALSE is + returned; otherwise returns TRUE. + + \sa readListEntry(), readNumEntry(), readDoubleEntry(), readBoolEntry(), removeEntry(), TQStringList::join() +*/ +bool TQSettings::writeEntry(const TQString &key, const TQStringList &value, + const TQChar &separator) +{ + TQString s(value.join(separator)); + return writeEntry(key, s); +} + +/*! + \overload + + Writes the string list entry \a value into key \a key. The \a key + is created if it doesn't exist. Any previous value is overwritten + by \a value. + + If an error occurs the settings are left unchanged and FALSE is + returned; otherwise returns TRUE. + + \sa readListEntry(), readNumEntry(), readDoubleEntry(), readBoolEntry(), removeEntry() +*/ +bool TQSettings::writeEntry(const TQString &key, const TQStringList &value) +{ + TQString s; + for (TQStringList::ConstIterator it=value.begin(); it!=value.end(); ++it) { + TQString el = *it; + if ( el.isNull() ) { + el = "^0"; + } else { + el.replace("^", "^^"); + } + s+=el; + s+="^e"; // end of element + } + return writeEntry(key, s); +} + + +/*! + \overload TQStringList TQSettings::readListEntry(const TQString &key, const TQChar &separator, bool *ok ) const + \obsolete + + Reads the entry specified by \a key as a string. The \a separator + is used to create a TQStringList by calling TQStringList::split(\a + separator, entry). If \a ok is not 0: \a *ok is set to TRUE + if the key was read, otherwise \a *ok is set to FALSE. + + \warning As the documentation states, TQStringList::split() will + omit empty strings from the list. Because of this, it is + impossible to retrieve identical list data with this function. We + recommend using the readListEntry() and writeEntry() overloads + that do not take a \a separator argument. + + Note that if you want to iterate over the list, you should iterate + over a copy, e.g. + \code + TQStringList list = mySettings.readListEntry( "size", " " ); + TQStringList::Iterator it = list.begin(); + while( it != list.end() ) { + myProcessing( *it ); + ++it; + } + \endcode + + \sa readEntry(), readDoubleEntry(), readBoolEntry(), writeEntry(), removeEntry(), TQStringList::split() +*/ + +/*! + \internal +*/ +TQStringList TQSettings::readListEntry(const TQString &key, const TQChar &separator, bool *ok ) +{ + TQString value = readEntry( key, TQString::null, ok ); + if ( ok && !*ok ) + return TQStringList(); + + return TQStringList::split(separator, value); +} + +/*! + \fn TQStringList TQSettings::readListEntry(const TQString &key, bool *ok ) const + Reads the entry specified by \a key as a string. If \a ok is not + 0, \a *ok is set to TRUE if the key was read, otherwise \a *ok is + set to FALSE. + + Note that if you want to iterate over the list, you should iterate + over a copy, e.g. + \code + TQStringList list = mySettings.readListEntry( "recentfiles" ); + TQStringList::Iterator it = list.begin(); + while( it != list.end() ) { + myProcessing( *it ); + ++it; + } + \endcode + + \sa readEntry(), readDoubleEntry(), readBoolEntry(), writeEntry(), removeEntry(), TQStringList::split() +*/ + +/*! + \internal +*/ +TQStringList TQSettings::readListEntry(const TQString &key, bool *ok ) +{ + TQString value = readEntry( key, TQString::null, ok ); + if ( ok && !*ok ) + return TQStringList(); + TQStringList l; + TQString s; + bool esc=FALSE; + for (int i=0; i<(int)value.length(); i++) { + if ( esc ) { + if ( value[i] == 'e' ) { // end-of-string + l.append(s); + s=""; + } else if ( value[i] == '0' ) { // null string + s=TQString::null; + } else { + s.append(value[i]); + } + esc=FALSE; + } else if ( value[i] == '^' ) { + esc = TRUE; + } else { + s.append(value[i]); + if ( i == (int)value.length()-1 ) + l.append(s); + } + } + return l; +} + +#ifdef Q_OS_MAC +void qt_setSettingsBasePath(const TQString &); //tqsettings_mac.cpp +#endif + +/*! + Insert platform-dependent paths from platform-independent information. + + The \a domain should be an Internet domain name + controlled by the producer of the software, eg. Trolltech products + use "trolltech.com". + + The \a product should be the official name of the product. + + The \a scope should be + TQSettings::User for user-specific settings, or + TQSettings::Global for system-wide settings (generally + these will be read-only to many users). + + Not all information is relevant on all systems. +*/ + +void TQSettings::setPath( const TQString &domain, const TQString &product, Scope scope ) +{ +// On Windows, any trailing ".com(\..*)" is stripped from the domain. The +// Global scope corresponds to HKEY_LOCAL_MACHINE, and User corresponds to +// HKEY_CURRENT_USER. Note that on some installations, not all users can +// write to the Global scope. On UNIX, any trailing ".com(\..*)" is stripped +// from the domain. The Global scope corresponds to "/opt" (this would be +// configurable at library build time - eg. to "/usr/local" or "/usr"), +// while the User scope corresponds to $HOME/.*rc. +// Note that on most installations, not all users can write to the System +// scope. +// +// On MacOS X, if there is no "." in domain, append ".com", then reverse the +// order of the elements (Mac OS uses "com.apple.finder" as domain+product). +// The Global scope corresponds to /Library/Preferences/*.plist, while the +// User scope corresponds to ~/Library/Preferences/*.plist. +// Note that on most installations, not all users can write to the System +// scope. + d->globalScope = scope == Global; + + TQString actualSearchPath; + int lastDot = domain.findRev( '.' ); + +#if defined(TQ_WS_WIN) + actualSearchPath = "/" + domain.mid( 0, lastDot ) + "/" + product; + insertSearchPath( Windows, actualSearchPath ); +#elif defined(Q_OS_MAC) + if(lastDot != -1) { + TQString topLevelDomain = domain.right( domain.length() - lastDot - 1 ) + "."; + if ( !topLevelDomain.isEmpty() ) + qt_setSettingsBasePath( topLevelDomain ); + } + actualSearchPath = "/" + domain.left( lastDot ) + "." + product; + insertSearchPath( Mac, actualSearchPath ); +#else + if (scope == User) + actualSearchPath = TQDir::homeDirPath() + "/."; + else + actualSearchPath = TQString(tqInstallPathSysconf()) + "/"; + actualSearchPath += domain.mid( 0, lastDot ) + "/" + product; + insertSearchPath( Unix, actualSearchPath ); +#endif +} + +/*! + Appends \a group to the current key prefix. + + \code + TQSettings settings; + settings.beginGroup( "/MainWindow" ); + // read values + settings.endGroup(); + \endcode +*/ +void TQSettings::beginGroup( const TQString &group ) +{ + d->groupStack.push( group ); + d->groupDirty = TRUE; +} + +/*! + Undo previous calls to beginGroup(). Note that a single beginGroup("a/b/c") is undone + by a single call to endGroup(). + + \code + TQSettings settings; + settings.beginGroup( "/MainWindow/Geometry" ); + // read values + settings.endGroup(); + \endcode +*/ +void TQSettings::endGroup() +{ + d->groupStack.pop(); + d->groupDirty = TRUE; +} + +/*! + Set the current key prefix to the empty string. +*/ +void TQSettings::resetGroup() +{ + d->groupStack.clear(); + d->groupDirty = FALSE; + d->groupPrefix = TQString::null; +} + +/*! + Returns the current key prefix, or a null string if there is no key prefix set. + + \sa beginGroup(); +*/ +TQString TQSettings::group() const +{ + if ( d->groupDirty ) { + d->groupDirty = FALSE; + d->groupPrefix = TQString::null; + + TQValueStack::Iterator it = d->groupStack.begin(); + while ( it != d->groupStack.end() ) { + TQString group = *it; + ++it; + if ( group[0] != '/' ) + group.prepend( "/" ); + d->groupPrefix += group; + } + } + return d->groupPrefix; +} + +#endif diff --git a/src/tools/tqsettings.h b/src/tools/tqsettings.h new file mode 100644 index 000000000..ee8e8e3b2 --- /dev/null +++ b/src/tools/tqsettings.h @@ -0,0 +1,159 @@ +/**************************************************************************** +** +** Definition of TQSettings class +** +** Created : 000626 +** +** Copyright (C) 2000-2008 Trolltech ASA. All rights reserved. +** +** This file is part of the tools module of the TQt GUI Toolkit. +** +** This file may be used under the terms of the GNU General +** Public License versions 2.0 or 3.0 as published by the Free +** Software Foundation and appearing in the files LICENSE.GPL2 +** and LICENSE.GPL3 included in the packaging of this file. +** Alternatively you may (at your option) use any later version +** of the GNU General Public License if such license has been +** publicly approved by Trolltech ASA (or its successors, if any) +** and the KDE Free TQt Foundation. +** +** Please review the following information to ensure GNU General +** Public Licensing requirements will be met: +** http://trolltech.com/products/qt/licenses/licensing/opensource/. +** If you are unsure which license is appropriate for your use, please +** review the following information: +** http://trolltech.com/products/qt/licenses/licensing/licensingoverview +** or contact the sales department at sales@trolltech.com. +** +** This file may be used under the terms of the Q Public License as +** defined by Trolltech ASA and appearing in the file LICENSE.TQPL +** included in the packaging of this file. Licensees holding valid TQt +** Commercial licenses may use this file in accordance with the TQt +** Commercial License Agreement provided with the Software. +** +** This file is provided "AS IS" with NO WARRANTY OF ANY KIND, +** INCLUDING THE WARRANTIES OF DESIGN, MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE. Trolltech reserves all rights not granted +** herein. +** +**********************************************************************/ + +#ifndef TQSETTINGS_H +#define TQSETTINGS_H + +#ifndef QT_H +#include "tqdatetime.h" +#include "tqstringlist.h" +#endif // QT_H + +#ifndef TQT_NO_SETTINGS + +class TQSettingsPrivate; + + +class TQ_EXPORT TQSettings +{ +public: + enum Format { + Native = 0, + Ini + }; + enum System { + Unix = 0, + Windows, + Mac + }; + enum Scope { + User, + Global + }; + + TQSettings(); + TQSettings( Format format ); + + ~TQSettings(); + +#if !defined(Q_NO_BOOL_TYPE) + bool writeEntry( const TQString &, bool ); +#endif + bool writeEntry( const TQString &, double ); + bool writeEntry( const TQString &, int ); + bool writeEntry( const TQString &, const char * ); + bool writeEntry( const TQString &, const TQString & ); + bool writeEntry( const TQString &, const TQStringList & ); + bool writeEntry( const TQString &, const TQStringList &, const TQChar& sep ); + + TQStringList entryList(const TQString &) const; + TQStringList subkeyList(const TQString &) const; + + //### remove non const versions in 4.0 + TQStringList readListEntry( const TQString &, bool * = 0 ); + TQStringList readListEntry( const TQString &, const TQChar& sep, bool * = 0 ); + TQString readEntry( const TQString &, const TQString &def = TQString::null, bool * = 0 ); + int readNumEntry( const TQString &, int def = 0, bool * = 0 ); + double readDoubleEntry( const TQString &, double def = 0, bool * = 0 ); + bool readBoolEntry( const TQString &, bool def = FALSE, bool * = 0 ); + + //### make those non-inlined in 4.0 + TQStringList readListEntry( const TQString &key, bool *ok = 0 ) const + { + TQSettings *that = (TQSettings*)this; + return that->readListEntry( key, ok ); + } + TQStringList readListEntry( const TQString &key, const TQChar& sep, bool *ok = 0 ) const + { + TQSettings *that = (TQSettings*)this; + return that->readListEntry( key, sep, ok ); + } + TQString readEntry( const TQString &key, const TQString &def = TQString::null, + bool *ok = 0 ) const + { + TQSettings *that = (TQSettings*)this; + return that->readEntry( key, def, ok ); + } + int readNumEntry( const TQString &key, int def = 0, bool *ok = 0 ) const + { + TQSettings *that = (TQSettings*)this; + return that->readNumEntry( key, def, ok ); + } + + double readDoubleEntry( const TQString &key, double def = 0, bool *ok = 0 ) const + { + TQSettings *that = (TQSettings*)this; + return that->readDoubleEntry( key, def, ok ); + } + bool readBoolEntry( const TQString &key, bool def = FALSE, bool *ok = 0 ) const + { + TQSettings *that = (TQSettings*)this; + return that->readBoolEntry( key, def, ok ); + } + + bool removeEntry( const TQString & ); + + void insertSearchPath( System, const TQString & ); + void removeSearchPath( System, const TQString & ); + + void setPath( const TQString &domain, const TQString &product, Scope = Global ); + + void beginGroup( const TQString &group ); + void endGroup(); + void resetGroup(); + TQString group() const; + + bool sync(); + +private: + TQSettingsPrivate *d; + +#if defined(TQ_DISABLE_COPY) + TQSettings(const TQSettings &); + TQSettings &operator=(const TQSettings &); +#endif + + TQDateTime lastModificationTime( const TQString & ); + + friend class TQApplication; +}; + +#endif // TQT_NO_SETTINGS +#endif // TQSETTINGS_H diff --git a/src/tools/tqsettings_p.h b/src/tools/tqsettings_p.h new file mode 100644 index 000000000..75318492d --- /dev/null +++ b/src/tools/tqsettings_p.h @@ -0,0 +1,148 @@ +/**************************************************************************** +** +** Definition of TQSettings related classes +** +** Created : 990124 +** +** Copyright (C) 1999-2008 Trolltech ASA. All rights reserved. +** +** This file is part of the kernel module of the TQt GUI Toolkit. +** +** This file may be used under the terms of the GNU General +** Public License versions 2.0 or 3.0 as published by the Free +** Software Foundation and appearing in the files LICENSE.GPL2 +** and LICENSE.GPL3 included in the packaging of this file. +** Alternatively you may (at your option) use any later version +** of the GNU General Public License if such license has been +** publicly approved by Trolltech ASA (or its successors, if any) +** and the KDE Free TQt Foundation. +** +** Please review the following information to ensure GNU General +** Public Licensing requirements will be met: +** http://trolltech.com/products/qt/licenses/licensing/opensource/. +** If you are unsure which license is appropriate for your use, please +** review the following information: +** http://trolltech.com/products/qt/licenses/licensing/licensingoverview +** or contact the sales department at sales@trolltech.com. +** +** This file may be used under the terms of the Q Public License as +** defined by Trolltech ASA and appearing in the file LICENSE.TQPL +** included in the packaging of this file. Licensees holding valid TQt +** Commercial licenses may use this file in accordance with the TQt +** Commercial License Agreement provided with the Software. +** +** This file is provided "AS IS" with NO WARRANTY OF ANY KIND, +** INCLUDING THE WARRANTIES OF DESIGN, MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE. Trolltech reserves all rights not granted +** herein. +** +**********************************************************************/ + +#ifndef TQSETTINGS_P_H +#define TQSETTINGS_P_H + +// +// W A R N I N G +// ------------- +// +// This file is not part of the TQt API. It exists for the convenience +// of TQSettings. This header file may change from version to +// version without notice, or even be removed. +// +// We mean it. +// +// + +#ifndef QT_H +#include "tqstringlist.h" +#include "tqmap.h" +#include "tqvaluestack.h" +#endif // QT_H + +#ifndef TQT_NO_SETTINGS +class TQSettingsSysPrivate; + +// TQSettingsGroup is a map of key/value pairs +class TQSettingsGroup : public TQMap +{ +public: + TQSettingsGroup(); + + bool modified; +}; + +// TQSettingsHeading is a map of heading/group pairs +class TQSettingsHeading : public TQMap +{ +public: + TQSettingsHeading::Iterator git; + void read(const TQString &); + void parseLine(TQTextStream &); +}; + + +class TQSettingsPrivate +{ +public: + TQSettingsPrivate( TQSettings::Format format ); + ~TQSettingsPrivate(); + + TQSettingsGroup readGroup(); + void removeGroup(const TQString &); + void writeGroup(const TQString &, const TQString &); + TQDateTime modificationTime(); + + TQStringList searchPaths; + TQMap headings; + TQString group; + TQString heading; + + /*### static data brings threading trouble + static TQString *defProduct; + static TQString *defDomain; + */ + TQValueStack groupStack; + TQString groupPrefix; + + bool groupDirty :1; + bool modified :1; + bool globalScope :1; + +#if defined(TQ_WS_WIN) || defined(Q_OS_MAC) + // system dependent implementations to use the + // system specific setting database (ie. registry on Windows) + + TQSettingsSysPrivate *sysd; + void sysInit(); + void sysClear(); + +#if !defined(Q_NO_BOOL_TYPE) + bool sysWriteEntry( const TQString &, bool ); +#endif + bool sysWriteEntry( const TQString &, double ); + bool sysWriteEntry( const TQString &, int ); + bool sysWriteEntry( const TQString &, const TQString & ); + bool sysWriteEntry( const TQString &, const TQStringList & ); + bool sysWriteEntry( const TQString &, const TQStringList &, const TQChar& sep ); + + TQStringList sysEntryList(const TQString &) const; + TQStringList sysSubkeyList(const TQString &) const; + + TQStringList sysReadListEntry( const TQString &, bool * = 0 ) const; + TQStringList sysReadListEntry( const TQString &, const TQChar& sep, bool * = 0 ) const; + TQString sysReadEntry( const TQString &, const TQString &def = TQString::null, bool * = 0 ) const; + int sysReadNumEntry( const TQString &, int def = 0, bool * = 0 ) const; + double sysReadDoubleEntry( const TQString &, double def = 0, bool * = 0 ) const; + bool sysReadBoolEntry( const TQString &, bool def = 0, bool * = 0 ) const; + + bool sysRemoveEntry( const TQString & ); + + bool sysSync(); + + void sysInsertSearchPath( TQSettings::System, const TQString & ); + void sysRemoveSearchPath( TQSettings::System, const TQString & ); +#endif + +}; +#endif //TQT_NO_SETTINGS +#endif // TQSETTINGS_P_H diff --git a/src/tools/tqstring.cpp b/src/tools/tqstring.cpp index 86b1add58..58a377cd7 100644 --- a/src/tools/tqstring.cpp +++ b/src/tools/tqstring.cpp @@ -52,7 +52,7 @@ #include "tqstring.h" #include "tqregexp.h" -#include "ntqdatastream.h" +#include "tqdatastream.h" #ifndef TQT_NO_TEXTCODEC #include "tqtextcodec.h" #endif diff --git a/src/tools/tqstringlist.cpp b/src/tools/tqstringlist.cpp index 8e08a4f08..43637c203 100644 --- a/src/tools/tqstringlist.cpp +++ b/src/tools/tqstringlist.cpp @@ -43,7 +43,7 @@ #ifndef TQT_NO_STRINGLIST #include "tqregexp.h" #include "tqstrlist.h" -#include "ntqdatastream.h" +#include "tqdatastream.h" #include "ntqtl.h" /*! diff --git a/src/tools/tqstrlist.h b/src/tools/tqstrlist.h index 4bbcc2ca0..2815b609e 100644 --- a/src/tools/tqstrlist.h +++ b/src/tools/tqstrlist.h @@ -44,7 +44,7 @@ #ifndef QT_H #include "tqstring.h" #include "tqptrlist.h" -#include "ntqdatastream.h" +#include "tqdatastream.h" #endif // QT_H #if defined(Q_QDOC) diff --git a/src/tools/tqstrvec.h b/src/tools/tqstrvec.h index d80bfb979..2490c828b 100644 --- a/src/tools/tqstrvec.h +++ b/src/tools/tqstrvec.h @@ -44,7 +44,7 @@ #ifndef QT_H #include "tqstring.h" #include "tqptrvector.h" -#include "ntqdatastream.h" +#include "tqdatastream.h" #endif // QT_H class TQ_EXPORT TQStrVec : public TQPtrVector diff --git a/src/tools/tqtextstream.cpp b/src/tools/tqtextstream.cpp index 0a911b0ed..20f6301e9 100644 --- a/src/tools/tqtextstream.cpp +++ b/src/tools/tqtextstream.cpp @@ -43,8 +43,8 @@ #ifndef TQT_NO_TEXTSTREAM #include "tqtextcodec.h" #include "tqregexp.h" -#include "ntqbuffer.h" -#include "ntqfile.h" +#include "tqbuffer.h" +#include "tqfile.h" #include #include #include diff --git a/src/tools/tqtextstream.h b/src/tools/tqtextstream.h index ab2366b39..acfea9704 100644 --- a/src/tools/tqtextstream.h +++ b/src/tools/tqtextstream.h @@ -42,7 +42,7 @@ #define TQTEXTSTREAM_H #ifndef QT_H -#include "ntqiodevice.h" +#include "tqiodevice.h" #include "tqstring.h" #include #endif // QT_H diff --git a/src/tools/tqvaluelist.h b/src/tools/tqvaluelist.h index 4056290df..8a5bcb841 100644 --- a/src/tools/tqvaluelist.h +++ b/src/tools/tqvaluelist.h @@ -44,7 +44,7 @@ #ifndef QT_H #include "ntqtl.h" #include "ntqshared.h" -#include "ntqdatastream.h" +#include "tqdatastream.h" #endif // QT_H #ifndef TQT_NO_STL diff --git a/src/tools/tqvaluevector.h b/src/tools/tqvaluevector.h index 90dc45e10..fd45bce85 100644 --- a/src/tools/tqvaluevector.h +++ b/src/tools/tqvaluevector.h @@ -44,7 +44,7 @@ #ifndef QT_H #include "ntqtl.h" #include "ntqshared.h" -#include "ntqdatastream.h" +#include "tqdatastream.h" #endif // QT_H #ifndef TQT_NO_STL -- cgit v1.2.1