summaryrefslogtreecommitdiffabout
authorzautrix <zautrix>2005-03-30 11:55:53 (UTC)
committer zautrix <zautrix>2005-03-30 11:55:53 (UTC)
commitb5222dd7a607f78235b1ea39fea0f95a9c08ccd3 (patch) (side-by-side diff)
tree4e4d334ae9d8805b7718c1610bd84af128fd8151
parent597cad3a63e6c22855704bf8435db70e3c2b184f (diff)
downloadkdepimpi-b5222dd7a607f78235b1ea39fea0f95a9c08ccd3.zip
kdepimpi-b5222dd7a607f78235b1ea39fea0f95a9c08ccd3.tar.gz
kdepimpi-b5222dd7a607f78235b1ea39fea0f95a9c08ccd3.tar.bz2
fixes
Diffstat (more/less context) (ignore whitespace changes)
-rw-r--r--kabc/addresseeview.cpp2
-rw-r--r--kabc/plugins/file/resourcefile.cpp41
-rw-r--r--kabc/plugins/file/resourcefile.h2
-rw-r--r--microkde/kdatetbl.cpp2
-rw-r--r--microkde/kdecore/kstandarddirs.cpp4
-rw-r--r--microkde/kdecore/kstandarddirs.h4
6 files changed, 39 insertions, 16 deletions
diff --git a/kabc/addresseeview.cpp b/kabc/addresseeview.cpp
index aa96210..9118c3d 100644
--- a/kabc/addresseeview.cpp
+++ b/kabc/addresseeview.cpp
@@ -1,539 +1,539 @@
/*
This file is part of libkdepim.
Copyright (c) 2003 Tobias Koenig <tokoe@kde.org>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA.
*/
#include <kabc/address.h>
#include <kabc/addressee.h>
#include <kabc/phonenumber.h>
#include <kglobal.h>
//US#include <kglobalsettings.h>
#include <kiconloader.h>
#include <klocale.h>
//US #include <kstringhandler.h>
#include <qscrollview.h>
#include <qregexp.h>
#include <qfile.h>
#include <qvbox.h>
#include <qlabel.h>
#include <qwidget.h>
#include <qlayout.h>
#include <qapplication.h>
#include <qpushbutton.h>
#ifdef DESKTOP_VERSION
#include <qpaintdevicemetrics.h>
#include <qprinter.h>
#include <qpainter.h>
#endif
#include "externalapphandler.h"
#include <kabc/addresseeview.h>
//US #ifndef DESKTOP_VERSION
//US #include <qtopia/qcopenvelope_qws.h>
//US #include <qpe/qpeapplication.h>
//US #endif
//US static int kphoneInstalled = 0;
using namespace KABC;
AddresseeView::AddresseeView( QWidget *parent, const char *name )
: QTextBrowser( parent, name )
{
//US setWrapPolicy( QTextEdit::AtWordBoundary );
setLinkUnderline( false );
// setVScrollBarMode( QScrollView::AlwaysOff );
//setHScrollBarMode( QScrollView::AlwaysOff );
//US QStyleSheet *sheet = styleSheet();
//US QStyleSheetItem *link = sheet->item( "a" );
//US link->setColor( KGlobalSettings::linkColor() );
}
void AddresseeView::printMe()
{
#ifdef DESKTOP_VERSION
QPrinter printer;
if (!printer.setup() )
return;
QPainter p;
p.begin ( &printer );
QPaintDeviceMetrics m = QPaintDeviceMetrics ( &printer );
float dx, dy;
int wid = (m.width() * 9)/10;
dx = (float) wid/(float)contentsWidth ();
dy = (float)(m.height()) / (float)contentsHeight ();
float scale;
// scale to fit the width or height of the paper
if ( dx < dy )
scale = dx;
else
scale = dy;
p.translate( m.width()/10,0 );
p.scale( scale, scale );
drawContents ( &p, 0,0, contentsWidth (), contentsHeight () );
p.end();
#endif
}
void AddresseeView::setSource(const QString& n)
{
//qDebug("********AddresseeView::setSource %s", n.latin1());
if ( n.left( 6 ) == "mailto" )
ExternalAppHandler::instance()->mailToOneContact( n.mid(7) );
else if ( n.left( 7 ) == "phoneto" )
ExternalAppHandler::instance()->callByPhone( n.mid(8) );
else if ( n.left( 5 ) == "faxto" )
ExternalAppHandler::instance()->callByFax( n.mid(6) );
else if ( n.left( 5 ) == "smsto" )
ExternalAppHandler::instance()->callBySMS( n.mid(6) );
else if ( n.left( 7 ) == "pagerto" )
ExternalAppHandler::instance()->callByPager( n.mid(8) );
else if ( n.left( 5 ) == "sipto" )
ExternalAppHandler::instance()->callBySIP( n.mid(6) );
}
void AddresseeView::setAddressee( const KABC::Addressee& mAddressee )
{
bool kemailAvail = ExternalAppHandler::instance()->isEmailAppAvailable();
// mAddressee = addr;
// clear view
//setText( QString::null );
if ( mAddressee.isEmpty() ) {
setText( QString::null);
return;
}
QString name = ( mAddressee.assembledName().isEmpty() ?
mAddressee.formattedName() : mAddressee.assembledName() );
QString dynamicPart;
dynamicPart += getPhoneNumbers( mAddressee.phoneNumbers(),true );
QStringList emails = mAddressee.emails();
QStringList::ConstIterator emailIt;
QString type = i18n( "Email" );
emailIt = emails.begin();
if ( emailIt != emails.end() ) {
if ( kemailAvail ) {
dynamicPart += QString(
"<tr><td align=\"right\"><b>%1</b></td>"
"<td align=\"left\"><a href=\"mailto:%2 <%3> \">%4</a></td></tr>" )
.arg( type )
.arg( name )
.arg( *emailIt )
.arg( *emailIt );
++emailIt;
} else {
dynamicPart += QString(
"<tr><td align=\"right\"><b>%1</b></td>"
"<td align=\"left\">%2</td></tr>" )
.arg( type )
.arg( *emailIt );
++emailIt;
}
}
if ( mAddressee.birthday().date().isValid() ) {
dynamicPart += QString(
"<tr><td align=\"right\"><b>%1</b></td>"
"<td align=\"left\">%2</td></tr>" )
.arg( i18n ("Birthday") )
.arg( KGlobal::locale()->formatDate( mAddressee.birthday().date() ,true) );
}
dynamicPart += getPhoneNumbers( mAddressee.phoneNumbers(), false );
for ( ; emailIt != emails.end(); ++emailIt ) {
if ( kemailAvail ) {
dynamicPart += QString(
"<tr><td align=\"right\"><b>%1</b></td>"
"<td align=\"left\"><a href=\"mailto:%2 <%3> \">%4</a></td></tr>" )
.arg( type )
.arg( name )
.arg( *emailIt )
.arg( *emailIt );
} else {
dynamicPart += QString(
"<tr><td align=\"right\"><b>%1</b></td>"
"<td align=\"left\">%2</td></tr>" )
.arg( type )
.arg( *emailIt );
}
}
if ( !mAddressee.url().url().isEmpty() ) {
dynamicPart += QString(
"<tr><td align=\"right\"><b>%1</b></td>"
"<td align=\"left\">%2</td></tr>" )
.arg( i18n( "Homepage" ) )
//US .arg( KStringHandler::tagURLs( mAddressee.url().url() ) );
.arg( mAddressee.url().url() );
//qDebug("AddresseeView::setAddressee has to be verified.");
}
KABC::Address::List addresses = mAddressee.addresses();
KABC::Address::List::ConstIterator addrIt;
for ( addrIt = addresses.begin(); addrIt != addresses.end(); ++addrIt ) {
if ( true /*(*addrIt).label().isEmpty()*/ ) {
QString formattedAddress = (*addrIt).formattedAddress().stripWhiteSpace();
//US formattedAddress = formattedAddress.replace( '\n', "<br>" );
//qDebug("adresss %s ",formattedAddress.latin1() );
formattedAddress = formattedAddress.replace( QRegExp("\n"), "<br>" );
//qDebug("AddresseeView::setAddressee has to be verified.");
dynamicPart += QString(
"<tr><td align=\"right\"><b>%1</b></td>"
"<td align=\"left\">%2</td></tr>" )
.arg( KABC::Address::typeLabel( (*addrIt).type() ) )
.arg( formattedAddress );
} else {
dynamicPart += QString(
"<tr><td align=\"right\"><b>%1</b></td>"
"<td align=\"left\">%2</td></tr>" )
.arg( KABC::Address::typeLabel( (*addrIt).type() ) )
//US .arg( (*addrIt).label().replace( '\n', "<br>" ) );
.arg( (*addrIt).label() /*replace( QRegExp("\n"), "<br>" )*/ );
}
}
QString notes;
if ( !mAddressee.note().isEmpty() ) {
notes = QString(
"<tr>"
"<td align=\"right\" valign=\"top\"><b>%1</b></td>" // note label
"<td align=\"left\">%2</td>" // note
"</tr>" ).arg( i18n( "Notes" ) )
//US .arg( mAddressee.note().replace( '\n', "<br>" ) );
.arg( mAddressee.note().replace( QRegExp("\n"), "<br>" ) );
//qDebug("AddresseeView::setAddressee has to be verified.");
}
QString aRole = "";
QString aOrga = "";
if ( true /*!mAddressee.role().isEmpty()*/ ) {
aRole = "<tr>"
"<td align=\"left\">" + mAddressee.role() + "</td>"
"</tr>";
}
if ( true /*!mAddressee.organization().isEmpty()*/ ) {
aOrga = "<tr>"
"<td align=\"left\">" + mAddressee.organization() + "</td>"
"</tr>";
}
mText = "";
QString picString = "";
KABC::Picture picture = mAddressee.photo();
bool picAvailintern = false;
bool picAvailUrl = false;
if (! picture.undefined() ) {
picAvailintern = (picture.isIntern() && !picture.data().isNull());
picAvailUrl = !picture.isIntern() && QFile::exists(picture.url() );
}
if ( picAvailUrl || picAvailintern || QApplication::desktop()->width() > 320 ) {
picString = "<img src=\"myimage\" width=\"50\" height=\"70\">";
if ( picAvailintern ) {
QMimeSourceFactory::defaultFactory()->setImage( "myimage", picture.data() );
} else {
if ( picAvailUrl ) {
QMimeSourceFactory::defaultFactory()->setPixmap( "myimage", QPixmap( picture.url() ));
} else {
if ( !mAddressee.custom( "KADDRESSBOOK", "X-Children" ).isEmpty() ) {
static bool setDefaultImageChildren = false;
if ( !setDefaultImageChildren ) {
QMimeSourceFactory::defaultFactory()->setPixmap( "familyIcon", KGlobal::iconLoader()->loadIcon( "ic_kids", KIcon::Desktop, 128 ) );
setDefaultImageChildren = true;
}
picString = "<img src=\"familyIcon\" width=\"64\" height=\"64\">";
} else if ( !mAddressee.custom( "KADDRESSBOOK", "X-SpousesName" ).isEmpty() ) {
static bool setDefaultImagepouses = false;
if ( !setDefaultImagepouses ) {
QMimeSourceFactory::defaultFactory()->setPixmap( "SpousesIcon", KGlobal::iconLoader()->loadIcon( "ic_family", KIcon::Desktop, 128 ) );
setDefaultImagepouses = true;
}
picString = "<img src=\"SpousesIcon\" width=\"64\" height=\"64\">";
} else {
QString gen = mAddressee.custom( "KADDRESSBOOK", "X-Gender" );
if ( gen == "male" ) {
static bool setDefaultImageMale = false;
if ( !setDefaultImageMale ) {
QMimeSourceFactory::defaultFactory()->setPixmap( "MaleIcon", KGlobal::iconLoader()->loadIcon( "ic_male", KIcon::Desktop, 128 ) );
setDefaultImageMale = true;
}
picString = "<img src=\"MaleIcon\" width=\"64\" height=\"64\">";
} else if ( gen == "female" ) {
static bool setDefaultImageFemale = false;
if ( !setDefaultImageFemale ) {
QMimeSourceFactory::defaultFactory()->setPixmap( "FemaleIcon", KGlobal::iconLoader()->loadIcon( "ic_female", KIcon::Desktop, 128 ) );
setDefaultImageFemale = true;
}
picString = "<img src=\"FemaleIcon\" width=\"64\" height=\"64\">";
} else {
static bool setDefaultImage = false;
if ( !setDefaultImage ) {
- qDebug("Setting default pixmap ");
+ //qDebug("Setting default pixmap ");
QMimeSourceFactory::defaultFactory()->setPixmap( "defaultIcon", KGlobal::iconLoader()->loadIcon( "ic_penguin", KIcon::Desktop, 128 ) );
setDefaultImage = true;
}
picString = "<img src=\"defaultIcon\" width=\"64\" height=\"64\">";
}
}
}
}
mText = QString::fromLatin1(
"<html>"
"<body text=\"%1\" bgcolor=\"%2\">" // text and background color
"<table>"
"<tr>"
"<td rowspan=\"3\" align=\"right\" valign=\"top\">"
"%3"
"</td>"
"<td align=\"left\"><font size=\"+2\"><b>%4</b></font></td>" // name
"</tr>"
"%5" // role
"%6" // organization
"<td colspan=\"2\">&nbsp;</td>"
"%7" // dynamic part
"%8" // notes
"</table>"
"</body>"
"</html>")
//US
.arg( /*KGlobalSettings::textColor().name()*/ "black" )
//US
.arg( /*KGlobalSettings::baseColor().name()*/ "white" )
.arg( picString )
.arg( name )
.arg( aRole )
.arg( aOrga )
.arg( dynamicPart )
.arg( notes );
} else { // no picture!
mText = "<table width=\"100%\">\n";
//mText += "<tr bgcolor=\"#3679AD\"><td><h2>";
#ifdef DESKTOP_VERSION
mText += "<tr bgcolor=\"#5699CD\"><td align=\"left\"><h1>";
mText += "<font color=\"#FFFFFF\">" + name +"</font></h1>";
#else
mText += "<tr bgcolor=\"#5699CD\"><td align=\"left\"><h3>";
mText += "<font color=\"#FFFFFF\"> " + name +"</font></h3>";
#endif
mText += "</td></tr>\n<tr bgcolor=\"#EAF8FA\"><td>";
mText += "<table><td colspan=\"2\">&nbsp;</td>";
/*
mText += QString("<tr><td align=\"right\"><b2>%1</b2></td>"
"<td align=\"left\"><b>%2</b></td></tr>" )
.arg( i18n(" ") )
.arg( name );
*/
if ( ! mAddressee.role().isEmpty() )
mText += QString("<tr><td align=\"right\"><b>%1</b></td>"
"<td align=\"left\">%2</td></tr>" )
.arg( i18n(" ") )
.arg( mAddressee.role());
if ( ! mAddressee.organization().isEmpty() )
mText += QString("<tr><td align=\"right\"><b>%1</b></td>"
"<td align=\"left\">%2</td></tr>" )
.arg( i18n(" ") )
.arg( mAddressee.organization());
mText += dynamicPart;
mText += notes;
mText += "</table>";
}
// at last display it...
setText( mText );
}
QString AddresseeView::getPhoneNumbers( KABC::PhoneNumber::List phones ,bool preferred )
{
ExternalAppHandler* eah = ExternalAppHandler::instance();
bool kphoneAvail = eah->isPhoneAppAvailable();
bool kfaxAvail = eah->isFaxAppAvailable();
bool ksmsAvail = eah->isSMSAppAvailable();
bool kpagerAvail = eah->isPagerAppAvailable();
bool ksipAvail = eah->isSIPAppAvailable();
QString dynamicPart;
KABC::PhoneNumber::List::ConstIterator phoneIt;
QString extension;
int phonetype;
QString sms;
for ( phoneIt = phones.begin(); phoneIt != phones.end(); ++phoneIt ) {
phonetype = (*phoneIt).type();
if ( ((phonetype & KABC::PhoneNumber::Pref) == 0 ) == preferred )
continue;
if (ksmsAvail &&
(
((phonetype & KABC::PhoneNumber::Car) == KABC::PhoneNumber::Car) ||
((phonetype & KABC::PhoneNumber::Cell) == KABC::PhoneNumber::Cell)
)
)
{
sms = QString("<a href=\"smsto:%1 \">(sms)</a>" )
.arg( (*phoneIt).number() );
}
else
sms = "";
extension = QString::null;
if ((phonetype & KABC::PhoneNumber::Fax) == KABC::PhoneNumber::Fax) {
if (kfaxAvail) extension = "faxto:";
}
else if ((phonetype & KABC::PhoneNumber::Pager) == KABC::PhoneNumber::Pager) {
if (kpagerAvail) extension = "pagerto:";
}
else if ((phonetype & KABC::PhoneNumber::Sip) == KABC::PhoneNumber::Sip) {
if (ksipAvail) extension = "sipto:";
}
else if (kphoneAvail) {
extension = "phoneto:";
}
else
extension = QString::null;
if ( !extension.isEmpty() ) {
dynamicPart += QString(
"<tr><td align=\"right\"><b>%1</b></td>"
"<td align=\"left\"><a href=\"%2%3 \">%4</a> %5</td></tr>" )
.arg( KABC::PhoneNumber::typeLabel( phonetype ) )
.arg( extension )
.arg( (*phoneIt).number() )
.arg( (*phoneIt).number() )
.arg( sms );
} else {
dynamicPart += QString(
"<tr><td align=\"right\"><b>%1</b></td>"
"<td align=\"left\">%2 %3</td></tr>" )
.arg( KABC::PhoneNumber::typeLabel( phonetype ) )
.arg( (*phoneIt).number() )
.arg( sms );
}
}
return dynamicPart;
}
/*
KABC::Addressee AddresseeView::addressee() const
{
return mAddressee;
}
*/
void AddresseeView::addTag(const QString & tag,const QString & text)
{
if ( text.isEmpty() )
return;
int number=text.contains("\n");
QString str = "<" + tag + ">";
QString tmpText=text;
QString tmpStr=str;
if(number !=-1)
{
if (number > 0) {
int pos=0;
QString tmp;
for(int i=0;i<=number;i++) {
pos=tmpText.find("\n");
tmp=tmpText.left(pos);
tmpText=tmpText.right(tmpText.length()-pos-1);
tmpStr+=tmp+"<br>";
}
}
else tmpStr += tmpText;
tmpStr+="</" + tag + ">";
mText.append(tmpStr);
}
else
{
str += text + "</" + tag + ">";
mText.append(str);
}
}
AddresseeChooser::AddresseeChooser( KABC::Addressee loc, KABC::Addressee rem, bool takeloc, QWidget *parent, const char *name ) : KDialogBase(parent,name,
true ,i18n("Conflict! Please choose Adressee!"),Ok|User1|Close,Close, false)
{
findButton( Close )->setText( i18n("Cancel Sync"));
findButton( Ok )->setText( i18n("Remote"));
findButton( User1 )->setText( i18n("Local"));
QWidget* topframe = new QWidget( this );
setMainWidget( topframe );
QBoxLayout* bl;
if ( QApplication::desktop()->width() < 640 ) {
bl = new QVBoxLayout( topframe );
} else {
bl = new QHBoxLayout( topframe );
}
QVBox* subframe = new QVBox( topframe );
bl->addWidget(subframe );
QLabel* lab = new QLabel( i18n("Local Addressee"), subframe );
if ( takeloc )
lab->setBackgroundColor(Qt::green.light() );
AddresseeView * av = new AddresseeView( subframe );
av->setAddressee( loc );
subframe = new QVBox( topframe );
bl->addWidget(subframe );
lab = new QLabel( i18n("Remote Addressee"), subframe );
if ( !takeloc )
lab->setBackgroundColor(Qt::green.light() );
av = new AddresseeView( subframe );
av->setAddressee( rem );
QObject::connect(findButton( Ok ),SIGNAL(clicked()),this, SLOT(slot_remote()));
QObject::connect(this,SIGNAL(user1Clicked()),this, SLOT(slot_local()));
#ifndef DESKTOP_VERSION
showMaximized();
#else
resize ( 640, 400 );
#endif
}
int AddresseeChooser::executeD( bool local )
{
mSyncResult = 3;
if ( local )
findButton( User1 )->setFocus();
else
findButton( Ok )->setFocus();
exec();
return mSyncResult;
}
void AddresseeChooser::slot_remote()
{
mSyncResult = 2;
accept();
}
void AddresseeChooser::slot_local()
{
mSyncResult = 1;
accept();
}
diff --git a/kabc/plugins/file/resourcefile.cpp b/kabc/plugins/file/resourcefile.cpp
index dc5932f..4ab7f02 100644
--- a/kabc/plugins/file/resourcefile.cpp
+++ b/kabc/plugins/file/resourcefile.cpp
@@ -1,404 +1,421 @@
/*
This file is part of libkabc.
Copyright (c) 2001 Cornelius Schumacher <schumacher@kde.org>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA.
*/
/*
Enhanced Version of the file for platform independent KDE tools.
Copyright (c) 2004 Ulf Schenk
$Id$
*/
#include <sys/types.h>
#include <sys/stat.h>
#ifndef _WIN32_
#include <unistd.h>
#endif
#include <qfile.h>
#include <qfileinfo.h>
#include <qregexp.h>
#include <qtimer.h>
#include <kapplication.h>
#include <kconfig.h>
#include <kdebug.h>
#include <klocale.h>
//US #include <ksavefile.h>
#include <kstandarddirs.h>
#include <kmessagebox.h>
#include "formatfactory.h"
#include "resource.h"
#include "resourcefileconfig.h"
#include "stdaddressbook.h"
#define NO_DIRWATCH
#include "resourcefile.h"
//#define ALLOW_LOCKING
-
using namespace KABC;
extern "C"
#ifdef _WIN32_
__declspec(dllexport)
#else
{
#endif
//US void *init_kabc_file()
void *init_microkabc_file()
{
return new KRES::PluginFactory<ResourceFile,ResourceFileConfig>();
}
#ifndef _WIN32_
}
#endif
ResourceFile::ResourceFile( const KConfig *config )
: Resource( config ) , mFormat( 0 )
{
QString fileName, formatName, default_fileName;
default_fileName = StdAddressBook::fileName();
KConfig *cfg = (KConfig *)config;
if ( cfg ) {
fileName = cfg->readEntry( "FileName", default_fileName );
formatName = cfg->readEntry( "FileFormat", "vcard" );
} else {
fileName = default_fileName;
formatName = "vcard";
}
init( fileName, formatName );
}
ResourceFile::ResourceFile( const QString &fileName ,
const QString &formatName )
: Resource( 0 )
{
// qDebug("ResourceFile::ResourceFile : 3 %s, %s", fileName.latin1(), formatName.latin1());
+
+
+
init( fileName, formatName );
}
void ResourceFile::init( const QString &fileName, const QString &formatName )
{
mFormatName = formatName;
FormatFactory *factory = FormatFactory::self();
mFormat = factory->format( mFormatName );
if ( !mFormat ) {
mFormatName = "vcard";
mFormat = factory->format( mFormatName );
}
#ifndef NO_DIRWATCH
connect( &mDirWatch, SIGNAL( dirty(const QString&) ), SLOT( fileChanged() ) );
connect( &mDirWatch, SIGNAL( created(const QString&) ), SLOT( fileChanged() ) );
connect( &mDirWatch, SIGNAL( deleted(const QString&) ), SLOT( fileChanged() ) );
#endif
+
+
+ QString localKdeDir;
+ localKdeDir = readEnvPath("LOCALMICROKDEHOME");
+ if ( ! localKdeDir.isEmpty() ) {
+ qDebug("LOCALMICROKDEHOME is set to: %s",localKdeDir.latin1() );
+
+
+
+
+ }
+ qDebug("RESOURCE: %s ", fileName.latin1());
+
+
+
setFileName( fileName );
}
ResourceFile::~ResourceFile()
{
delete mFormat;
mFormat = 0;
}
void ResourceFile::writeConfig( KConfig *config )
{
config->setGroup( "Resource_" + identifier() );
Resource::writeConfig( config );
- config->writeEntry( "FileName", mFileName );
+ config->writeEntry( "FileName", fileName() );
config->writeEntry( "FileFormat", mFormatName );
// qDebug("ResourceFile::writeConfig format %s, %s", mFileName.latin1(), mFormatName.latin1());
}
Ticket *ResourceFile::requestSaveTicket()
{
kdDebug(5700) << "ResourceFile::requestSaveTicket()" << endl;
if ( !addressBook() ) return 0;
#ifdef ALLOW_LOCKING
if ( !lock( mFileName ) ) {
qDebug("unablt to lock file ");
return 0;
}
#endif
return createTicket( this );
}
bool ResourceFile::doOpen()
{
- QFile file( mFileName );
- qDebug("ResourceFile::openfile %s ", mFileName.latin1());
+ QFile file( fileName() );
+ qDebug("ResourceFile::openfile %s ", fileName().latin1());
if ( !file.exists() ) {
// try to create the file
bool ok = file.open( IO_WriteOnly );
if ( ok )
file.close();
return ok;
} else {
if ( !file.open( IO_ReadWrite ) )
return false;
if ( file.size() == 0 ) {
file.close();
return true;
}
bool ok = mFormat->checkFormat( &file );
file.close();
return ok;
}
}
void ResourceFile::doClose()
{
}
bool ResourceFile::load()
{
- QFile file( mFileName );
+ QFile file( fileName() );
if ( !file.open( IO_ReadOnly ) ) {
- addressBook()->error( i18n( "Unable to open file '%1'." ).arg( mFileName ) );
+ addressBook()->error( i18n( "Unable to open file '%1'." ).arg( fileName() ) );
return false;
}
// qDebug("ResourceFile::load format %s, %s", mFileName.latin1(), mFormatName.latin1());
return mFormat->loadAll( addressBook(), this, &file );
}
bool ResourceFile::save( Ticket *ticket )
{
// qDebug("ResourceFile::save format %s, %s", mFileName.latin1(), mFormatName.latin1());
// create backup file
QString extension = "_" + QString::number( QDate::currentDate().dayOfWeek() );
/*US we use a simpler method to create a backupfile
(void) KSaveFile::backupFile( mFileName, QString::null
,extension );
KSaveFile saveFile( mFileName );
bool ok = false;
if ( saveFile.status() == 0 && saveFile.file() )
{
mFormat->saveAll( addressBook(), this, saveFile.file() );
ok = saveFile.close();
}
*/
//US ToDo: write backupfile
#ifndef NO_DIRWATCH
mDirWatch.stopScan();
#endif
QFile info;
- info.setName( mFileName );
+ info.setName( fileName() );
bool ok = info.open( IO_WriteOnly );
if ( ok ) {
mFormat->saveAll( addressBook(), this, &info );
info.close();
ok = true;
}
else {
}
if ( !ok )
- addressBook()->error( i18n( "Unable to save file '%1'." ).arg( mFileName ) );
+ addressBook()->error( i18n( "Unable to save file '%1'." ).arg( fileName() ) );
#ifndef NO_DIRWATCH
mDirWatch.startScan();
#endif
delete ticket;
#ifdef ALLOW_LOCKING
unlock( mFileName );
#endif
return ok;
}
bool ResourceFile::lock( const QString &fileName )
{
#ifdef ALLOW_LOCKING
QString fn = fileName;
//US change the implementation how the lockfilename is getting created
//US fn.replace( QRegExp("/"), "_" );
//US QString lockName = locateLocal( "data", "kabc/lock/" + fn + ".lock" );
KURL url(fn);
QString lockName = locateLocal( "data", "kabc/lock/" + url.fileName() + ".lock" );
if (QFile::exists( lockName )) return false;
QString lockUniqueName;
lockUniqueName = fn + KApplication::randomString( 8 );
url = lockUniqueName;
//US mLockUniqueName = locateLocal( "data", "kabc/lock/" + lockUniqueName );
mLockUniqueName = locateLocal( "data", "kabc/lock/" + url.fileName() );
kdDebug(5700) << "-- lock unique name: " << mLockUniqueName << endl;
// Create unique file
QFile file( mLockUniqueName );
file.open( IO_WriteOnly );
file.close();
// Create lock file
int result = 0;
#ifndef _WIN32_
result = ::link( QFile::encodeName( mLockUniqueName ),
QFile::encodeName( lockName ) );
#endif
if ( result == 0 ) {
addressBook()->emitAddressBookLocked();
return true;
}
// TODO: check stat
return false;
#else
return true;
#endif
}
void ResourceFile::unlock( const QString &fileName )
{
#ifdef ALLOW_LOCKING
QString fn = fileName;
//US change the implementation how the lockfilename is getting created
//US fn.replace( QRegExp( "/" ), "_" );
//US QString lockName = locateLocal( "data", "kabc/lock/" + fn + ".lock" );
//US QString lockName = fn + ".lock";
KURL url(fn);
QString lockName = locateLocal( "data", "kabc/lock/" + url.fileName() + ".lock" );
QFile::remove( lockName );
QFile::remove( mLockUniqueName );
addressBook()->emitAddressBookUnlocked();
#else
return;
#endif
}
void ResourceFile::setFileName( const QString &fileName )
{
#ifndef NO_DIRWATCH
mDirWatch.stopScan();
mDirWatch.removeFile( mFileName );
mFileName = fileName;
mDirWatch.addFile( mFileName );
mDirWatch.startScan();
#else
- mFileName = fileName;
+ mFileName2 = fileName;
#endif
//US simulate KDirWatch event
//US fileChanged();
}
QString ResourceFile::fileName() const
{
- return mFileName;
+ return mFileName2;
}
void ResourceFile::setFormat( const QString &format )
{
mFormatName = format;
delete mFormat;
FormatFactory *factory = FormatFactory::self();
mFormat = factory->format( mFormatName );
/*US
//qDebug("ResourceFile::setFormat initialized with format %s ", format.latin1());
if (mFormatName == "vcard") {
mFormat = new VCardFormatPlugin2();
// qDebug("ResourceFile::setFormat format %s", mFormatName.latin1());
}
else if (mFormatName == "binary") {
mFormat = new BinaryFormat();
// qDebug("ResourceFile::setFormat format %s", mFormatName.latin1());
}
else
qDebug("ResourceFile::setFormat format unknown !!! %s ", format.latin1());
*/
}
QString ResourceFile::format() const
{
return mFormatName;
}
void ResourceFile::fileChanged()
{
// There is a small theoretical chance that KDirWatch calls us before
// we are fully constructed
if (!addressBook())
return;
- QString text( i18n( "File resource '%1'<br> has been changed by third party.<br>Do you want to reload?").arg( mFileName ) );
+ QString text( i18n( "File resource '%1'<br> has been changed by third party.<br>Do you want to reload?").arg( fileName() ) );
if ( readOnly() || KMessageBox::questionYesNo( 0, text ) == KMessageBox::Yes ) {
load();
addressBook()->emitAddressBookChanged();
}
}
void ResourceFile::removeAddressee( const Addressee &addr )
{
QFile::remove( QFile::encodeName( locateLocal( "data", "kabc/photos/" ) + addr.uid() ) );
QFile::remove( QFile::encodeName( locateLocal( "data", "kabc/logos/" ) + addr.uid() ) );
QFile::remove( QFile::encodeName( locateLocal( "data", "kabc/sounds/" ) + addr.uid() ) );
}
void ResourceFile::cleanUp()
{
- unlock( mFileName );
+ unlock( fileName() );
}
//US #include "resourcefile.moc"
diff --git a/kabc/plugins/file/resourcefile.h b/kabc/plugins/file/resourcefile.h
index b4421b2..dd38a9d 100644
--- a/kabc/plugins/file/resourcefile.h
+++ b/kabc/plugins/file/resourcefile.h
@@ -1,163 +1,163 @@
/*
This file is part of libkabc.
Copyright (c) 2001 Cornelius Schumacher <schumacher@kde.org>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA.
*/
/*
Enhanced Version of the file for platform independent KDE tools.
Copyright (c) 2004 Ulf Schenk
$Id$
*/
#ifndef KABC_RESOURCEFILE_H
#define KABC_RESOURCEFILE_H
#include <kconfig.h>
#include <kdirwatch.h>
#include <sys/types.h>
#include <resource.h>
class QTimer;
class FormatPlugin;
namespace KABC {
//US class FormatPlugin;
class ResourceConfigWidget;
/**
@internal
*/
class ResourceFile : public Resource
{
Q_OBJECT
public:
/**
Constructor.
@param cfg The config object where custom resource settings are stored.
*/
ResourceFile( const KConfig *cfg );
/**
Construct file resource on file @arg fileName using format @arg formatName.
*/
ResourceFile( const QString &fileName , const QString &formatName = "vcard" );
/**
* Destructor.
*/
~ResourceFile();
/**
Writes the config back.
*/
virtual void writeConfig( KConfig *cfg );
/**
* Tries to open the file and checks for the proper format.
* This method should be called before @ref load().
*/
virtual bool doOpen();
/**
* Closes the file again.
*/
virtual void doClose();
/**
* Requests a save ticket, that is used by @ref save()
*/
virtual Ticket *requestSaveTicket();
/**
* Loads all addressees from file to the address book.
* Returns true if all addressees could be loaded otherwise false.
*/
virtual bool load();
/**
* Saves all addresses from address book to file.
* Returns true if all addressees could be saved otherwise false.
*
* @param ticket The ticket returned by @ref requestSaveTicket()
*/
virtual bool save( Ticket *ticket );
/**
* Set name of file to be used for saving.
*/
void setFileName( const QString & );
/**
* Return name of file used for loading and saving the address book.
*/
QString fileName() const;
/**
Sets a new format by name.
*/
void setFormat( const QString &name );
/**
Returns the format name.
*/
QString format() const;
/**
* Remove a addressee from its source.
* This method is mainly called by KABC::AddressBook.
*/
virtual void removeAddressee( const Addressee& addr );
/**
* This method is called by an error handler if the application
* crashed
*/
virtual void cleanUp();
protected slots:
void fileChanged();
protected:
void init( const QString &fileName, const QString &format );
bool lock( const QString &fileName );
void unlock( const QString &fileName );
private:
- QString mFileName;
+ QString mFileName2;
QString mFormatName;
FormatPlugin *mFormat;
QString mLockUniqueName;
#ifndef NO_DIRWATCH
KDirWatch mDirWatch;
#endif
};
}
#endif
diff --git a/microkde/kdatetbl.cpp b/microkde/kdatetbl.cpp
index d182279..2d97c8c 100644
--- a/microkde/kdatetbl.cpp
+++ b/microkde/kdatetbl.cpp
@@ -1,839 +1,839 @@
/* -*- C++ -*-
This file is part of the KDE libraries
Copyright (C) 1997 Tim D. Gilman (tdgilman@best.org)
(C) 1998-2001 Mirko Boehm (mirko@kde.org)
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA.
*/
/////////////////// KDateTable widget class //////////////////////
//
// Copyright (C) 1997 Tim D. Gilman
// (C) 1998-2001 Mirko Boehm
// Written using Qt (http://www.troll.no) for the
// KDE project (http://www.kde.org)
//
// This is a support class for the KDatePicker class. It just
// draws the calender table without titles, but could theoretically
// be used as a standalone.
//
// When a date is selected by the user, it emits a signal:
// dateSelected(QDate)
#include <kglobal.h>
#include <kglobalsettings.h>
#include <kapplication.h>
#include <klocale.h>
#include <kdebug.h>
#include <knotifyclient.h>
#include "kdatetbl.h"
#include <qdatetime.h>
#include <qstring.h>
#include <qpen.h>
#include <qpainter.h>
#include <qdialog.h>
#include <assert.h>
#include <qapplication.h>
KDateValidator::KDateValidator(QWidget* parent, const char* name)
: QValidator(parent, name)
{
}
QValidator::State
KDateValidator::validate(QString& text, int&) const
{
QDate temp;
// ----- everything is tested in date():
return date(text, temp);
}
QValidator::State
KDateValidator::date(const QString& text, QDate& d) const
{
QDate tmp = KGlobal::locale()->readDate(text);
if (!tmp.isNull())
{
d = tmp;
return Acceptable;
} else
return Valid;
}
void
KDateValidator::fixup( QString& ) const
{
}
KDateTable::KDateTable(QWidget *parent, QDate date_, const char* name, WFlags f)
: QGridView(parent, name, f)
{
setFont( KGlobalSettings::generalFont() );
if(!date_.isValid())
{
date_=QDate::currentDate();
}
setFocusPolicy( QWidget::StrongFocus );
setNumRows(7); // 6 weeks max + headline
setNumCols(7); // 7 days a week
setHScrollBarMode(AlwaysOff);
setVScrollBarMode(AlwaysOff);
viewport()->setBackgroundColor(QColor(220,245,255));
#if 0
viewport()->setEraseColor(lightGray);
#endif
mMarkCurrent = false;
setDate(date_); // this initializes firstday, numdays, numDaysPrevMonth
}
void
KDateTable::paintCell(QPainter *painter, int row, int col)
{
QRect rect;
QString text;
QPen pen;
int w=cellWidth();
int h=cellHeight();
int pos;
QBrush brushBlue(blue);
QBrush brushLightblue(QColor(220,245,255));
QFont _font=font();
// -----
if(row==0)
{ // we are drawing the headline
_font.setBold(true);
painter->setFont(_font);
bool normalday = true;
QString daystr;
if (KGlobal::locale()->weekStartsMonday())
{
daystr = KGlobal::locale()->weekDayName(col+1, true);
if (col == 5 || col == 6)
normalday = false;
} else {
daystr = KGlobal::locale()->weekDayName(col==0? 7 : col, true);
if (col == 0 || col == 6)
normalday = false;
}
if (!normalday)
{
painter->setPen(QColor(220,245,255));
painter->setBrush(brushLightblue);
painter->drawRect(0, 0, w, h);
painter->setPen(blue);
} else {
painter->setPen(blue);
painter->setBrush(brushBlue);
painter->drawRect(0, 0, w, h);
painter->setPen(white);
}
painter->drawText(0, 0, w, h-1, AlignCenter,
daystr, -1, &rect);
painter->setPen(black);
painter->moveTo(0, h-1);
painter->lineTo(w-1, h-1);
// ----- draw the weekday:
} else {
painter->setFont(_font);
pos=7*(row-1)+col;
if (KGlobal::locale()->weekStartsMonday())
pos++;
if(pos<firstday || (firstday+numdays<=pos))
{ // we are either
// ° painting a day of the previous month or
// ° painting a day of the following month
if(pos<firstday)
{ // previous month
text.setNum(numDaysPrevMonth+pos-firstday+1);
} else { // following month
text.setNum(pos-firstday-numdays+1);
}
painter->setPen(gray);
} else { // paint a day of the current month
text.setNum(pos-firstday+1);
painter->setPen(black);
}
pen=painter->pen();
if(firstday+date.day()-1==pos)
{
if(mMarkCurrent && firstday+QDate::currentDate().day()-1==pos)
painter->setPen(green);
else
painter->setPen(red);
if(hasFocus())
{
painter->setBrush(darkRed);
pen=white;
} else {
painter->setBrush(darkGray);
pen=white;
}
} else {
if(mMarkCurrent && firstday+QDate::currentDate().day()-1==pos)
{
painter->setPen(green);
painter->setBrush(darkGreen);
pen=white;
} else {
painter->setBrush(QColor(220,245,255));
painter->setPen(QColor(220,245,255));
}
}
painter->drawRect(0, 0, w, h);
painter->setPen(pen);
painter->drawText(0, 0, w, h, AlignCenter, text, -1, &rect);
}
/*
if(rect.width()>maxCell.width()) maxCell.setWidth(rect.width());
if(rect.height()>maxCell.height()) {
maxCell.setHeight(rect.height());
}
*/
}
void
KDateTable::keyPressEvent( QKeyEvent *e )
{
/*
// not working properly
if ( e->key() == Qt::Key_Prior ) {
if ( date.month() == 1 ) {
KNotifyClient::beep();
return;
}
int day = date.day();
if ( day > 27 )
while ( !QDate::isValid( date.year(), date.month()-1, day ) )
day--;
setDate(QDate(date.year(), date.month()-1, day));
return;
}
if ( e->key() == Qt::Key_Next ) {
if ( date.month() == 12 ) {
KNotifyClient::beep();
return;
}
int day = date.day();
if ( day > 27 )
while ( !QDate::isValid( date.year(), date.month()+1, day ) )
day--;
setDate(QDate(date.year(), date.month()+1, day));
return;
}
*/
int dayoff = KGlobal::locale()->weekStartsMonday() ? 1 : 0;
int temp=firstday+date.day()-dayoff;
int pos = temp;
bool irgnore = true;
if ( e->state() != Qt::ControlButton ) {
if ( e->key() == Qt::Key_Up ) {
pos -= 7;
irgnore = false;
}
if ( e->key() == Qt::Key_Down ) {
pos += 7;
irgnore = false;
}
if ( e->key() == Qt::Key_Left ) {
pos--;
irgnore = false;
}
if ( e->key() == Qt::Key_Right ) {
pos++;
irgnore = false;
}
}
if ( irgnore )
e->ignore();
if(pos+dayoff<=firstday)
{ // this day is in the previous month
KNotifyClient::beep();
return;
}
if(firstday+numdays<pos+dayoff)
{ // this date is in the next month
KNotifyClient::beep(i18n( "Month not long enough" ));
return;
}
if ( pos == temp )
return;
setDate(QDate(date.year(), date.month(), pos-firstday+dayoff));
updateCell(temp/7+1, temp%7); // Update the previously selected cell
updateCell(pos/7+1, pos%7); // Update the selected cell
assert(QDate(date.year(), date.month(), pos-firstday+dayoff).isValid());
}
void
KDateTable::viewportResizeEvent(QResizeEvent * e)
{
QGridView::viewportResizeEvent(e);
setCellWidth(viewport()->width()/7);
setCellHeight(viewport()->height()/7);
}
void
KDateTable::setFontSize(int size)
{
int count;
QRect rect;
// ----- store rectangles:
fontsize=size;
QFont _font = font();
_font.setPointSize(fontsize);
setFont( _font );
_font.setBold( true );
QFontMetrics metrics(_font);
// ----- find largest day name:
maxCell.setWidth(0);
maxCell.setHeight(0);
for(count=0; count<7; ++count)
{
rect=metrics.boundingRect(KGlobal::locale()->weekDayName(count+1, true));
maxCell.setWidth(QMAX(maxCell.width(), rect.width()));
maxCell.setHeight(QMAX(maxCell.height(), rect.height()));
}
// ----- compare with a real wide number and add some space:
rect=metrics.boundingRect(QString::fromLatin1("88"));
maxCell.setWidth(QMAX(maxCell.width()+2, rect.width()));
#ifdef DESKTOP_VERSION
maxCell.setHeight(QMAX(maxCell.height()+8, rect.height()));
#else
maxCell.setHeight(QMAX(maxCell.height()+4, rect.height()));
#endif
if ( maxCell.width() * 1000 / maxCell.height() > 1900 ) {
maxCell.setHeight(maxCell.width() * 1000 / 1900 );
- qDebug("setmax ");
+ //qDebug("setmax ");
}
}
void
KDateTable::contentsMousePressEvent(QMouseEvent *e)
{
if(e->type()!=QEvent::MouseButtonPress)
{ // the KDatePicker only reacts on mouse press events:
return;
}
if(!isEnabled())
{
KNotifyClient::beep();
return;
}
int dayoff = KGlobal::locale()->weekStartsMonday() ? 1 : 0;
// -----
int row, col, pos, temp;
QPoint mouseCoord;
// -----
mouseCoord = e->pos();
row=rowAt(mouseCoord.y());
col=columnAt(mouseCoord.x());
if(row<0 || col<0)
{ // the user clicked on the frame of the table
return;
}
pos=7*(row-1)+col+1;
#if 0
if(pos+dayoff<=firstday)
{ // this day is in the previous month
KNotifyClient::beep();
return;
}
if(firstday+numdays<pos+dayoff)
{ // this date is in the next month
KNotifyClient::beep();
return;
}
#endif
temp=firstday+date.day()-dayoff-1;
QDate da = QDate(date.year(), date.month(),1);
setDate(da.addDays( pos-firstday+dayoff-1));
updateCell(temp/7+1, temp%7); // Update the previously selected cell
updateCell(row, col); // Update the selected cell
// assert(QDate(date.year(), date.month(), pos-firstday+dayoff).isValid());
emit(tableClicked());
}
bool
KDateTable::setDate(const QDate& date_)
{
bool changed=false;
QDate temp;
mMarkCurrent = false;
// -----
if(!date_.isValid())
{
kdDebug() << "KDateTable::setDate: refusing to set invalid date." << endl;
return false;
}
if(date!=date_)
{
date=date_;
changed=true;
}
mMarkCurrent = ( date.month() == QDate::currentDate().month() && date.year() == QDate::currentDate().year() );
temp.setYMD(date.year(), date.month(), 1);
firstday=temp.dayOfWeek();
if(firstday==1) firstday=8;
numdays=date.daysInMonth();
if(date.month()==1)
{ // set to december of previous year
temp.setYMD(date.year()-1, 12, 1);
} else { // set to previous month
temp.setYMD(date.year(), date.month()-1, 1);
}
numDaysPrevMonth=temp.daysInMonth();
if(changed)
{
repaintContents(false);
}
emit(dateChanged(date));
return true;
}
const QDate&
KDateTable::getDate() const
{
return date;
}
void KDateTable::focusInEvent( QFocusEvent *e )
{
repaintContents(false);
QGridView::focusInEvent( e );
}
void KDateTable::focusOutEvent( QFocusEvent *e )
{
repaintContents(false);
QGridView::focusOutEvent( e );
}
QSize
KDateTable::sizeHint() const
{
if(maxCell.height()>0 && maxCell.width()>0)
{
return QSize((maxCell.width()+2)*numCols()+2*frameWidth(),
(maxCell.height()+4)*numRows()+2*frameWidth());
} else {
return QSize(-1, -1);
}
}
KDateInternalMonthPicker::KDateInternalMonthPicker
(QWidget* parent, const char* name)
: QGridView(parent, name),
result(0) // invalid
{
QRect rect;
QFont font;
// -----
activeCol = -1;
activeRow = -1;
font=KGlobalSettings::generalFont();
int fontsize = 10;
int add = 2;
if ( QApplication::desktop()->width() >= 480 && QApplication::desktop()->width() <= 640 )
add += 8;
if ( QApplication::desktop()->width() > 640 )
add += 6;
font.setPointSize(fontsize+add);
setFont(font);
setHScrollBarMode(AlwaysOff);
setVScrollBarMode(AlwaysOff);
setFrameStyle(QFrame::NoFrame);
setNumRows(4);
setNumCols(3);
// enable to find drawing failures:
// setTableFlags(Tbl_clipCellPainting);
#if 0
viewport()->setEraseColor(lightGray); // for consistency with the datepicker
#endif
// ----- find the preferred size
// (this is slow, possibly, but unfortunatly it is needed here):
QFontMetrics metrics(font);
for(int i=1; i <= 12; ++i)
{
rect=metrics.boundingRect(KGlobal::locale()->monthName(i, false));
if(max.width()<rect.width()) max.setWidth(rect.width());
if(max.height()<rect.height()) max.setHeight(rect.height());
}
}
QSize
KDateInternalMonthPicker::sizeHint() const
{
return QSize((max.width()+6)*numCols()+2*frameWidth(),
(max.height()+6)*numRows()+2*frameWidth());
}
int
KDateInternalMonthPicker::getResult() const
{
return result;
}
void
KDateInternalMonthPicker::setupPainter(QPainter *p)
{
p->setPen(black);
}
void
KDateInternalMonthPicker::viewportResizeEvent(QResizeEvent*)
{
setCellWidth(width()/3);
setCellHeight(height()/4);
}
void
KDateInternalMonthPicker::paintCell(QPainter* painter, int row, int col)
{
int index;
QString text;
// ----- find the number of the cell:
index=3*row+col+1;
text=KGlobal::locale()->monthName(index, false);
painter->drawText(0, 0, cellWidth(), cellHeight(), AlignCenter, text);
if ( activeCol == col && activeRow == row )
painter->drawRect( 0, 0, cellWidth(), cellHeight() );
}
void
KDateInternalMonthPicker::contentsMousePressEvent(QMouseEvent *e)
{
if(!isEnabled() || e->button() != LeftButton)
{
KNotifyClient::beep();
return;
}
// -----
int row, col;
QPoint mouseCoord;
// -----
mouseCoord = e->pos();
row=rowAt(mouseCoord.y());
col=columnAt(mouseCoord.x());
if(row<0 || col<0)
{ // the user clicked on the frame of the table
activeCol = -1;
activeRow = -1;
} else {
activeCol = col;
activeRow = row;
updateCell( row, col /*, false */ );
}
}
void
KDateInternalMonthPicker::contentsMouseMoveEvent(QMouseEvent *e)
{
if (e->state() & LeftButton)
{
int row, col;
QPoint mouseCoord;
// -----
mouseCoord = e->pos();
row=rowAt(mouseCoord.y());
col=columnAt(mouseCoord.x());
int tmpRow = -1, tmpCol = -1;
if(row<0 || col<0)
{ // the user clicked on the frame of the table
if ( activeCol > -1 )
{
tmpRow = activeRow;
tmpCol = activeCol;
}
activeCol = -1;
activeRow = -1;
} else {
bool differentCell = (activeRow != row || activeCol != col);
if ( activeCol > -1 && differentCell)
{
tmpRow = activeRow;
tmpCol = activeCol;
}
if ( differentCell)
{
activeRow = row;
activeCol = col;
updateCell( row, col /*, false */ ); // mark the new active cell
}
}
if ( tmpRow > -1 ) // repaint the former active cell
updateCell( tmpRow, tmpCol /*, true */ );
}
}
void
KDateInternalMonthPicker::contentsMouseReleaseEvent(QMouseEvent *e)
{
if(!isEnabled())
{
return;
}
// -----
int row, col, pos;
QPoint mouseCoord;
// -----
mouseCoord = e->pos();
row=rowAt(mouseCoord.y());
col=columnAt(mouseCoord.x());
if(row<0 || col<0)
{ // the user clicked on the frame of the table
emit(closeMe(0));
}
pos=3*row+col+1;
result=pos;
emit(closeMe(1));
}
KDateInternalYearSelector::KDateInternalYearSelector
(int fontsize, QWidget* parent, const char* name)
: QLineEdit(parent, name),
val(new QIntValidator(this)),
result(0)
{
QFont font;
// -----
font=KGlobalSettings::generalFont();
font.setPointSize(fontsize);
setFont(font);
#if 0
setFrameStyle(QFrame::NoFrame);
#endif
// we have to respect the limits of QDate here, I fear:
val->setRange(0, 8000);
setValidator(val);
connect(this, SIGNAL(returnPressed()), SLOT(yearEnteredSlot()));
}
void
KDateInternalYearSelector::yearEnteredSlot()
{
bool ok;
int year;
QDate date;
// ----- check if this is a valid year:
year=text().toInt(&ok);
if(!ok)
{
KNotifyClient::beep();
return;
}
date.setYMD(year, 1, 1);
if(!date.isValid())
{
KNotifyClient::beep();
return;
}
result=year;
emit(closeMe(1));
}
int
KDateInternalYearSelector::getYear()
{
return result;
}
void
KDateInternalYearSelector::setYear(int year)
{
QString temp;
// -----
temp.setNum(year);
setText(temp);
}
KPopupFrame::KPopupFrame(QWidget* parent, const char* name)
: QFrame(parent, name, WType_Popup),
result(0), // rejected
main(0)
{
setFrameStyle(QFrame::Box|QFrame::Raised);
setMidLineWidth(2);
}
void
KPopupFrame::keyPressEvent(QKeyEvent* e)
{
if(e->key()==Key_Escape)
{
result=0; // rejected
qApp->exit_loop();
}
}
void
KPopupFrame::close(int r)
{
result=r;
qApp->exit_loop();
}
void
KPopupFrame::setMainWidget(QWidget* m)
{
main=m;
if(main!=0)
{
resize(main->width()+2*frameWidth(), main->height()+2*frameWidth());
}
}
void
KPopupFrame::resizeEvent(QResizeEvent*)
{
if(main!=0)
{
main->setGeometry(frameWidth(), frameWidth(),
width()-2*frameWidth(), height()-2*frameWidth());
}
}
void
KPopupFrame::popup(const QPoint &pos)
{
// Make sure the whole popup is visible.
QRect d = QApplication::desktop()->frameGeometry();
int x = pos.x();
int y = pos.y();
int w = width();
int h = height();
if (x+w > d.x()+d.width())
x = d.width() - w;
if (y+h > d.y()+d.height())
y = d.height() - h;
if (x < d.x())
x = 0;
if (y < d.y())
y = 0;
// Pop the thingy up.
move(x, y);
show();
}
int
KPopupFrame::exec(QPoint pos)
{
popup(pos);
repaint();
qApp->enter_loop();
hide();
return result;
}
int
KPopupFrame::exec(int x, int y)
{
return exec(QPoint(x, y));
}
void KPopupFrame::virtual_hook( int, void* )
{ /*BASE::virtual_hook( id, data );*/ }
void KDateTable::virtual_hook( int, void* )
{ /*BASE::virtual_hook( id, data );*/ }
//#include "kdatetbl.moc"
KDateInternalWeekPicker::KDateInternalWeekPicker
(QWidget* parent, const char* name)
: QGridView(parent, name),
result(0) // invalid
{
QRect rect;
QFont font;
// -----
activeCol = -1;
activeRow = -1;
font=KGlobalSettings::generalFont();
int fontsize = 10;
int add = 2;
if ( QApplication::desktop()->width() >= 480 && QApplication::desktop()->width() <= 640 )
add += 6;
font.setPointSize(fontsize+add);
setFont(font);
setHScrollBarMode(AlwaysOff);
setVScrollBarMode(AlwaysOff);
setFrameStyle(QFrame::NoFrame);
setNumRows(13);
setNumCols(4);
// enable to find drawing failures:
// setTableFlags(Tbl_clipCellPainting);
#if 0
viewport()->setEraseColor(lightGray); // for consistency with the datepicker
#endif
// ----- find the preferred size
// (this is slow, possibly, but unfortunatly it is needed here):
QFontMetrics metrics(font);
for(int i=1; i <= 52; ++i)
{
rect=metrics.boundingRect(QString::number( i ));
if(max.width()<rect.width()) max.setWidth(rect.width());
if(max.height()<rect.height()) max.setHeight(rect.height());
}
if ( QApplication::desktop()->width() > 640 ) {
max.setWidth(max.width()+6);
max.setHeight(max.height()+8);
}
}
QSize
KDateInternalWeekPicker::sizeHint() const
{
return QSize((max.width()+6)*numCols()+2*frameWidth(),
(max.height()+6)*numRows()+2*frameWidth());
}
int
KDateInternalWeekPicker::getResult() const
{
return result;
}
void
KDateInternalWeekPicker::setupPainter(QPainter *p)
{
p->setPen(black);
}
void
KDateInternalWeekPicker::viewportResizeEvent(QResizeEvent*)
{
setCellWidth(width()/4);
setCellHeight(height()/13);
}
void
KDateInternalWeekPicker::paintCell(QPainter* painter, int row, int col)
diff --git a/microkde/kdecore/kstandarddirs.cpp b/microkde/kdecore/kstandarddirs.cpp
index 810c889..4ab1a68 100644
--- a/microkde/kdecore/kstandarddirs.cpp
+++ b/microkde/kdecore/kstandarddirs.cpp
@@ -694,993 +694,995 @@ KStandardDirs::realPath(const QString &dirname)
return dirname;
#endif
}
/*US
void KStandardDirs::createSpecialResource(const char *type)
{
char hostname[256];
hostname[0] = 0;
gethostname(hostname, 255);
QString dir = QString("%1%2-%3").arg(localkdedir()).arg(type).arg(hostname);
char link[1024];
link[1023] = 0;
int result = readlink(QFile::encodeName(dir).data(), link, 1023);
if ((result == -1) && (errno == ENOENT))
{
QString srv = findExe(QString::fromLatin1("lnusertemp"), KDEDIR+QString::fromLatin1("/bin"));
if (srv.isEmpty())
srv = findExe(QString::fromLatin1("lnusertemp"));
if (!srv.isEmpty())
{
system(QFile::encodeName(srv)+" "+type);
result = readlink(QFile::encodeName(dir).data(), link, 1023);
}
}
if (result > 0)
{
link[result] = 0;
if (link[0] == '/')
dir = QFile::decodeName(link);
else
dir = QDir::cleanDirPath(dir+QFile::decodeName(link));
}
addResourceDir(type, dir+'/');
}
*/
QStringList KStandardDirs::resourceDirs(const char *type) const
{
QStringList *candidates = dircache.find(type);
if (!candidates) { // filling cache
/*US
if (strcmp(type, "socket") == 0)
const_cast<KStandardDirs *>(this)->createSpecialResource(type);
else if (strcmp(type, "tmp") == 0)
const_cast<KStandardDirs *>(this)->createSpecialResource(type);
else if (strcmp(type, "cache") == 0)
const_cast<KStandardDirs *>(this)->createSpecialResource(type);
*/
QDir testdir;
candidates = new QStringList();
QStringList *dirs;
bool restrictionActive = false;
if (d && d->restrictionsActive)
{
if (d->dataRestrictionActive)
restrictionActive = true;
else if (d->restrictions["all"])
restrictionActive = true;
else if (d->restrictions[type])
restrictionActive = true;
d->dataRestrictionActive = false; // Reset
}
dirs = relatives.find(type);
if (dirs)
{
bool local = true;
const QStringList *prefixList = 0;
if (strncmp(type, "xdgdata-", 8) == 0)
prefixList = &(d->xdgdata_prefixes);
else if (strncmp(type, "xdgconf-", 8) == 0)
prefixList = &(d->xdgconf_prefixes);
else
prefixList = &prefixes;
for (QStringList::ConstIterator pit = prefixList->begin();
pit != prefixList->end();
pit++)
{
for (QStringList::ConstIterator it = dirs->begin();
it != dirs->end(); ++it) {
QString path = realPath(*pit + *it);
testdir.setPath(path);
if (local && restrictionActive)
continue;
if ((local || testdir.exists()) && !candidates->contains(path))
candidates->append(path);
}
local = false;
}
}
dirs = absolutes.find(type);
if (dirs)
for (QStringList::ConstIterator it = dirs->begin();
it != dirs->end(); ++it)
{
testdir.setPath(*it);
if (testdir.exists())
{
QString filename = realPath(*it);
if (!candidates->contains(filename))
candidates->append(filename);
}
}
dircache.insert(type, candidates);
}
#if 0
kdDebug() << "found dirs for resource " << type << ":" << endl;
for (QStringList::ConstIterator pit = candidates->begin();
pit != candidates->end();
pit++)
{
fprintf(stderr, "%s\n", (*pit).latin1());
}
#endif
return *candidates;
}
/*US
QString KStandardDirs::findExe( const QString& appname,
const QString& pstr, bool ignore)
{
QFileInfo info;
// absolute path ?
if (appname.startsWith(QString::fromLatin1("/")))
{
info.setFile( appname );
if( info.exists() && ( ignore || info.isExecutable() )
&& info.isFile() ) {
return appname;
}
return QString::null;
}
//US QString p = QString("%1/%2").arg(__KDE_BINDIR).arg(appname);
QString p = QString("%1/%2").arg(appname).arg(appname);
qDebug("KStandardDirs::findExe this is probably wrong");
info.setFile( p );
if( info.exists() && ( ignore || info.isExecutable() )
&& ( info.isFile() || info.isSymLink() ) ) {
return p;
}
QStringList tokens;
p = pstr;
if( p.isNull() ) {
p = getenv( "PATH" );
}
tokenize( tokens, p, ":\b" );
// split path using : or \b as delimiters
for( unsigned i = 0; i < tokens.count(); i++ ) {
p = tokens[ i ];
if ( p[ 0 ] == '~' )
{
int len = p.find( '/' );
if ( len == -1 )
len = p.length();
if ( len == 1 )
p.replace( 0, 1, QDir::homeDirPath() );
else
{
QString user = p.mid( 1, len - 1 );
struct passwd *dir = getpwnam( user.local8Bit().data() );
if ( dir && strlen( dir->pw_dir ) )
p.replace( 0, len, QString::fromLocal8Bit( dir->pw_dir ) );
}
}
p += "/";
p += appname;
// Check for executable in this tokenized path
info.setFile( p );
if( info.exists() && ( ignore || info.isExecutable() )
&& ( info.isFile() || info.isSymLink() ) ) {
return p;
}
}
// If we reach here, the executable wasn't found.
// So return empty string.
return QString::null;
}
int KStandardDirs::findAllExe( QStringList& list, const QString& appname,
const QString& pstr, bool ignore )
{
QString p = pstr;
QFileInfo info;
QStringList tokens;
if( p.isNull() ) {
p = getenv( "PATH" );
}
list.clear();
tokenize( tokens, p, ":\b" );
for ( unsigned i = 0; i < tokens.count(); i++ ) {
p = tokens[ i ];
p += "/";
p += appname;
info.setFile( p );
if( info.exists() && (ignore || info.isExecutable())
&& info.isFile() ) {
list.append( p );
}
}
return list.count();
}
*/
static int tokenize( QStringList& tokens, const QString& str,
const QString& delim )
{
int len = str.length();
QString token = "";
for( int index = 0; index < len; index++)
{
if ( delim.find( str[ index ] ) >= 0 )
{
tokens.append( token );
token = "";
}
else
{
token += str[ index ];
}
}
if ( token.length() > 0 )
{
tokens.append( token );
}
return tokens.count();
}
QString KStandardDirs::kde_default(const char *type) {
if (!strcmp(type, "data"))
return "apps/";
if (!strcmp(type, "html"))
return "share/doc/HTML/";
if (!strcmp(type, "icon"))
return "share/icons/";
if (!strcmp(type, "config"))
return "config/";
if (!strcmp(type, "pixmap"))
return "share/pixmaps/";
if (!strcmp(type, "apps"))
return "share/applnk/";
if (!strcmp(type, "sound"))
return "share/sounds/";
if (!strcmp(type, "locale"))
return "share/locale/";
if (!strcmp(type, "services"))
return "share/services/";
if (!strcmp(type, "servicetypes"))
return "share/servicetypes/";
if (!strcmp(type, "mime"))
return "share/mimelnk/";
if (!strcmp(type, "cgi"))
return "cgi-bin/";
if (!strcmp(type, "wallpaper"))
return "share/wallpapers/";
if (!strcmp(type, "templates"))
return "share/templates/";
if (!strcmp(type, "exe"))
return "bin/";
if (!strcmp(type, "lib"))
return "lib/";
if (!strcmp(type, "module"))
return "lib/kde3/";
if (!strcmp(type, "qtplugins"))
return "lib/kde3/plugins";
if (!strcmp(type, "xdgdata-apps"))
return "applications/";
if (!strcmp(type, "xdgdata-dirs"))
return "desktop-directories/";
if (!strcmp(type, "xdgconf-menu"))
return "menus/";
if (!strcmp(type, "tmp"))
return "tmp/";
qFatal("unknown resource type %s", type);
return QString::null;
}
QString KStandardDirs::saveLocation(const char *type,
const QString& suffix,
bool create) const
{
//qDebug("KStandardDirs::saveLocation called %s %s", type,suffix.latin1() );
//return "";
checkConfig();
QString *pPath = savelocations.find(type);
if (!pPath)
{
QStringList *dirs = relatives.find(type);
if (!dirs && (
(strcmp(type, "socket") == 0) ||
(strcmp(type, "tmp") == 0) ||
(strcmp(type, "cache") == 0) ))
{
(void) resourceDirs(type); // Generate socket|tmp|cache resource.
dirs = relatives.find(type); // Search again.
}
if (dirs)
{
// Check for existance of typed directory + suffix
if (strncmp(type, "xdgdata-", 8) == 0)
pPath = new QString(realPath(localxdgdatadir() + dirs->last()));
else if (strncmp(type, "xdgconf-", 8) == 0)
pPath = new QString(realPath(localxdgconfdir() + dirs->last()));
else
pPath = new QString(realPath(localkdedir() + dirs->last()));
}
else {
dirs = absolutes.find(type);
if (!dirs)
qFatal("KStandardDirs: The resource type %s is not registered", type);
pPath = new QString(realPath(dirs->last()));
}
savelocations.insert(type, pPath);
}
QString fullPath = *pPath + suffix;
//US struct stat st;
//US if (stat(QFile::encodeName(fullPath), &st) != 0 || !(S_ISDIR(st.st_mode)))
QFileInfo fullPathInfo(QFile::encodeName(fullPath));
if (fullPathInfo.isReadable() || !fullPathInfo.isDir())
{
if(!create) {
#ifndef NDEBUG
qDebug("save location %s doesn't exist", fullPath.latin1());
#endif
return fullPath;
}
if(!makeDir(fullPath, 0700)) {
qWarning("failed to create %s", fullPath.latin1());
return fullPath;
}
dircache.remove(type);
}
return fullPath;
}
QString KStandardDirs::relativeLocation(const char *type, const QString &absPath)
{
QString fullPath = absPath;
int i = absPath.findRev('/');
if (i != -1)
{
fullPath = realPath(absPath.left(i+1))+absPath.mid(i+1); // Normalize
}
QStringList candidates = resourceDirs(type);
for (QStringList::ConstIterator it = candidates.begin();
it != candidates.end(); it++)
if (fullPath.startsWith(*it))
{
return fullPath.mid((*it).length());
}
return absPath;
}
bool KStandardDirs::makeDir(const QString& dir2, int mode)
{
QString dir = QDir::convertSeparators( dir2 );
#if 0
//LR
// we want an absolute path
if (dir.at(0) != '/')
return false;
QString target = dir;
uint len = target.length();
// append trailing slash if missing
if (dir.at(len - 1) != '/')
target += '/';
QString base("");
uint i = 1;
while( i < len )
{
//US struct stat st;
int pos = target.find('/', i);
base += target.mid(i - 1, pos - i + 1);
QCString baseEncoded = QFile::encodeName(base);
// bail out if we encountered a problem
//US if (stat(baseEncoded, &st) != 0)
QFileInfo baseEncodedInfo(baseEncoded);
if (!baseEncodedInfo.exists())
{
// Directory does not exist....
// Or maybe a dangling symlink ?
//US if (lstat(baseEncoded, &st) == 0)
if (baseEncodedInfo.isSymLink()) {
//US (void)unlink(baseEncoded); // try removing
QFile(baseEncoded).remove();
}
//US if ( mkdir(baseEncoded, (mode_t) mode) != 0)
QDir dirObj;
if ( dirObj.mkdir(baseEncoded) != true )
{
//US perror("trying to create local folder");
return false; // Couldn't create it :-(
}
}
i = pos + 1;
}
return true;
#endif
// ********************************************
// new code for WIN32
QDir dirObj;
// we want an absolute path
#ifndef _WIN32_
if (dir.at(0) != '/')
return false;
#endif
QString target = dir;
uint len = target.length();
#ifndef _WIN32_
// append trailing slash if missing
if (dir.at(len - 1) != '/')
target += '/';
#endif
QString base("");
uint i = 1;
while( i < len )
{
//US struct stat st;
#ifndef _WIN32_
int pos = target.find('/', i);
#else
int pos = target.find('\\', i);
#endif
if ( pos < 0 )
return true;
base += target.mid(i - 1, pos - i + 1);
//QMessageBox::information( 0,"cap111", base, 1 );
/*US
QCString baseEncoded = QFile::encodeName(base);
// bail out if we encountered a problem
if (stat(baseEncoded, &st) != 0)
{
// Directory does not exist....
// Or maybe a dangling symlink ?
if (lstat(baseEncoded, &st) == 0)
(void)unlink(baseEncoded); // try removing
if ( mkdir(baseEncoded, (mode_t) mode) != 0) {
perror("trying to create local folder");
return false; // Couldn't create it :-(
}
}
*/
if (dirObj.exists(base) == false)
{
//qDebug("KStandardDirs::makeDir try to create : %s" , base.latin1());
if (dirObj.mkdir(base) != true)
{
qDebug("KStandardDirs::makeDir could not create: %s" , base.latin1());
return false;
}
}
i = pos + 1;
}
return true;
}
-static QString readEnvPath(const char *env)
+QString readEnvPath(const char *env)
{
//#ifdef _WIN32_
// return "";
//#else
QCString c_path;
if ( getenv(env) != NULL )
c_path = QString ( getenv(env) );
if (c_path.isEmpty())
return QString::null;
return QFile::decodeName(c_path);
//#endif
}
void KStandardDirs::addKDEDefaults()
{
//qDebug("ERROR: KStandardDirs::addKDEDefaults() called ");
//return;
QStringList kdedirList;
// begin KDEDIRS
QString kdedirs = readEnvPath("MICROKDEDIRS");
if (!kdedirs.isEmpty())
{
tokenize(kdedirList, kdedirs, ":");
}
else
{
QString kdedir = readEnvPath("MICROKDEDIR");
if (!kdedir.isEmpty())
{
kdedir = KShell::tildeExpand(kdedir);
kdedirList.append(kdedir);
}
}
//US kdedirList.append(KDEDIR);
//US for embedded, add qtopia dir as kdedir
#ifndef DESKTOP_VERSION
QString tmp = readEnvPath("QPEDIR");
if (!tmp.isEmpty())
kdedirList.append(tmp);
tmp = readEnvPath("QTDIR");
if (!tmp.isEmpty())
kdedirList.append(tmp);
tmp = readEnvPath("OPIEDIR");
if (!tmp.isEmpty())
kdedirList.append(tmp);
#endif
#ifdef __KDE_EXECPREFIX
QString execPrefix(__KDE_EXECPREFIX);
if (execPrefix!="NONE")
kdedirList.append(execPrefix);
#endif
QString localKdeDir;
//US if (getuid())
if (true)
{
localKdeDir = readEnvPath("MICROKDEHOME");
if (!localKdeDir.isEmpty())
{
#ifdef _WIN32_
if (localKdeDir.at(localKdeDir.length()-1) != '\\')
localKdeDir += '\\';
#else
if (localKdeDir.at(localKdeDir.length()-1) != '/')
localKdeDir += '/';
#endif
//QMessageBox::information( 0,"localKdeDir",localKdeDir, 1 );
}
else
{
QString confFile;
#ifdef DESKTOP_VERSION
confFile = qApp->applicationDirPath ()+ "/.microkdehome" ;
QFileInfo fi ( confFile );
if ( !fi.exists() )
confFile = QDir::homeDirPath() + "/.microkdehome";
else
qDebug("Loading path info from " + confFile );
#else
confFile = QDir::homeDirPath() + "/.microkdehome";
#endif
KConfig cfg ( confFile );
cfg.setGroup("Global");
localKdeDir = cfg.readEntry( "MICROKDEHOME", QDir::homeDirPath() + "/kdepim/" );
#ifdef DESKTOP_VERSION
if ( localKdeDir.startsWith( "LOCAL:" ) ) {
#ifdef _WIN32_
localKdeDir = qApp->applicationDirPath () + "\\"+ localKdeDir.mid( 6 );
#else
localKdeDir = qApp->applicationDirPath () + "/"+ localKdeDir.mid( 6 );
#endif
qDebug("Using local conf dir %s ",localKdeDir.latin1() );
+ // <stdlib.h>
+ setenv( "LOCALMICROKDEHOME", localKdeDir.latin1(), 1 );
}
#endif
}
}
else
{
// We treat root different to prevent root messing up the
// file permissions in the users home directory.
localKdeDir = readEnvPath("MICROKDEROOTHOME");
if (!localKdeDir.isEmpty())
{
if (localKdeDir.at(localKdeDir.length()-1) != '/')
localKdeDir += '/';
}
else
{
//US struct passwd *pw = getpwuid(0);
//US localKdeDir = QFile::decodeName((pw && pw->pw_dir) ? pw->pw_dir : "/root") + "/.microkde/";
qDebug("KStandardDirs::addKDEDefaults: 1 has to be fixed");
}
}
//US localKdeDir = appDir();
//US
// qDebug("KStandardDirs::addKDEDefaults: localKdeDir=%s", localKdeDir.latin1());
if (localKdeDir != "-/")
{
localKdeDir = KShell::tildeExpand(localKdeDir);
addPrefix(localKdeDir);
}
for (QStringList::ConstIterator it = kdedirList.begin();
it != kdedirList.end(); it++)
{
QString dir = KShell::tildeExpand(*it);
addPrefix(dir);
}
// end KDEDIRS
// begin XDG_CONFIG_XXX
QStringList xdgdirList;
QString xdgdirs = readEnvPath("XDG_CONFIG_DIRS");
if (!xdgdirs.isEmpty())
{
tokenize(xdgdirList, xdgdirs, ":");
}
else
{
xdgdirList.clear();
xdgdirList.append("/etc/xdg");
}
QString localXdgDir = readEnvPath("XDG_CONFIG_HOME");
if (!localXdgDir.isEmpty())
{
if (localXdgDir.at(localXdgDir.length()-1) != '/')
localXdgDir += '/';
}
else
{
//US if (getuid())
if (true)
{
localXdgDir = QDir::homeDirPath() + "/.config/";
}
else
{
//US struct passwd *pw = getpwuid(0);
//US localXdgDir = QFile::decodeName((pw && pw->pw_dir) ? pw->pw_dir : "/root") + "/.config/";
qDebug("KStandardDirs::addKDEDefaults: 2 has to be fixed");
}
}
localXdgDir = KShell::tildeExpand(localXdgDir);
addXdgConfigPrefix(localXdgDir);
for (QStringList::ConstIterator it = xdgdirList.begin();
it != xdgdirList.end(); it++)
{
QString dir = KShell::tildeExpand(*it);
addXdgConfigPrefix(dir);
}
// end XDG_CONFIG_XXX
// begin XDG_DATA_XXX
xdgdirs = readEnvPath("XDG_DATA_DIRS");
if (!xdgdirs.isEmpty())
{
tokenize(xdgdirList, xdgdirs, ":");
}
else
{
xdgdirList.clear();
for (QStringList::ConstIterator it = kdedirList.begin();
it != kdedirList.end(); it++)
{
QString dir = *it;
if (dir.at(dir.length()-1) != '/')
dir += '/';
xdgdirList.append(dir+"share/");
}
xdgdirList.append("/usr/local/share/");
xdgdirList.append("/usr/share/");
}
localXdgDir = readEnvPath("XDG_DATA_HOME");
if (!localXdgDir.isEmpty())
{
if (localXdgDir.at(localXdgDir.length()-1) != '/')
localXdgDir += '/';
}
else
{
//US if (getuid())
if (true)
{
localXdgDir = QDir::homeDirPath() + "/.local/share/";
}
else
{
//US struct passwd *pw = getpwuid(0);
//US localXdgDir = QFile::decodeName((pw && pw->pw_dir) ? pw->pw_dir : "/root") + "/.local/share/";
qDebug("KStandardDirs::addKDEDefaults: 3 has to be fixed");
}
}
localXdgDir = KShell::tildeExpand(localXdgDir);
addXdgDataPrefix(localXdgDir);
for (QStringList::ConstIterator it = xdgdirList.begin();
it != xdgdirList.end(); it++)
{
QString dir = KShell::tildeExpand(*it);
addXdgDataPrefix(dir);
}
// end XDG_DATA_XXX
uint index = 0;
while (types[index] != 0) {
addResourceType(types[index], kde_default(types[index]));
index++;
}
addResourceDir("home", QDir::homeDirPath());
}
void KStandardDirs::checkConfig() const
{
/*US
if (!addedCustoms && KGlobal::_instance && KGlobal::_instance->_config)
const_cast<KStandardDirs*>(this)->addCustomized(KGlobal::_instance->_config);
*/
if (!addedCustoms && KGlobal::config())
const_cast<KStandardDirs*>(this)->addCustomized(KGlobal::config());
}
bool KStandardDirs::addCustomized(KConfig *config)
{
if (addedCustoms) // there are already customized entries
return false; // we just quite and hope they are the right ones
// save the numbers of config directories. If this changes,
// we will return true to give KConfig a chance to reparse
uint configdirs = resourceDirs("config").count();
// reading the prefixes in
QString oldGroup = config->group();
config->setGroup("Directories");
QStringList list;
QStringList::ConstIterator it;
list = config->readListEntry("prefixes");
for (it = list.begin(); it != list.end(); it++)
addPrefix(*it);
// iterating over all entries in the group Directories
// to find entries that start with dir_$type
/*US
QMap<QString, QString> entries = config->entryMap("Directories");
QMap<QString, QString>::ConstIterator it2;
for (it2 = entries.begin(); it2 != entries.end(); it2++)
{
QString key = it2.key();
if (key.left(4) == "dir_") {
// generate directory list, there may be more than 1.
QStringList dirs = QStringList::split(',', *it2);
QStringList::Iterator sIt(dirs.begin());
QString resType = key.mid(4, key.length());
for (; sIt != dirs.end(); ++sIt) {
addResourceDir(resType.latin1(), *sIt);
}
}
}
// Process KIOSK restrictions.
config->setGroup("KDE Resource Restrictions");
entries = config->entryMap("KDE Resource Restrictions");
for (it2 = entries.begin(); it2 != entries.end(); it2++)
{
QString key = it2.key();
if (!config->readBoolEntry(key, true))
{
d->restrictionsActive = true;
d->restrictions.insert(key.latin1(), &d->restrictionsActive); // Anything will do
dircache.remove(key.latin1());
}
}
*/
// save it for future calls - that will return
addedCustoms = true;
config->setGroup(oldGroup);
// return true if the number of config dirs changed
return (resourceDirs("config").count() != configdirs);
}
QString KStandardDirs::localkdedir() const
{
// Return the prefix to use for saving
return prefixes.first();
}
QString KStandardDirs::localxdgdatadir() const
{
// Return the prefix to use for saving
return d->xdgdata_prefixes.first();
}
QString KStandardDirs::localxdgconfdir() const
{
// Return the prefix to use for saving
return d->xdgconf_prefixes.first();
}
void KStandardDirs::setAppDir( const QString &appDir )
{
mAppDir = appDir;
if ( mAppDir.right( 1 ) != "/" )
mAppDir += "/";
}
QString KStandardDirs::appDir()
{
return mAppDir;
}
// just to make code more readable without macros
QString locate( const char *type,
const QString& filename/*US , const KInstance* inst*/ )
{
//US return inst->dirs()->findResource(type, filename);
return KGlobal::dirs()->findResource(type, filename);
}
QString locateLocal( const char *type,
const QString& filename/*US , const KInstance* inst*/ )
{
QString path = locateLocal(type, filename, true /*US, inst*/);
/*
static int ccc = 0;
++ccc;
if ( ccc > 13 )
abort();
*/
//qDebug("locatelocal: %s" , path.latin1());
return path;
/*US why do we put all files into one directory. It is quit complicated.
why not staying with the original directorystructure ?
QString escapedFilename = filename;
escapedFilename.replace( QRegExp( "/" ), "_" );
QString path = KStandardDirs::appDir() + type + "_" + escapedFilename;
kdDebug() << "locate: '" << path << "'" << endl;
qDebug("locate: %s" , path.latin1());
return path;
*/
//US so my proposal is this:
// QString escapedFilename = filename;
// escapedFilename.replace( QRegExp( "/" ), "_" );
#if 0
#ifdef _WIN32_
QString path = QDir::convertSeparators(KStandardDirs::appDir() + type + "/" + filename);
#else
QString path = KStandardDirs::appDir() + type + "/" + filename;
#endif
//US Create the containing dir if needed
QFileInfo fi ( path );
// QString dir=pathurl.directory();
// QMessageBox::information( 0,"path", path, 1 );
#ifdef _WIN32_
KStandardDirs::makeDir(path);
#else
KStandardDirs::makeDir(fi.dirPath( true ));
#endif
qDebug("locate22: %s" , path.latin1());
return path;
#endif
}
QString locateLocal( const char *type,
const QString& filename, bool createDir/*US , const KInstance* inst*/ )
{
// try to find slashes. If there are some, we have to
// create the subdir first
int slash = filename.findRev('/')+1;
if (!slash) // only one filename
//US return inst->dirs()->saveLocation(type, QString::null, createDir) + filename;
return KGlobal::dirs()->saveLocation(type, QString::null, createDir) + filename;
// split path from filename
QString dir = filename.left(slash);
QString file = filename.mid(slash);
//US return inst->dirs()->saveLocation(type, dir, createDir) + file;
return KGlobal::dirs()->saveLocation(type, dir, createDir) + file;
// ***************************************************************
#if 0
/*US why do we put all files into one directory. It is quit complicated.
why not staying with the original directorystructure ?
QString escapedFilename = filename;
escapedFilename.replace( QRegExp( "/" ), "_" );
QString path = KStandardDirs::appDir() + type + "_" + escapedFilename;
kdDebug() << "locate: '" << path << "'" << endl;
qDebug("locate: %s" , path.latin1());
return path;
*/
//US so my proposal is this:
// QString escapedFilename = filename;
// escapedFilename.replace( QRegExp( "/" ), "_" );
#ifdef _WIN32_
QString path = QDir::convertSeparators(KStandardDirs::appDir() + type + "/" + filename);
#else
QString path = KStandardDirs::appDir() + type + "/" + filename;
#endif
//US Create the containing dir if needed
KURL pathurl;
pathurl.setPath(path);
QString dir=pathurl.directory();
// QMessageBox::information( 0,"path", path, 1 );
#ifdef _WIN32_
KStandardDirs::makeDir(path);
#else
KStandardDirs::makeDir(dir);
#endif
return path;
#endif
}
diff --git a/microkde/kdecore/kstandarddirs.h b/microkde/kdecore/kstandarddirs.h
index bee864e..901384e 100644
--- a/microkde/kdecore/kstandarddirs.h
+++ b/microkde/kdecore/kstandarddirs.h
@@ -138,544 +138,548 @@ public:
/**
* Adds another search dir to front of the @p fsstnd list.
*
* @li When compiling kdelibs, the prefix is added to this.
* @li KDEDIRS or KDEDIR is taking into account
* @li Additional dirs may be loaded from kdeglobals.
*
* @param dir The directory to append relative paths to.
*/
void addPrefix( const QString& dir );
/**
* Adds another search dir to front of the XDG_CONFIG_XXX list
* of prefixes.
* This prefix is only used for resources that start with "xdgconf-"
*
* @param dir The directory to append relative paths to.
*/
void addXdgConfigPrefix( const QString& dir );
/**
* Adds another search dir to front of the XDG_DATA_XXX list
* of prefixes.
* This prefix is only used for resources that start with "xdgdata-"
*
* @param dir The directory to append relative paths to.
*/
void addXdgDataPrefix( const QString& dir );
/**
* Adds suffixes for types.
*
* You may add as many as you need, but it is advised that there
* is exactly one to make writing definite.
* All basic types (@ref kde_default) are added by @ref addKDEDefaults(),
* but for those you can add more relative paths as well.
*
* The later a suffix is added, the higher its priority. Note, that the
* suffix should end with / but doesn't have to start with one (as prefixes
* should end with one). So adding a suffix for app_pics would look
* like KGlobal::dirs()->addResourceType("app_pics", "share/app/pics");
*
* @param type Specifies a short descriptive string to access
* files of this type.
* @param relativename Specifies a directory relative to the root
* of the KFSSTND.
* @return true if successful, false otherwise.
*/
bool addResourceType( const char *type,
const QString& relativename );
/**
* Adds absolute path at the end of the search path for
* particular types (for example in case of icons where
* the user specifies extra paths).
*
* You shouldn't need this
* function in 99% of all cases besides adding user-given
* paths.
*
* @param type Specifies a short descriptive string to access files
* of this type.
* @param absdir Points to directory where to look for this specific
* type. Non-existant directories may be saved but pruned.
* @return true if successful, false otherwise.
*/
bool addResourceDir( const char *type,
const QString& absdir);
/**
* Tries to find a resource in the following order:
* @li All PREFIX/\<relativename> paths (most recent first).
* @li All absolute paths (most recent first).
*
* The filename should be a filename relative to the base dir
* for resources. So is a way to get the path to libkdecore.la
* to findResource("lib", "libkdecore.la"). KStandardDirs will
* then look into the subdir lib of all elements of all prefixes
* ($KDEDIRS) for a file libkdecore.la and return the path to
* the first one it finds (e.g. /opt/kde/lib/libkdecore.la)
*
* @param type The type of the wanted resource
* @param filename A relative filename of the resource.
*
* @return A full path to the filename specified in the second
* argument, or QString::null if not found.
*/
QString findResource( const char *type,
const QString& filename ) const;
/**
* Checks whether a resource is restricted as part of the KIOSK
* framework. When a resource is restricted it means that user-
* specific files in the resource are ignored.
*
* E.g. by restricting the "wallpaper" resource, only system-wide
* installed wallpapers will be found by this class. Wallpapers
* installed under the $KDEHOME directory will be ignored.
*
* @param type The type of the resource to check
* @param relPath A relative path in the resource.
*
* @return True if the resource is restricted.
* @since 3.1
*/
bool isRestrictedResource( const char *type,
const QString& relPath=QString::null ) const;
/**
* Returns a number that identifies this version of the resource.
* When a change is made to the resource this number will change.
*
* @param type The type of the wanted resource
* @param filename A relative filename of the resource.
* @param deep If true, all resources are taken into account
* otherwise only the one returned by findResource().
*
* @return A number identifying the current version of the
* resource.
*/
/*US
Q_UINT32 calcResourceHash( const char *type,
const QString& filename, bool deep) const;
*/
/**
* Tries to find all directories whose names consist of the
* specified type and a relative path. So would
* findDirs("apps", "Settings") return
* @li /opt/kde/share/applnk/Settings/
* @li /home/joe/.kde/share/applnk/Settings/
*
* Note that it appends / to the end of the directories,
* so you can use this right away as directory names.
*
* @param type The type of the base directory.
* @param reldir Relative directory.
*
* @return A list of matching directories, or an empty
* list if the resource specified is not found.
*/
QStringList findDirs( const char *type,
const QString& reldir ) const;
/**
* Tries to find the directory the file is in.
* It works the same as @ref findResource(), but it doesn't
* return the filename but the name of the directory.
*
* This way the application can access a couple of files
* that have been installed into the same directory without
* having to look for each file.
*
* findResourceDir("lib", "libkdecore.la") would return the
* path of the subdir libkdecore.la is found first in
* (e.g. /opt/kde/lib/)
*
* @param type The type of the wanted resource
* @param filename A relative filename of the resource.
* @return The directory where the file specified in the second
* argument is located, or QString::null if the type
* of resource specified is unknown or the resource
* cannot be found.
*/
QString findResourceDir( const char *type,
const QString& filename) const;
/**
* Tries to find all resources with the specified type.
*
* The function will look into all specified directories
* and return all filenames in these directories.
*
* @param type The type of resource to locate directories for.
* @param filter Only accept filenames that fit to filter. The filter
* may consist of an optional directory and a @ref QRegExp
* wildcard expression. E.g. "images\*.jpg". Use QString::null
* if you do not want a filter.
* @param recursive Specifies if the function should decend
* into subdirectories.
* @param uniq If specified, only return items which have
* unique suffixes - suppressing duplicated filenames.
*
* @return A list of directories matching the resource specified,
* or an empty list if the resource type is unknown.
*/
QStringList findAllResources( const char *type,
const QString& filter = QString::null,
bool recursive = false,
bool uniq = false) const;
/**
* Tries to find all resources with the specified type.
*
* The function will look into all specified directories
* and return all filenames (full and relative paths) in
* these directories.
*
* @param type The type of resource to locate directories for.
* @param filter Only accept filenames that fit to filter. The filter
* may consist of an optional directory and a @ref QRegExp
* wildcard expression. E.g. "images\*.jpg". Use QString::null
* if you do not want a filter.
* @param recursive Specifies if the function should decend
* into subdirectories.
* @param uniq If specified, only return items which have
* unique suffixes.
* @param list Of relative paths for the given type.
* @param relPaths The list to store the relative paths into
* These can be used later to ::locate() the file
*
* @return A list of directories matching the resource specified,
* or an empty list if the resource type is unknown.
*/
QStringList findAllResources( const char *type,
const QString& filter,
bool recursive,
bool uniq,
QStringList &relPaths) const;
/**
* Finds the executable in the system path.
*
* A valid executable must
* be a file and have its executable bit set.
*
* @param appname The name of the executable file for which to search.
* @param pathstr The path which will be searched. If this is
* null (default), the $PATH environment variable will
* be searched.
* @param ignoreExecBit If true, an existing file will be returned
* even if its executable bit is not set.
*
* @return The path of the executable. If it was not found,
* it will return QString::null.
* @see findAllExe()
*/
/*US
static QString findExe( const QString& appname,
const QString& pathstr=QString::null,
bool ignoreExecBit=false );
*/
/**
* Finds all occurences of an executable in the system path.
*
* @param list Will be filled with the pathnames of all the
* executables found. Will be empty if the executable
* was not found.
* @param appname The name of the executable for which to
* search.
* @param pathstr The path list which will be searched. If this
* is 0 (default), the $PATH environment variable will
* be searched.
* @param ignoreExecBit If true, an existing file will be returned
* even if its executable bit is not set.
*
* @return The number of executables found, 0 if none were found.
*
* @see findExe()
*/
static int findAllExe( QStringList& list, const QString& appname,
const QString& pathstr=QString::null,
bool ignoreExecBit=false );
/**
* This function adds the defaults that are used by the current
* KDE version.
*
* It's a series of @ref addResourceTypes()
* and @ref addPrefix() calls.
* You normally wouldn't call this function because it's called
* for you from @ref KGlobal.
*/
void addKDEDefaults();
/**
* Reads customized entries out of the given config object and add
* them via @ref addResourceDirs().
*
* @param config The object the entries are read from. This should
* contain global config files
* @return true if new config paths have been added
* from @p config.
**/
bool addCustomized(KConfig *config);
/**
* This function is used internally by almost all other function as
* it serves and fills the directories cache.
*
* @param type The type of resource
* @return The list of possible directories for the specified @p type.
* The function updates the cache if possible. If the resource
* type specified is unknown, it will return an empty list.
* Note, that the directories are assured to exist beside the save
* location, which may not exist, but is returned anyway.
*/
QStringList resourceDirs(const char *type) const;
/**
* This function will return a list of all the types that KStandardDirs
* supports.
*
* @return All types that KDE supports
*/
QStringList allTypes() const;
/**
* Finds a location to save files into for the given type
* in the user's home directory.
*
* @param type The type of location to return.
* @param suffix A subdirectory name.
* Makes it easier for you to create subdirectories.
* You can't pass filenames here, you _have_ to pass
* directory names only and add possible filename in
* that directory yourself. A directory name always has a
* trailing slash ('/').
* @param create If set, saveLocation() will create the directories
* needed (including those given by @p suffix).
*
* @return A path where resources of the specified type should be
* saved, or QString::null if the resource type is unknown.
*/
QString saveLocation(const char *type,
const QString& suffix = QString::null,
bool create = true) const;
/**
* Converts an absolute path to a path relative to a certain
* resource.
*
* If "abs = ::locate(resource, rel)"
* then "rel = relativeLocation(resource, abs)" and vice versa.
*
* @param type The type of resource.
*
* @param absPath An absolute path to make relative.
*
* @return A relative path relative to resource @p type that
* will find @p absPath. If no such relative path exists, absPath
* will be returned unchanged.
*/
QString relativeLocation(const char *type, const QString &absPath);
/**
* Recursively creates still-missing directories in the given path.
*
* The resulting permissions will depend on the current umask setting.
* permission = mode & ~umask.
*
* @param dir Absolute path of the directory to be made.
* @param mode Directory permissions.
* @return true if successful, false otherwise
*/
static bool makeDir(const QString& dir, int mode = 0755);
/**
* This returns a default relative path for the standard KDE
* resource types. Below is a list of them so you get an idea
* of what this is all about.
*
* @li data - share/apps
* @li html - share/doc/HTML
* @li icon - share/icon
* @li config - share/config
* @li pixmap - share/pixmaps
* @li apps - share/applnk
* @li sound - share/sounds
* @li locale - share/locale
* @li services - share/services
* @li servicetypes - share/servicetypes
* @li mime - share/mimelnk
* @li wallpaper - share/wallpapers
* @li templates - share/templates
* @li exe - bin
* @li lib - lib
*
* @returns Static default for the specified resource. You
* should probably be using locate() or locateLocal()
* instead.
* @see locate()
* @see locateLocal()
*/
static QString kde_default(const char *type);
/**
* @internal (for use by sycoca only)
*/
QString kfsstnd_prefixes();
/**
* Returns the toplevel directory in which KStandardDirs
* will store things. Most likely $HOME/.kde
* Don't use this function if you can use locateLocal
* @return the toplevel directory
*/
QString localkdedir() const;
/**
* @return $XDG_DATA_HOME
* See also http://www.freedesktop.org/standards/basedir/draft/basedir-spec/basedir-spec.html
*/
QString localxdgdatadir() const;
/**
* @return $XDG_CONFIG_HOME
* See also http://www.freedesktop.org/standards/basedir/draft/basedir-spec/basedir-spec.html
*/
QString localxdgconfdir() const;
/**
* Checks for existence and accessability.
* Faster than creating a QFileInfo first.
* @param fullPath the path to check
* @return true if the directory exists
*/
static bool exists(const QString &fullPath);
/**
* Expands all symbolic links and resolves references to
* '/./', '/../' and extra '/' characters in @p dirname
* and returns the canonicalized absolute pathname.
* The resulting path will have no symbolic link, '/./'
* or '/../' components.
* @since 3.1
*/
static QString realPath(const QString &dirname);
static void setAppDir( const QString & );
static QString appDir();
private:
QStringList prefixes;
// Directory dictionaries
QDict<QStringList> absolutes;
QDict<QStringList> relatives;
mutable QDict<QStringList> dircache;
mutable QDict<QString> savelocations;
// Disallow assignment and copy-construction
KStandardDirs( const KStandardDirs& );
KStandardDirs& operator= ( const KStandardDirs& );
bool addedCustoms;
class KStandardDirsPrivate;
KStandardDirsPrivate *d;
//US
static QString mAppDir;
void checkConfig() const;
void applyDataRestrictions(const QString &) const;
//US void createSpecialResource(const char*);
};
/**
* \addtogroup locates Locate Functions
* @{
* On The Usage Of 'locate' and 'locateLocal'
*
* Typical KDE applications use resource files in one out of
* three ways:
*
* 1) A resource file is read but is never written. A system
* default is supplied but the user can override this
* default in his local .kde directory:
*
* \code
* // Code example
* myFile = locate("appdata", "groups.lst");
* myData = myReadGroups(myFile); // myFile may be null
* \endcode
*
* 2) A resource file is read and written. If the user has no
* local version of the file the system default is used.
* The resource file is always written to the users local
* .kde directory.
*
* \code
* // Code example
* myFile = locate("appdata", "groups.lst")
* myData = myReadGroups(myFile);
* ...
* doSomething(myData);
* ...
* myFile = locateLocal("appdata", "groups.lst");
* myWriteGroups(myFile, myData);
* \endcode
*
* 3) A resource file is read and written. No system default
* is used if the user has no local version of the file.
* The resource file is always written to the users local
* .kde directory.
*
* \code
* // Code example
* myFile = locateLocal("appdata", "groups.lst");
* myData = myReadGroups(myFile);
* ...
* doSomething(myData);
* ...
* myFile = locateLocal("appdata", "groups.lst");
* myWriteGroups(myFile, myData);
* \endcode
**/
+
/*!
* \relates KStandardDirs
* This function is just for convenience. It simply calls
*instance->dirs()->\link KStandardDirs::findResource() findResource\endlink(type, filename).
**/
QString locate( const char *type, const QString& filename /*US , const KInstance* instance = KGlobal::instance()*/ );
/*!
* \relates KStandardDirs
* This function is much like locate. However it returns a
* filename suitable for writing to. No check is made if the
* specified filename actually exists. Missing directories
* are created. If filename is only a directory, without a
* specific file, filename must have a trailing slash.
*
**/
QString locateLocal( const char *type, const QString& filename /*US , const KInstance* instance = KGlobal::instance() */ );
/*!
* \relates KStandardDirs
* This function is much like locate. No check is made if the
* specified filename actually exists. Missing directories
* are created if @p createDir is true. If filename is only
* a directory, without a specific file,
* filename must have a trailing slash.
*
**/
QString locateLocal( const char *type, const QString& filename, bool createDir /*US , const KInstance* instance = KGlobal::instance() */);
+QString readEnvPath(const char *env);
+
+
/*! @} */
#endif // SSK_KSTDDIRS_H