kdecore Library API Documentation

kdebug.cpp

00001 /* This file is part of the KDE libraries
00002     Copyright (C) 1997 Matthias Kalle Dalheimer (kalle@kde.org)
00003                   2002 Holger Freyther (freyther@kde.org)
00004 
00005     This library is free software; you can redistribute it and/or
00006     modify it under the terms of the GNU Library General Public
00007     License as published by the Free Software Foundation; either
00008     version 2 of the License, or (at your option) any later version.
00009 
00010     This library is distributed in the hope that it will be useful,
00011     but WITHOUT ANY WARRANTY; without even the implied warranty of
00012     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
00013     Library General Public License for more details.
00014 
00015     You should have received a copy of the GNU Library General Public License
00016     along with this library; see the file COPYING.LIB.  If not, write to
00017     the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
00018     Boston, MA 02111-1307, USA.
00019 */
00020 
00021 #include "kdebug.h"
00022 
00023 #ifdef NDEBUG
00024 #undef kdDebug
00025 #undef kdBacktrace
00026 #endif
00027 
00028 #include "kdebugdcopiface.h"
00029 
00030 #include "kapplication.h"
00031 #include "kglobal.h"
00032 #include "kinstance.h"
00033 #include "kstandarddirs.h"
00034 
00035 #include <qmessagebox.h>
00036 #include <klocale.h>
00037 #include <qfile.h>
00038 #include <qintdict.h>
00039 #include <qstring.h>
00040 #include <qdatetime.h>
00041 #include <qpoint.h>
00042 #include <qrect.h>
00043 #include <qregion.h>
00044 #include <qstringlist.h>
00045 #include <qpen.h>
00046 #include <qbrush.h>
00047 #include <qsize.h>
00048 
00049 #include <kurl.h>
00050 
00051 #include <stdlib.h> // abort
00052 #include <unistd.h> // getpid
00053 #include <stdarg.h> // vararg stuff
00054 #include <ctype.h>      // isprint
00055 #include <syslog.h>
00056 #include <errno.h>
00057 #include <string.h>
00058 #include <kconfig.h>
00059 #include "kstaticdeleter.h"
00060 #include <config.h>
00061 
00062 #ifdef HAVE_BACKTRACE
00063 #include <execinfo.h>
00064 #endif
00065 
00066 class KDebugEntry;
00067 
00068 class KDebugEntry
00069 {
00070 public:
00071     KDebugEntry (int n, const QCString& d) {number=n; descr=d;}
00072     unsigned int number;
00073     QCString descr;
00074 };
00075 
00076 static QIntDict<KDebugEntry> *KDebugCache;
00077 
00078 static KStaticDeleter< QIntDict<KDebugEntry> > kdd;
00079 
00080 static QCString getDescrFromNum(unsigned int _num)
00081 {
00082   if (!KDebugCache) {
00083     kdd.setObject(KDebugCache, new QIntDict<KDebugEntry>( 601 ));
00084     // Do not call this deleter from ~KApplication
00085     KGlobal::unregisterStaticDeleter(&kdd);
00086     KDebugCache->setAutoDelete(true);
00087   }
00088 
00089   KDebugEntry *ent = KDebugCache->find( _num );
00090   if ( ent )
00091     return ent->descr;
00092 
00093   if ( !KDebugCache->isEmpty() ) // areas already loaded
00094     return QCString();
00095 
00096   QString filename(locate("config","kdebug.areas"));
00097   if (filename.isEmpty())
00098       return QCString();
00099 
00100   QFile file(filename);
00101   if (!file.open(IO_ReadOnly)) {
00102     qWarning("Couldn't open %s", filename.local8Bit().data());
00103     file.close();
00104     return QCString();
00105   }
00106 
00107   uint lineNumber=0;
00108   QCString line(1024);
00109   int len;
00110 
00111   while (( len = file.readLine(line.data(),line.size()-1) ) > 0) {
00112       int i=0;
00113       ++lineNumber;
00114 
00115       while (line[i] && line[i] <= ' ')
00116         i++;
00117 
00118       unsigned char ch=line[i];
00119 
00120       if ( !ch || ch =='#' || ch =='\n')
00121           continue; // We have an eof, a comment or an empty line
00122 
00123       if (ch < '0' && ch > '9') {
00124           qWarning("Syntax error: no number (line %u)",lineNumber);
00125           continue;
00126       }
00127 
00128       const int numStart=i;
00129       do {
00130           ch=line[++i];
00131       } while ( ch >= '0' && ch <= '9');
00132 
00133       const Q_ULONG number =line.mid(numStart,i).toULong();
00134 
00135       while (line[i] && line[i] <= ' ')
00136         i++;
00137 
00138       KDebugCache->insert(number, new KDebugEntry(number, line.mid(i, len-i-1)));
00139   }
00140   file.close();
00141 
00142   ent = KDebugCache->find( _num );
00143   if ( ent )
00144       return ent->descr;
00145 
00146   return QCString();
00147 }
00148 
00149 enum DebugLevels {
00150     KDEBUG_INFO=    0,
00151     KDEBUG_WARN=    1,
00152     KDEBUG_ERROR=   2,
00153     KDEBUG_FATAL=   3
00154 };
00155 
00156 
00157 struct kDebugPrivate {
00158   kDebugPrivate() :
00159     oldarea(0), config(0) { }
00160 
00161   ~kDebugPrivate() { delete config; }
00162 
00163   QCString aAreaName;
00164   unsigned int oldarea;
00165   KConfig *config;
00166 };
00167 
00168 static kDebugPrivate *kDebug_data = 0;
00169 static KStaticDeleter<kDebugPrivate> pcd;
00170 static KStaticDeleter<KDebugDCOPIface> dcopsd;
00171 static KDebugDCOPIface* kDebugDCOPIface = 0;
00172 
00173 static void kDebugBackend( unsigned short nLevel, unsigned int nArea, const char *data)
00174 {
00175   if ( !kDebug_data )
00176   {
00177       pcd.setObject(kDebug_data, new kDebugPrivate());
00178       // Do not call this deleter from ~KApplication
00179       KGlobal::unregisterStaticDeleter(&pcd);
00180 
00181       // create the dcop interface if it has not been created yet
00182       if (!kDebugDCOPIface)
00183       {
00184           kDebugDCOPIface = dcopsd.setObject(kDebugDCOPIface, new KDebugDCOPIface);
00185       }
00186   }
00187 
00188   if (!kDebug_data->config && KGlobal::_instance )
00189   {
00190       kDebug_data->config = new KConfig("kdebugrc", false, false);
00191       kDebug_data->config->setGroup("0");
00192 
00193       //AB: this is necessary here, otherwise all output with area 0 won't be
00194       //prefixed with anything, unless something with area != 0 is called before
00195       if ( KGlobal::_instance )
00196         kDebug_data->aAreaName = KGlobal::instance()->instanceName();
00197   }
00198 
00199   if (kDebug_data->config && kDebug_data->oldarea != nArea) {
00200     kDebug_data->config->setGroup( QString::number(static_cast<int>(nArea)) );
00201     kDebug_data->oldarea = nArea;
00202     if ( nArea > 0 && KGlobal::_instance )
00203       kDebug_data->aAreaName = getDescrFromNum(nArea);
00204     if ((nArea == 0) || kDebug_data->aAreaName.isEmpty())
00205       if ( KGlobal::_instance )
00206         kDebug_data->aAreaName = KGlobal::instance()->instanceName();
00207   }
00208 
00209   int nPriority = 0;
00210   QString aCaption;
00211 
00212     /* Determine output */
00213 
00214   QString key;
00215   switch( nLevel )
00216   {
00217   case KDEBUG_INFO:
00218       key = "InfoOutput";
00219       aCaption = "Info";
00220       nPriority = LOG_INFO;
00221       break;
00222   case KDEBUG_WARN:
00223       key = "WarnOutput";
00224       aCaption = "Warning";
00225       nPriority = LOG_WARNING;
00226     break;
00227   case KDEBUG_FATAL:
00228       key = "FatalOutput";
00229       aCaption = "Fatal Error";
00230       nPriority = LOG_CRIT;
00231       break;
00232   case KDEBUG_ERROR:
00233   default:
00234       /* Programmer error, use "Error" as default */
00235       key = "ErrorOutput";
00236       aCaption = "Error";
00237       nPriority = LOG_ERR;
00238       break;
00239   }
00240 
00241   short nOutput = kDebug_data->config ? kDebug_data->config->readNumEntry(key, 4) : 4;
00242 
00243   // If the application doesn't have a QApplication object it can't use
00244   // a messagebox.
00245   if (!kapp && (nOutput == 1))
00246     nOutput = 2;
00247   else if ( nOutput == 4 && nLevel != KDEBUG_FATAL )
00248       return;
00249 
00250   const int BUFSIZE = 4096;
00251   char buf[BUFSIZE];
00252   int nSize;
00253   if ( !kDebug_data->aAreaName.isEmpty() ) {
00254       strlcpy( buf, kDebug_data->aAreaName.data(), BUFSIZE );
00255       strlcat( buf, ": ", BUFSIZE );
00256       strlcat( buf, data, BUFSIZE );
00257       nSize = strlen( buf );
00258   }
00259   else
00260       nSize = strlcpy( buf, data, BUFSIZE );
00261 
00262 
00263   // Output
00264   switch( nOutput )
00265   {
00266   case 0: // File
00267   {
00268       const char* aKey;
00269       switch( nLevel )
00270       {
00271       case KDEBUG_INFO:
00272           aKey = "InfoFilename";
00273           break;
00274       case KDEBUG_WARN:
00275           aKey = "WarnFilename";
00276           break;
00277       case KDEBUG_FATAL:
00278           aKey = "FatalFilename";
00279           break;
00280       case KDEBUG_ERROR:
00281       default:
00282           aKey = "ErrorFilename";
00283           break;
00284       }
00285       QFile aOutputFile( kDebug_data->config->readPathEntry(aKey, "kdebug.dbg") );
00286       aOutputFile.open( IO_WriteOnly | IO_Append | IO_Raw );
00287       if ( ( nSize == -1 ) || ( nSize >= BUFSIZE ) )
00288           aOutputFile.writeBlock( buf, BUFSIZE-1 );
00289       else
00290           aOutputFile.writeBlock( buf, nSize );
00291       aOutputFile.close();
00292       break;
00293   }
00294   case 1: // Message Box
00295   {
00296       // Since we are in kdecore here, we cannot use KMsgBox and use
00297       // QMessageBox instead
00298       if ( !kDebug_data->aAreaName.isEmpty() )
00299           aCaption += QString("(%1)").arg( kDebug_data->aAreaName );
00300       QMessageBox::warning( 0L, aCaption, data, i18n("&OK") );
00301       break;
00302   }
00303   case 2: // Shell
00304   {
00305       write( 2, buf, nSize ); //fputs( buf, stderr );
00306       break;
00307   }
00308   case 3: // syslog
00309   {
00310       syslog( nPriority, "%s", buf);
00311       break;
00312   }
00313   }
00314 
00315   // check if we should abort
00316   if( ( nLevel == KDEBUG_FATAL )
00317       && ( !kDebug_data->config || kDebug_data->config->readNumEntry( "AbortFatal", 1 ) ) )
00318         abort();
00319 }
00320 
00321 kdbgstream &perror( kdbgstream &s) { return s << QString::fromLocal8Bit(strerror(errno)); }
00322 kdbgstream kdDebug(int area) { return kdbgstream(area, KDEBUG_INFO); }
00323 kdbgstream kdDebug(bool cond, int area) { if (cond) return kdbgstream(area, KDEBUG_INFO); else return kdbgstream(0, 0, false); }
00324 
00325 kdbgstream kdError(int area) { return kdbgstream("ERROR: ", area, KDEBUG_ERROR); }
00326 kdbgstream kdError(bool cond, int area) { if (cond) return kdbgstream("ERROR: ", area, KDEBUG_ERROR); else return kdbgstream(0,0,false); }
00327 kdbgstream kdWarning(int area) { return kdbgstream("WARNING: ", area, KDEBUG_WARN); }
00328 kdbgstream kdWarning(bool cond, int area) { if (cond) return kdbgstream("WARNING: ", area, KDEBUG_WARN); else return kdbgstream(0,0,false); }
00329 kdbgstream kdFatal(int area) { return kdbgstream("FATAL: ", area, KDEBUG_FATAL); }
00330 kdbgstream kdFatal(bool cond, int area) { if (cond) return kdbgstream("FATAL: ", area, KDEBUG_FATAL); else return kdbgstream(0,0,false); }
00331 
00332 kdbgstream::kdbgstream(kdbgstream &str)
00333  : output(str.output), area(str.area), level(str.level), print(str.print) 
00334 { 
00335     str.output.truncate(0); 
00336 }
00337 
00338 void kdbgstream::flush() {
00339     if (output.isEmpty() || !print)
00340     return;
00341     kDebugBackend( level, area, output.local8Bit().data() );
00342     output = QString::null;
00343 }
00344 
00345 kdbgstream &kdbgstream::form(const char *format, ...)
00346 {
00347     char buf[4096];
00348     va_list arguments;
00349     va_start( arguments, format );
00350     vsnprintf( buf, sizeof(buf), format, arguments );
00351     va_end(arguments);
00352     *this << buf;
00353     return *this;
00354 }
00355 
00356 kdbgstream::~kdbgstream() {
00357     if (!output.isEmpty()) {
00358     fprintf(stderr, "ASSERT: debug output not ended with \\n\n");
00359         fprintf(stderr, "%s", kdBacktrace().latin1());
00360     *this << "\n";
00361     }
00362 }
00363 
00364 kdbgstream& kdbgstream::operator << (char ch)
00365 {
00366   if (!print) return *this;
00367   if (!isprint(ch))
00368     output += "\\x" + QString::number( static_cast<uint>( ch ), 16 ).rightJustify(2, '0');
00369   else {
00370     output += ch;
00371     if (ch == '\n') flush();
00372   }
00373   return *this;
00374 }
00375 
00376 kdbgstream& kdbgstream::operator << (QChar ch)
00377 {
00378   if (!print) return *this;
00379   if (!ch.isPrint())
00380     output += "\\x" + QString::number( ch.unicode(), 16 ).rightJustify(2, '0');
00381   else {
00382     output += ch;
00383     if (ch == '\n') flush();
00384   }
00385   return *this;
00386 }
00387 
00388 kdbgstream& kdbgstream::operator << (QWidget* widget)
00389 {
00390     return *this << const_cast< const QWidget* >( widget );
00391 }
00392 
00393 kdbgstream& kdbgstream::operator << (const QWidget* widget)
00394 {
00395   QString string, temp;
00396   // -----
00397   if(widget==0)
00398     {
00399       string=(QString)"[Null pointer]";
00400     } else {
00401       temp.setNum((ulong)widget, 16);
00402       string=(QString)"["+widget->className()+" pointer "
00403     + "(0x" + temp + ")";
00404       if(widget->name(0)==0)
00405     {
00406       string += " to unnamed widget, ";
00407     } else {
00408       string += (QString)" to widget " + widget->name() + ", ";
00409     }
00410       string += "geometry="
00411     + QString().setNum(widget->width())
00412     + "x"+QString().setNum(widget->height())
00413     + "+"+QString().setNum(widget->x())
00414     + "+"+QString().setNum(widget->y())
00415     + "]";
00416     }
00417   if (!print)
00418     {
00419       return *this;
00420     }
00421   output += string;
00422   if (output.at(output.length() -1 ) == '\n')
00423     {
00424       flush();
00425     }
00426   return *this;
00427 }
00428 /*
00429  * either use 'output' directly and do the flush if needed
00430  * or use the QString operator which calls the char* operator
00431  *
00432  */
00433 kdbgstream& kdbgstream::operator<<( const QDateTime& time) {
00434     *this << time.toString();
00435     return *this;
00436 }
00437 kdbgstream& kdbgstream::operator<<( const QDate& date) {
00438     *this << date.toString();
00439 
00440     return *this;
00441 }
00442 kdbgstream& kdbgstream::operator<<( const QTime& time ) {
00443     *this << time.toString();
00444     return *this;
00445 }
00446 kdbgstream& kdbgstream::operator<<( const QPoint& p ) {
00447     *this << "(" << p.x() << ", " << p.y() << ")";
00448     return *this;
00449 }
00450 kdbgstream& kdbgstream::operator<<( const QSize& s ) {
00451     *this << "[" << s.width() << "x" << s.height() << "]";
00452     return *this;
00453 }
00454 kdbgstream& kdbgstream::operator<<( const QRect& r ) {
00455     *this << "[" << r.x() << "," << r.y() << " - " << r.width() << "x" << r.height() << "]";
00456     return *this;
00457 }
00458 kdbgstream& kdbgstream::operator<<( const QRegion& reg ) {
00459     *this<< "[ ";
00460 
00461     QMemArray<QRect>rs=reg.rects();
00462     for (uint i=0;i<rs.size();++i)
00463         *this << QString("[%1,%2 - %3x%4] ").arg(rs[i].x()).arg(rs[i].y()).arg(rs[i].width()).arg(rs[i].height() ) ;
00464 
00465     *this <<"]";
00466     return *this;
00467 }
00468 kdbgstream& kdbgstream::operator<<( const KURL& u ) {
00469     *this << u.prettyURL();
00470     return *this;
00471 }
00472 kdbgstream& kdbgstream::operator<<( const QStringList& l ) {
00473     *this << "(";
00474     *this << l.join(",");
00475     *this << ")";
00476 
00477     return *this;
00478 }
00479 kdbgstream& kdbgstream::operator<<( const QColor& c ) {
00480     if ( c.isValid() )
00481         *this <<c.name();
00482     else
00483         *this << "(invalid/default)";
00484     return *this;
00485 }
00486 kdbgstream& kdbgstream::operator<<( const QPen& p ) {
00487     static const char* const s_penStyles[] = {
00488         "NoPen", "SolidLine", "DashLine", "DotLine", "DashDotLine",
00489         "DashDotDotLine" };
00490     static const char* const s_capStyles[] = {
00491         "FlatCap", "SquareCap", "RoundCap" };
00492     *this << "[ style:";
00493     *this << s_penStyles[ p.style() ];
00494     *this << " width:";
00495     *this << p.width();
00496     *this << " color:";
00497     if ( p.color().isValid() )
00498         *this << p.color().name();
00499     else
00500         *this <<"(invalid/default)";
00501     if ( p.width() > 0 ) // cap style doesn't matter, otherwise
00502     {
00503         *this << " capstyle:";
00504         *this << s_capStyles[ p.capStyle() >> 4 ];
00505         // join style omitted
00506     }
00507     *this <<" ]";
00508     return *this;
00509 }
00510 kdbgstream& kdbgstream::operator<<( const QBrush& b) {
00511     static const char* const s_brushStyles[] = {
00512         "NoBrush", "SolidPattern", "Dense1Pattern", "Dense2Pattern", "Dense3Pattern",
00513         "Dense4Pattern", "Dense5Pattern", "Dense6Pattern", "Dense7Pattern",
00514         "HorPattern", "VerPattern", "CrossPattern", "BDiagPattern", "FDiagPattern",
00515         "DiagCrossPattern" };
00516 
00517     *this <<"[ style: ";
00518     *this <<s_brushStyles[ b.style() ];
00519     *this <<" color: ";
00520     // can't use operator<<(str, b.color()) because that terminates a kdbgstream (flushes)
00521     if ( b.color().isValid() )
00522         *this <<b.color().name() ;
00523     else
00524         *this <<"(invalid/default)";
00525     if ( b.pixmap() )
00526         *this <<" has a pixmap";
00527     *this <<" ]";
00528     return *this;
00529 }
00530 
00531 kdbgstream& kdbgstream::operator<<( const QVariant& v) {
00532     *this << "[variant: ";
00533     *this << v.typeName();
00534     // For now we just attempt a conversion to string.
00535     // Feel free to switch(v.type()) and improve the output.
00536     *this << " toString=";
00537     *this << v.toString();
00538     *this << "]";
00539     return *this;
00540 }
00541 
00542 kdbgstream& kdbgstream::operator<<( const QByteArray& data) {
00543     if (!print) return *this;
00544     output += '[';
00545     unsigned int i = 0;
00546     unsigned int sz = QMIN( data.size(), 64 );
00547     for ( ; i < sz ; ++i ) {
00548         output += QString::number( data[i], 16 ).rightJustify(2, '0');
00549         if ( i < sz )
00550             output += ' ';
00551     }
00552     if ( sz < data.size() )
00553         output += "...";
00554     output += ']';
00555     return *this;
00556 }
00557 
00558 QString kdBacktrace(int levels)
00559 {
00560     QString s;
00561 #ifdef HAVE_BACKTRACE
00562     void* trace[256];
00563     int n = backtrace(trace, 256);
00564     if (!n)
00565     return s;
00566     char** strings = backtrace_symbols (trace, n);
00567 
00568     if ( levels != -1 )
00569         n = QMIN( n, levels );
00570     s = "[\n";
00571 
00572     for (int i = 0; i < n; ++i)
00573         s += QString::number(i) +
00574              QString::fromLatin1(": ") +
00575              QString::fromLatin1(strings[i]) + QString::fromLatin1("\n");
00576     s += "]\n";
00577     if (strings)
00578         free (strings);
00579 #endif
00580     return s;
00581 }
00582 
00583 QString kdBacktrace()
00584 {
00585     return kdBacktrace(-1 /*all*/);
00586 }
00587 
00588 void kdClearDebugConfig()
00589 {
00590     delete kDebug_data->config;
00591     kDebug_data->config = 0;
00592 }
00593 
00594 
00595 // Needed for --enable-final
00596 #ifdef NDEBUG
00597 #define kdDebug kndDebug
00598 #endif
KDE Logo
This file is part of the documentation for kdecore Library Version 3.3.0.
Documentation copyright © 1996-2004 the KDE developers.
Generated on Sat Nov 27 13:41:12 2004 by doxygen 1.3.9.1 written by Dimitri van Heesch, © 1997-2003