summaryrefslogtreecommitdiffabout
authorzautrix <zautrix>2004-10-09 15:58:52 (UTC)
committer zautrix <zautrix>2004-10-09 15:58:52 (UTC)
commitb80a099d9432bdc3d4eea778b1813b82b2680ecf (patch) (side-by-side diff)
tree6327321f86070a13969b07e25b9cf84d4ad10d13
parented1eac5e36e675b030cb5a5aa90fb2d44eb40c73 (diff)
downloadkdepimpi-b80a099d9432bdc3d4eea778b1813b82b2680ecf.zip
kdepimpi-b80a099d9432bdc3d4eea778b1813b82b2680ecf.tar.gz
kdepimpi-b80a099d9432bdc3d4eea778b1813b82b2680ecf.tar.bz2
removed some debug output
Diffstat (more/less context) (ignore whitespace changes)
-rw-r--r--kabc/vcardformatplugin.cpp2
-rw-r--r--libkdepim/ksyncmanager.cpp24
-rw-r--r--microkde/kconfig.cpp4
-rw-r--r--microkde/kdecore/kstandarddirs.cpp2
-rw-r--r--microkde/kdeui/kactioncollection.cpp5
-rw-r--r--microkde/kdeui/klistview.cpp2
6 files changed, 18 insertions, 21 deletions
diff --git a/kabc/vcardformatplugin.cpp b/kabc/vcardformatplugin.cpp
index bc18690..8db8c11 100644
--- a/kabc/vcardformatplugin.cpp
+++ b/kabc/vcardformatplugin.cpp
@@ -1,70 +1,70 @@
/*
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.
*/
#include "vcardformatplugin.h"
#include "vcardformatimpl.h"
using namespace KABC;
VCardFormatPlugin::VCardFormatPlugin()
{
mImpl = new VCardFormatImpl;
}
VCardFormatPlugin::~VCardFormatPlugin()
{
delete mImpl;
}
bool VCardFormatPlugin::load( Addressee &addressee, QFile *file )
{
qDebug("VCardFormatPlugin::load");
return mImpl->load( addressee, file );
}
bool VCardFormatPlugin::loadAll( AddressBook *addressBook, Resource *resource, QFile *file )
{
- qDebug("VCardFormatPlugin::loadAll");
+ // qDebug("VCardFormatPlugin::loadAll");
return mImpl->loadAll( addressBook, resource, file );
}
void VCardFormatPlugin::save( const Addressee &addressee, QFile *file )
{
qDebug("VCardFormatPlugin::save");
mImpl->save( addressee, file );
}
void VCardFormatPlugin::saveAll( AddressBook *addressBook, Resource *resource, QFile *file )
{
qDebug("VCardFormatPlugin::saveAll");
mImpl->saveAll( addressBook, resource, file );
}
bool VCardFormatPlugin::checkFormat( QFile *file ) const
{
QString line;
file->readLine( line, 1024 );
line = line.stripWhiteSpace();
if ( line == "BEGIN:VCARD" )
return true;
else
return false;
}
diff --git a/libkdepim/ksyncmanager.cpp b/libkdepim/ksyncmanager.cpp
index 80fb147..df53235 100644
--- a/libkdepim/ksyncmanager.cpp
+++ b/libkdepim/ksyncmanager.cpp
@@ -1,1214 +1,1210 @@
/*
This file is part of KDE-Pim/Pi.
Copyright (c) 2004 Ulf Schenk
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.
*/
// $Id$
#include "ksyncmanager.h"
#include <stdlib.h>
#ifndef _WIN32_
#include <unistd.h>
#endif
#include "ksyncprofile.h"
#include "ksyncprefsdialog.h"
#include "kpimprefs.h"
#include <kmessagebox.h>
#include <qdir.h>
#include <qprogressbar.h>
#include <qpopupmenu.h>
#include <qpushbutton.h>
#include <qradiobutton.h>
#include <qbuttongroup.h>
#include <qtimer.h>
#include <qmessagebox.h>
#include <qapplication.h>
#include <qlineedit.h>
#include <qdialog.h>
#include <qlayout.h>
#include <qtextcodec.h>
#include <qlabel.h>
#include <klocale.h>
#include <kglobal.h>
#include <kconfig.h>
#include <kfiledialog.h>
KSyncManager::KSyncManager(QWidget* parent, KSyncInterface* implementation, TargetApp ta, KPimPrefs* prefs, QPopupMenu* syncmenu)
: QObject(), mParent(parent), mImplementation(implementation), mTargetApp(ta), mPrefs(prefs ),mSyncMenu(syncmenu)
{
mServerSocket = 0;
bar = new QProgressBar ( 1, 0 );
bar->setCaption ("");
int w = 300;
if ( QApplication::desktop()->width() < 320 )
w = 220;
int h = bar->sizeHint().height() ;
int dw = QApplication::desktop()->width();
int dh = QApplication::desktop()->height();
bar->setGeometry( (dw-w)/2, (dh - h )/2 ,w,h );
}
KSyncManager::~KSyncManager()
{
delete bar;
}
void KSyncManager::fillSyncMenu()
{
if ( mSyncMenu->count() )
mSyncMenu->clear();
mSyncMenu->insertItem( i18n("Configure..."), 0 );
mSyncMenu->insertSeparator();
if ( mServerSocket == 0 ) {
mSyncMenu->insertItem( i18n("Enable Pi-Sync"), 2 );
} else {
mSyncMenu->insertItem( i18n("Disable Pi-Sync"), 3 );
}
mSyncMenu->insertSeparator();
mSyncMenu->insertItem( i18n("Multiple sync"), 1 );
mSyncMenu->insertSeparator();
KConfig config ( locateLocal( "config","ksyncprofilesrc" ) );
config.setGroup("General");
QStringList prof = config.readListEntry("SyncProfileNames");
mLocalMachineName = config.readEntry("LocalMachineName","undefined");
if ( prof.count() < 2 ) {
prof.clear();
prof << i18n("Sharp_DTM");
prof << i18n("Local_file");
prof << i18n("Last_file");
KSyncProfile* temp = new KSyncProfile ();
temp->setName( prof[0] );
temp->writeConfig(&config);
temp->setName( prof[1] );
temp->writeConfig(&config);
temp->setName( prof[2] );
temp->writeConfig(&config);
config.setGroup("General");
config.writeEntry("SyncProfileNames",prof);
config.writeEntry("ExternSyncProfiles","Sharp_DTM");
config.sync();
delete temp;
}
mExternSyncProfiles = config.readListEntry("ExternSyncProfiles");
mSyncProfileNames = prof;
unsigned int i;
for ( i = 0; i < prof.count(); ++i ) {
mSyncMenu->insertItem( prof[i], 1000+i );
if ( i == 2 )
mSyncMenu->insertSeparator();
}
QDir app_dir;
//US do not display SharpDTM if app is pwmpi, or no sharpfiles available
if ( mTargetApp == PWMPI) {
mSyncMenu->removeItem( 1000 );
}
else if (!app_dir.exists(QDir::homeDirPath()+"/Applications/dtm" ) ) {
mSyncMenu->removeItem( 1000 );
}
mSyncMenu->removeItem( 1002 );
}
void KSyncManager::slotSyncMenu( int action )
{
//qDebug("syncaction %d ", action);
if ( action == 0 ) {
// seems to be a Qt2 event handling bug
// syncmenu.clear causes a segfault at first time
// when we call it after the main event loop, it is ok
// same behaviour when calling OM/Pi via QCOP for the first time
QTimer::singleShot ( 1, this, SLOT ( confSync() ) );
//confSync();
return;
}
if ( action == 1 ) {
multiSync( true );
return;
}
if ( action == 2 ) {
enableQuick();
QTimer::singleShot ( 1, this, SLOT ( fillSyncMenu() ) );
return;
}
if ( action == 3 ) {
delete mServerSocket;
mServerSocket = 0;
QTimer::singleShot ( 1, this, SLOT ( fillSyncMenu() ) );
return;
}
if (blockSave())
return;
setBlockSave(true);
mCurrentSyncProfile = action - 1000 ;
mCurrentSyncDevice = mSyncProfileNames[mCurrentSyncProfile] ;
mCurrentSyncName = mLocalMachineName ;
KConfig config ( locateLocal( "config","ksyncprofilesrc" ) );
KSyncProfile* temp = new KSyncProfile ();
temp->setName(mSyncProfileNames[mCurrentSyncProfile]);
temp->readConfig(&config);
mAskForPreferences = temp->getAskForPreferences();
mSyncAlgoPrefs = temp->getSyncPrefs();
mWriteBackFile = temp->getWriteBackFile();
mWriteBackExistingOnly = temp->getWriteBackExisting();
mWriteBackInFuture = 0;
if ( temp->getWriteBackFuture() )
mWriteBackInFuture = temp->getWriteBackFutureWeeks( );
mShowSyncSummary = temp->getShowSummaryAfterSync();
if ( action == 1000 ) {
syncSharp();
} else if ( action == 1001 ) {
syncLocalFile();
} else if ( action == 1002 ) {
mWriteBackFile = false;
mAskForPreferences = false;
mShowSyncSummary = false;
mSyncAlgoPrefs = 3;
quickSyncLocalFile();
} else if ( action >= 1003 ) {
if ( temp->getIsLocalFileSync() ) {
switch(mTargetApp)
{
case (KAPI):
if ( syncWithFile( temp->getRemoteFileNameAB( ), false ) )
mPrefs->mLastSyncedLocalFile = temp->getRemoteFileNameAB();
break;
case (KOPI):
if ( syncWithFile( temp->getRemoteFileName( ), false ) )
mPrefs->mLastSyncedLocalFile = temp->getRemoteFileName();
break;
case (PWMPI):
if ( syncWithFile( temp->getRemoteFileNamePWM( ), false ) )
mPrefs->mLastSyncedLocalFile = temp->getRemoteFileNamePWM();
break;
default:
qDebug("KSyncManager::slotSyncMenu: invalid apptype selected");
break;
}
} else {
if ( temp->getIsPhoneSync() ) {
mPhoneDevice = temp->getPhoneDevice( ) ;
mPhoneConnection = temp->getPhoneConnection( );
mPhoneModel = temp->getPhoneModel( );
syncPhone();
} else if ( temp->getIsPiSync() ) {
if ( mTargetApp == KAPI ) {
mPassWordPiSync = temp->getRemotePwAB();
mActiveSyncPort = temp->getRemotePortAB();
mActiveSyncIP = temp->getRemoteIPAB();
} else if ( mTargetApp == KOPI ) {
mPassWordPiSync = temp->getRemotePw();
mActiveSyncPort = temp->getRemotePort();
mActiveSyncIP = temp->getRemoteIP();
} else {
mPassWordPiSync = temp->getRemotePwPWM();
mActiveSyncPort = temp->getRemotePortPWM();
mActiveSyncIP = temp->getRemoteIPPWM();
}
syncPi();
} else
syncRemote( temp );
}
}
delete temp;
setBlockSave(false);
}
void KSyncManager::enableQuick()
{
QDialog dia ( 0, "input-dialog", true );
QLineEdit lab ( &dia );
QVBoxLayout lay( &dia );
lab.setText( mPrefs->mPassiveSyncPort );
lay.setMargin(7);
lay.setSpacing(7);
int po = 9197+mTargetApp;
QLabel label ( i18n("Port number (Default: %1)").arg(po), &dia );
lay.addWidget( &label);
lay.addWidget( &lab);
QLineEdit lepw ( &dia );
lepw.setText( mPrefs->mPassiveSyncPw );
QLabel label2 ( i18n("Password to enable\naccess from remote:"), &dia );
lay.addWidget( &label2);
lay.addWidget( &lepw);
dia.setFixedSize( 230,80 );
dia.setCaption( i18n("Enter port for Pi-Sync") );
QPushButton pb ( "OK", &dia);
lay.addWidget( &pb );
connect(&pb, SIGNAL( clicked() ), &dia, SLOT ( accept() ) );
dia.show();
if ( ! dia.exec() )
return;
dia.hide();
qApp->processEvents();
mPrefs->mPassiveSyncPw = lepw.text();
mPrefs->mPassiveSyncPort = lab.text();
bool ok;
Q_UINT16 port = mPrefs->mPassiveSyncPort.toUInt(&ok);
if ( ! ok ) {
KMessageBox::information( 0, i18n("No valid port"));
return;
}
//qDebug("port %d ", port);
mServerSocket = new KServerSocket ( mPrefs->mPassiveSyncPw, port ,1 );
mServerSocket->setFileName( defaultFileName() );
//qDebug("connected ");
if ( !mServerSocket->ok() ) {
KMessageBox::information( 0, i18n("Failed to bind or\nlisten to the port!"));
delete mServerSocket;
mServerSocket = 0;
return;
}
connect( mServerSocket, SIGNAL ( request_file() ),this, SIGNAL ( request_file() ) );
connect( mServerSocket, SIGNAL ( file_received( bool ) ), this, SIGNAL ( getFile( bool ) ) );
}
void KSyncManager::syncLocalFile()
{
QString fn =mPrefs->mLastSyncedLocalFile;
QString ext;
switch(mTargetApp)
{
case (KAPI):
ext = "(*.vcf)";
break;
case (KOPI):
ext = "(*.ics/*.vcs)";
break;
case (PWMPI):
ext = "(*.pwm)";
break;
default:
qDebug("KSyncManager::syncLocalFile: invalid apptype selected");
break;
}
fn =KFileDialog:: getOpenFileName( fn, i18n("Sync filename"+ext), mParent );
if ( fn == "" )
return;
if ( syncWithFile( fn, false ) ) {
qDebug("syncLocalFile() successful ");
}
}
bool KSyncManager::syncWithFile( QString fn , bool quick )
{
bool ret = false;
QFileInfo info;
info.setFile( fn );
QString mess;
bool loadbup = true;
if ( !info. exists() ) {
mess = i18n( "Sync file \n...%1\ndoes not exist!\nNothing synced!\n").arg(fn.right( 30) );
int result = QMessageBox::warning( mParent, i18n("Warning!"),
mess );
return ret;
}
int result = 0;
if ( !quick ) {
mess = i18n("Sync with file \n...%1\nfrom:\n%2\n").arg(fn.right( 25)).arg(KGlobal::locale()->formatDateTime(info.lastModified (), true, false ));
result = QMessageBox::warning( mParent, i18n("Warning!"),
mess,
i18n("Sync"), i18n("Cancel"), 0,
0, 1 );
if ( result )
return false;
}
if ( mAskForPreferences )
edit_sync_options();
if ( result == 0 ) {
//qDebug("Now sycing ... ");
if ( ret = mImplementation->sync( this, fn, mSyncAlgoPrefs ) )
mParent->topLevelWidget()->setCaption( i18n("Synchronization successful") );
else
mParent->topLevelWidget()->setCaption( i18n("Sync cancelled or failed. Nothing synced.") );
if ( ! quick )
mPrefs->mLastSyncedLocalFile = fn;
}
return ret;
}
void KSyncManager::quickSyncLocalFile()
{
if ( syncWithFile( mPrefs->mLastSyncedLocalFile, true ) ) {
qDebug("quick syncLocalFile() successful ");
}
}
void KSyncManager::multiSync( bool askforPrefs )
{
if (blockSave())
return;
setBlockSave(true);
QString question = i18n("Do you really want\nto multiple sync\nwith all checked profiles?\nSyncing takes some\ntime - all profiles\nare synced twice!");
if ( QMessageBox::information( mParent, i18n("KDE-Pim Sync"),
question,
i18n("Yes"), i18n("No"),
0, 0 ) != 0 ) {
setBlockSave(false);
mParent->topLevelWidget()->setCaption(i18n("Aborted! Nothing synced!"));
return;
}
mCurrentSyncDevice = i18n("Multiple profiles") ;
mSyncAlgoPrefs = mPrefs->mRingSyncAlgoPrefs;
if ( askforPrefs ) {
edit_sync_options();
mPrefs->mRingSyncAlgoPrefs = mSyncAlgoPrefs;
}
mParent->topLevelWidget()->setCaption(i18n("Multiple sync started.") );
qApp->processEvents();
int num = ringSync() ;
if ( num > 1 )
ringSync();
setBlockSave(false);
if ( num )
emit save();
if ( num )
mParent->topLevelWidget()->setCaption(i18n("%1 profiles synced. Multiple sync complete!").arg(num) );
else
mParent->topLevelWidget()->setCaption(i18n("Nothing synced! No profiles defined for multisync!"));
return;
}
int KSyncManager::ringSync()
{
int syncedProfiles = 0;
unsigned int i;
QTime timer;
KConfig config ( locateLocal( "config","ksyncprofilesrc" ) );
QStringList syncProfileNames = mSyncProfileNames;
KSyncProfile* temp = new KSyncProfile ();
mAskForPreferences = false;
for ( i = 0; i < syncProfileNames.count(); ++i ) {
mCurrentSyncProfile = i;
temp->setName(syncProfileNames[mCurrentSyncProfile]);
temp->readConfig(&config);
bool includeInRingSync;
switch(mTargetApp)
{
case (KAPI):
includeInRingSync = temp->getIncludeInRingSyncAB();
break;
case (KOPI):
includeInRingSync = temp->getIncludeInRingSync();
break;
case (PWMPI):
includeInRingSync = temp->getIncludeInRingSyncPWM();
break;
default:
qDebug("KSyncManager::ringSync: invalid apptype selected");
break;
}
if ( includeInRingSync && ( i < 1 || i > 2 )) {
mParent->topLevelWidget()->setCaption(i18n("Profile ")+syncProfileNames[mCurrentSyncProfile]+ i18n(" is synced ... "));
++syncedProfiles;
// mAskForPreferences = temp->getAskForPreferences();
mWriteBackFile = temp->getWriteBackFile();
mWriteBackExistingOnly = temp->getWriteBackExisting();
mWriteBackInFuture = 0;
if ( temp->getWriteBackFuture() )
mWriteBackInFuture = temp->getWriteBackFutureWeeks( );
mShowSyncSummary = false;
mCurrentSyncDevice = syncProfileNames[i] ;
mCurrentSyncName = mLocalMachineName;
if ( i == 0 ) {
syncSharp();
} else {
if ( temp->getIsLocalFileSync() ) {
switch(mTargetApp)
{
case (KAPI):
if ( syncWithFile( temp->getRemoteFileNameAB( ), false ) )
mPrefs->mLastSyncedLocalFile = temp->getRemoteFileNameAB();
break;
case (KOPI):
if ( syncWithFile( temp->getRemoteFileName( ), false ) )
mPrefs->mLastSyncedLocalFile = temp->getRemoteFileName();
break;
case (PWMPI):
if ( syncWithFile( temp->getRemoteFileNamePWM( ), false ) )
mPrefs->mLastSyncedLocalFile = temp->getRemoteFileNamePWM();
break;
default:
qDebug("KSyncManager::slotSyncMenu: invalid apptype selected");
break;
}
} else {
if ( temp->getIsPhoneSync() ) {
mPhoneDevice = temp->getPhoneDevice( ) ;
mPhoneConnection = temp->getPhoneConnection( );
mPhoneModel = temp->getPhoneModel( );
syncPhone();
} else if ( temp->getIsPiSync() ) {
if ( mTargetApp == KAPI ) {
mPassWordPiSync = temp->getRemotePwAB();
mActiveSyncPort = temp->getRemotePortAB();
mActiveSyncIP = temp->getRemoteIPAB();
} else if ( mTargetApp == KOPI ) {
mPassWordPiSync = temp->getRemotePw();
mActiveSyncPort = temp->getRemotePort();
mActiveSyncIP = temp->getRemoteIP();
} else {
mPassWordPiSync = temp->getRemotePwPWM();
mActiveSyncPort = temp->getRemotePortPWM();
mActiveSyncIP = temp->getRemoteIPPWM();
}
syncPi();
} else
syncRemote( temp, false );
}
}
timer.start();
mParent->topLevelWidget()->setCaption(i18n("Multiple sync in progress ... please wait!") );
while ( timer.elapsed () < 2000 ) {
qApp->processEvents();
#ifndef _WIN32_
sleep (1);
#endif
}
}
}
delete temp;
return syncedProfiles;
}
void KSyncManager::syncRemote( KSyncProfile* prof, bool ask)
{
QString question;
if ( ask ) {
question = i18n("Do you really want\nto remote sync\nwith profile \n")+ prof->getName()+" ?\n";
if ( QMessageBox::information( mParent, i18n("Sync"),
question,
i18n("Yes"), i18n("No"),
0, 0 ) != 0 )
return;
}
QString preCommand;
QString localTempFile;
QString postCommand;
switch(mTargetApp)
{
case (KAPI):
preCommand = prof->getPreSyncCommandAB();
postCommand = prof->getPostSyncCommandAB();
localTempFile = prof->getLocalTempFileAB();
break;
case (KOPI):
preCommand = prof->getPreSyncCommand();
postCommand = prof->getPostSyncCommand();
localTempFile = prof->getLocalTempFile();
break;
case (PWMPI):
preCommand = prof->getPreSyncCommandPWM();
postCommand = prof->getPostSyncCommandPWM();
localTempFile = prof->getLocalTempFilePWM();
break;
default:
qDebug("KSyncManager::syncRemote: invalid apptype selected");
break;
}
int fi;
if ( (fi = preCommand.find("$PWD$")) > 0 ) {
QString pwd = getPassword();
preCommand = preCommand.left( fi )+ pwd + preCommand.mid( fi+5 );
}
int maxlen = 30;
if ( QApplication::desktop()->width() > 320 )
maxlen += 25;
mParent->topLevelWidget()->setCaption ( i18n( "Copy remote file to local machine..." ) );
int fileSize = 0;
int result = system ( preCommand );
// 0 : okay
// 256: no such file or dir
//
- qDebug("KO: Remote copy result(0 = okay): %d ",result );
+ qDebug("Sync: Remote copy result(0 = okay): %d ",result );
if ( result != 0 ) {
unsigned int len = maxlen;
while ( len < preCommand.length() ) {
preCommand.insert( len , "\n" );
len += maxlen +2;
}
question = i18n("Sorry, the copy command failed!\nCommand was:\n%1\n \nTry command on console to get more\ndetailed info about the reason.\n").arg (preCommand) ;
QMessageBox::information( mParent, i18n("Sync - ERROR"),
question,
i18n("Okay!")) ;
mParent->topLevelWidget()->setCaption ("KDE-Pim");
return;
}
mParent->topLevelWidget()->setCaption ( i18n( "Copying succeed." ) );
//qDebug(" file **%s** ",prof->getLocalTempFile().latin1() );
if ( syncWithFile( localTempFile, true ) ) {
if ( mWriteBackFile ) {
int fi;
if ( (fi = postCommand.find("$PWD$")) > 0 ) {
QString pwd = getPassword();
postCommand = postCommand.left( fi )+ pwd + postCommand.mid( fi+5 );
}
mParent->topLevelWidget()->setCaption ( i18n( "Writing back file ..." ) );
result = system ( postCommand );
- qDebug("Writing back file result: %d ", result);
+ qDebug("Sync:Writing back file result: %d ", result);
if ( result != 0 ) {
mParent->topLevelWidget()->setCaption ( i18n( "Writing back file result: " )+QString::number( result ) );
return;
} else {
mParent->topLevelWidget()->setCaption ( i18n( "Syncronization sucessfully completed" ) );
}
}
}
return;
}
void KSyncManager::edit_pisync_options()
{
QDialog dia( mParent, "dia", true );
dia.setCaption( i18n("Pi-Sync options for device: " ) +mCurrentSyncDevice );
QVBoxLayout lay ( &dia );
lay.setSpacing( 5 );
lay.setMargin( 3 );
QLabel lab1 ( i18n("Password for remote access:"), &dia);
lay.addWidget( &lab1 );
QLineEdit le1 (&dia );
lay.addWidget( &le1 );
QLabel lab2 ( i18n("Remote IP address:"), &dia);
lay.addWidget( &lab2 );
QLineEdit le2 (&dia );
lay.addWidget( &le2 );
QLabel lab3 ( i18n("Remote port number:"), &dia);
lay.addWidget( &lab3 );
QLineEdit le3 (&dia );
lay.addWidget( &le3 );
QPushButton pb ( "OK", &dia);
lay.addWidget( &pb );
connect(&pb, SIGNAL( clicked() ), &dia, SLOT ( accept() ) );
le1.setText( mPassWordPiSync );
le2.setText( mActiveSyncIP );
le3.setText( mActiveSyncPort );
if ( dia.exec() ) {
mPassWordPiSync = le1.text();
mActiveSyncPort = le3.text();
mActiveSyncIP = le2.text();
}
}
void KSyncManager::edit_sync_options()
{
QDialog dia( mParent, "dia", true );
dia.setCaption( i18n("Device: " ) +mCurrentSyncDevice );
QButtonGroup gr ( 1, Qt::Horizontal, i18n("Sync preferences"), &dia);
QVBoxLayout lay ( &dia );
lay.setSpacing( 2 );
lay.setMargin( 3 );
lay.addWidget(&gr);
QRadioButton loc ( i18n("Take local entry on conflict"), &gr );
QRadioButton rem ( i18n("Take remote entry on conflict"), &gr );
QRadioButton newest( i18n("Take newest entry on conflict"), &gr );
QRadioButton ask( i18n("Ask for every entry on conflict"), &gr );
QRadioButton f_loc( i18n("Force: Take local entry always"), &gr );
QRadioButton f_rem( i18n("Force: Take remote entry always"), &gr );
//QRadioButton both( i18n("Take both on conflict"), &gr );
QPushButton pb ( "OK", &dia);
lay.addWidget( &pb );
connect(&pb, SIGNAL( clicked() ), &dia, SLOT ( accept() ) );
switch ( mSyncAlgoPrefs ) {
case 0:
loc.setChecked( true);
break;
case 1:
rem.setChecked( true );
break;
case 2:
newest.setChecked( true);
break;
case 3:
ask.setChecked( true);
break;
case 4:
f_loc.setChecked( true);
break;
case 5:
f_rem.setChecked( true);
break;
case 6:
// both.setChecked( true);
break;
default:
break;
}
if ( dia.exec() ) {
mSyncAlgoPrefs = rem.isChecked()*1+newest.isChecked()*2+ ask.isChecked()*3+ f_loc.isChecked()*4+ f_rem.isChecked()*5;//+ both.isChecked()*6 ;
}
}
QString KSyncManager::getPassword( )
{
QString retfile = "";
QDialog dia ( mParent, "input-dialog", true );
QLineEdit lab ( &dia );
lab.setEchoMode( QLineEdit::Password );
QVBoxLayout lay( &dia );
lay.setMargin(7);
lay.setSpacing(7);
lay.addWidget( &lab);
dia.setFixedSize( 230,50 );
dia.setCaption( i18n("Enter password") );
QPushButton pb ( "OK", &dia);
lay.addWidget( &pb );
connect(&pb, SIGNAL( clicked() ), &dia, SLOT ( accept() ) );
dia.show();
int res = dia.exec();
if ( res )
retfile = lab.text();
dia.hide();
qApp->processEvents();
return retfile;
}
void KSyncManager::confSync()
{
static KSyncPrefsDialog* sp = 0;
if ( ! sp ) {
sp = new KSyncPrefsDialog( mParent, "syncprefs", true );
}
sp->usrReadConfig();
#ifndef DESKTOP_VERSION
sp->showMaximized();
#else
sp->show();
#endif
sp->exec();
mSyncProfileNames = sp->getSyncProfileNames();
mLocalMachineName = sp->getLocalMachineName ();
QTimer::singleShot ( 1, this, SLOT ( fillSyncMenu() ) );
}
void KSyncManager::syncSharp()
{
if ( ! syncExternalApplication("sharp") )
- qDebug("ERROR sync sharp ");;
+ qDebug("ERROR sync sharp ");
}
bool KSyncManager::syncExternalApplication(QString resource)
{
emit save();
if ( mAskForPreferences )
edit_sync_options();
- qDebug("sync %s", resource.latin1());
+ qDebug("Sync extern %s", resource.latin1());
bool syncOK = mImplementation->syncExternal(this, resource);
return syncOK;
}
void KSyncManager::syncPhone()
{
syncExternalApplication("phone");
}
void KSyncManager::showProgressBar(int percentage, QString caption, int total)
{
if (!bar->isVisible())
{
bar->setCaption (caption);
bar->setTotalSteps ( total ) ;
bar->show();
}
bar->setProgress( percentage );
}
void KSyncManager::hideProgressBar()
{
bar->hide();
}
bool KSyncManager::isProgressBarCanceled()
{
return !bar->isVisible();
}
QString KSyncManager::syncFileName()
{
QString fn = "tempfile";
switch(mTargetApp)
{
case (KAPI):
fn = "tempsyncab.vcf";
break;
case (KOPI):
fn = "tempsynccal.ics";
break;
case (PWMPI):
fn = "tempsyncpw.pwm";
break;
default:
break;
}
#ifdef _WIN32_
return locateLocal( "tmp", fn );
#else
return (QString( "/tmp/" )+ fn );
#endif
}
void KSyncManager::syncPi()
{
qApp->processEvents();
if ( mAskForPreferences )
edit_pisync_options();
bool ok;
Q_UINT16 port = mActiveSyncPort.toUInt(&ok);
if ( ! ok ) {
mParent->topLevelWidget()->setCaption( i18n("Sorry, no valid port.Syncing cancelled.") );
return;
}
KCommandSocket* commandSocket = new KCommandSocket( mPassWordPiSync, port, mActiveSyncIP, this );
connect( commandSocket, SIGNAL(commandFinished( KCommandSocket*, int )), this, SLOT(deleteCommandSocket(KCommandSocket*, int)) );
mParent->topLevelWidget()->setCaption( i18n("Sending request for remote file ...") );
commandSocket->readFile( syncFileName() );
}
void KSyncManager::deleteCommandSocket(KCommandSocket*s, int state)
{
- qDebug("MainWindow::deleteCommandSocket %d", state);
-
//enum { success, errorW, errorR, quiet };
if ( state == KCommandSocket::errorR ||state == KCommandSocket::errorTO ) {
mParent->topLevelWidget()->setCaption( i18n("ERROR: Receiving remote file failed.") );
delete s;
if ( state == KCommandSocket::errorR ) {
KCommandSocket* commandSocket = new KCommandSocket( mPassWordPiSync, mActiveSyncPort.toUInt(), mActiveSyncIP, this );
connect( commandSocket, SIGNAL(commandFinished( KCommandSocket*, int)), this, SLOT(deleteCommandSocket(KCommandSocket*, int )) );
commandSocket->sendStop();
}
return;
} else if ( state == KCommandSocket::errorW ) {
mParent->topLevelWidget()->setCaption( i18n("ERROR:Writing back file failed.") );
} else if ( state == KCommandSocket::successR ) {
QTimer::singleShot( 1, this , SLOT ( readFileFromSocket()));
} else if ( state == KCommandSocket::successW ) {
mParent->topLevelWidget()->setCaption( i18n("Pi-Sync succesful!") );
}
delete s;
}
void KSyncManager::readFileFromSocket()
{
QString fileName = syncFileName();
mParent->topLevelWidget()->setCaption( i18n("Remote file saved to temp file.") );
if ( ! syncWithFile( fileName , true ) ) {
mParent->topLevelWidget()->setCaption( i18n("Syncing failed.") );
- qDebug("Syncing failed ");
return;
}
KCommandSocket* commandSocket = new KCommandSocket( mPassWordPiSync, mActiveSyncPort.toUInt(), mActiveSyncIP, this );
connect( commandSocket, SIGNAL(commandFinished( KCommandSocket*, int)), this, SLOT(deleteCommandSocket(KCommandSocket*, int )) );
if ( mWriteBackFile )
commandSocket->writeFile( fileName );
else {
commandSocket->sendStop();
mParent->topLevelWidget()->setCaption( i18n("Pi-Sync succesful!") );
}
}
KServerSocket:: KServerSocket ( QString pw, Q_UINT16 port, int backlog, QObject * parent, const char * name ) : QServerSocket( port, backlog, parent, name )
{
mPassWord = pw;
mSocket = 0;
mSyncActionDialog = 0;
blockRC = false;
};
void KServerSocket::newConnection ( int socket )
{
// qDebug("KServerSocket:New connection %d ", socket);
if ( mSocket ) {
qDebug("KServerSocket::newConnection Socket deleted! ");
delete mSocket;
mSocket = 0;
}
mSocket = new QSocket( this );
connect( mSocket , SIGNAL(readyRead()), this, SLOT(readClient()) );
connect( mSocket , SIGNAL(delayedCloseFinished()), this, SLOT(discardClient()) );
mSocket->setSocket( socket );
}
void KServerSocket::discardClient()
{
//qDebug(" KServerSocket::discardClient()");
if ( mSocket ) {
delete mSocket;
mSocket = 0;
}
//emit endConnect();
}
void KServerSocket::readClient()
{
if ( blockRC )
return;
if ( mSocket == 0 ) {
qDebug("ERROR::KServerSocket::readClient(): mSocket == 0 ");
return;
}
- qDebug("KServerSocket readClient()");
+ //qDebug("KServerSocket::readClient()");
if ( mSocket->canReadLine() ) {
QString line = mSocket->readLine();
- qDebug("KServerSocket readline: %s ", line.latin1());
+ //qDebug("KServerSocket readline: %s ", line.latin1());
QStringList tokens = QStringList::split( QRegExp("[ \r\n][ \r\n]*"), line );
if ( tokens[0] == "GET" ) {
if ( tokens[1] == mPassWord )
//emit sendFile( mSocket );
send_file();
else {
KMessageBox::error( 0, i18n("Got send file request\nwith invalid password"));
- qDebug("password %s, invalid password %s ",mPassWord.latin1(), tokens[1].latin1() );
+ //qDebug("password %s, invalid password %s ",mPassWord.latin1(), tokens[1].latin1() );
}
}
if ( tokens[0] == "PUT" ) {
if ( tokens[1] == mPassWord ) {
//emit getFile( mSocket );
blockRC = true;
get_file();
}
else {
KMessageBox::error( 0, i18n("Got receive file request\nwith invalid password"));
- qDebug("password %s, invalid password %s ",mPassWord.latin1(), tokens[1].latin1() );
+ //qDebug("password %s, invalid password %s ",mPassWord.latin1(), tokens[1].latin1() );
}
}
if ( tokens[0] == "STOP" ) {
//emit endConnect();
end_connect();
}
}
}
void KServerSocket::end_connect()
{
delete mSyncActionDialog;
mSyncActionDialog = 0;
}
void KServerSocket::send_file()
{
//qDebug("MainWindow::sendFile(QSocket* s) ");
if ( mSyncActionDialog )
delete mSyncActionDialog;
mSyncActionDialog = new QDialog ( 0, "input-dialog", true );
mSyncActionDialog->setCaption(i18n("Received sync request"));
QLabel* label = new QLabel( i18n("Synchronizing from remote ...\n\nDo not use this application!\n\nIf syncing fails\nyou can close this dialog."), mSyncActionDialog );
QVBoxLayout* lay = new QVBoxLayout( mSyncActionDialog );
lay->addWidget( label);
lay->setMargin(7);
lay->setSpacing(7);
mSyncActionDialog->setFixedSize( 230, 120);
mSyncActionDialog->show();
mSyncActionDialog->raise();
- qDebug("KSS::saving ... ");
emit request_file();
qApp->processEvents();
QString fileName = mFileName;
QFile file( fileName );
if (!file.open( IO_ReadOnly ) ) {
delete mSyncActionDialog;
mSyncActionDialog = 0;
qDebug("KSS::error open file ");
mSocket->close();
if ( mSocket->state() == QSocket::Idle )
QTimer::singleShot( 10, this , SLOT ( discardClient()));
return ;
}
mSyncActionDialog->setCaption( i18n("Sending file...") );
QTextStream ts( &file );
ts.setEncoding( QTextStream::Latin1 );
QTextStream os( mSocket );
os.setEncoding( QTextStream::Latin1 );
while ( ! ts.atEnd() ) {
os << ts.readLine() << "\n";
}
//os << ts.read();
file.close();
mSyncActionDialog->setCaption( i18n("Waiting for synced file...") );
mSocket->close();
if ( mSocket->state() == QSocket::Idle )
QTimer::singleShot( 10, this , SLOT ( discardClient()));
}
void KServerSocket::get_file()
{
mSyncActionDialog->setCaption( i18n("Receiving synced file...") );
piTime.start();
piFileString = "";
QTimer::singleShot( 1, this , SLOT (readBackFileFromSocket( ) ));
}
void KServerSocket::readBackFileFromSocket()
{
//qDebug("readBackFileFromSocket() %d ", piTime.elapsed ());
while ( mSocket->canReadLine () ) {
piTime.restart();
QString line = mSocket->readLine ();
piFileString += line;
//qDebug("readline: %s ", line.latin1());
mSyncActionDialog->setCaption( i18n("Received %1 bytes").arg( piFileString.length() ) );
}
if ( piTime.elapsed () < 3000 ) {
// wait for more
//qDebug("waitformore ");
QTimer::singleShot( 100, this , SLOT (readBackFileFromSocket( ) ));
return;
}
QString fileName = mFileName;
QFile file ( fileName );
if (!file.open( IO_WriteOnly ) ) {
delete mSyncActionDialog;
mSyncActionDialog = 0;
- qDebug("error open cal file ");
+ qDebug("KSS:Error open read back file ");
piFileString = "";
emit file_received( false );
blockRC = false;
return ;
}
// mView->setLoadedFileVersion(QDateTime::currentDateTime().addSecs( -1));
QTextStream ts ( &file );
ts.setEncoding( QTextStream::Latin1 );
mSyncActionDialog->setCaption( i18n("Writing file to disk...") );
ts << piFileString;
mSocket->close();
if ( mSocket->state() == QSocket::Idle )
QTimer::singleShot( 10, this , SLOT ( discardClient()));
file.close();
delete mSyncActionDialog;
mSyncActionDialog = 0;
piFileString = "";
blockRC = false;
emit file_received( true );
}
KCommandSocket::KCommandSocket ( QString password, Q_UINT16 port, QString host, QObject * parent, const char * name ): QObject( parent, name )
{
mPassWord = password;
mSocket = 0;
mPort = port;
mHost = host;
mRetVal = quiet;
mTimerSocket = new QTimer ( this );
connect( mTimerSocket, SIGNAL ( timeout () ), this, SLOT ( deleteSocket() ) );
}
void KCommandSocket::readFile( QString fn )
{
if ( !mSocket ) {
mSocket = new QSocket( this );
connect( mSocket, SIGNAL(readyRead()), this, SLOT(startReadFileFromSocket()) );
connect( mSocket, SIGNAL(delayedCloseFinished ()), this, SLOT(deleteSocket()) );
}
mFileString = "";
mFileName = fn;
mFirst = true;
mSocket->connectToHost( mHost, mPort );
QTextStream os( mSocket );
os.setEncoding( QTextStream::Latin1 );
os << "GET " << mPassWord << "\r\n";
mTimerSocket->start( 10000 );
}
void KCommandSocket::writeFile( QString fileName )
{
if ( !mSocket ) {
mSocket = new QSocket( this );
connect( mSocket, SIGNAL(delayedCloseFinished ()), this, SLOT(deleteSocket()) );
connect( mSocket, SIGNAL(connected ()), this, SLOT(writeFileToSocket()) );
}
mFileName = fileName ;
mSocket->connectToHost( mHost, mPort );
}
void KCommandSocket::writeFileToSocket()
{
QFile file2( mFileName );
if (!file2.open( IO_ReadOnly ) ) {
mRetVal= errorW;
mSocket->close();
if ( mSocket->state() == QSocket::Idle )
QTimer::singleShot( 10, this , SLOT ( deleteSocket()));
return ;
}
QTextStream ts2( &file2 );
ts2.setEncoding( QTextStream::Latin1 );
QTextStream os2( mSocket );
os2.setEncoding( QTextStream::Latin1 );
os2 << "PUT " << mPassWord << "\r\n";;
while ( ! ts2.atEnd() ) {
os2 << ts2.readLine() << "\n";
}
mRetVal= successW;
file2.close();
mSocket->close();
if ( mSocket->state() == QSocket::Idle )
QTimer::singleShot( 10, this , SLOT ( deleteSocket()));
}
void KCommandSocket::sendStop()
{
if ( !mSocket ) {
mSocket = new QSocket( this );
connect( mSocket, SIGNAL(delayedCloseFinished ()), this, SLOT(deleteSocket()) );
}
mSocket->connectToHost( mHost, mPort );
QTextStream os2( mSocket );
os2.setEncoding( QTextStream::Latin1 );
os2 << "STOP\r\n";
mSocket->close();
if ( mSocket->state() == QSocket::Idle )
QTimer::singleShot( 10, this , SLOT ( deleteSocket()));
}
void KCommandSocket::startReadFileFromSocket()
{
if ( ! mFirst )
return;
mFirst = false;
mTimerSocket->stop();
mFileString = "";
mTime.start();
QTimer::singleShot( 1, this , SLOT (readFileFromSocket( ) ));
}
void KCommandSocket::readFileFromSocket()
{
//qDebug("readBackFileFromSocket() %d ", mTime.elapsed ());
while ( mSocket->canReadLine () ) {
mTime.restart();
QString line = mSocket->readLine ();
mFileString += line;
//qDebug("readline: %s ", line.latin1());
}
if ( mTime.elapsed () < 3000 ) {
// wait for more
//qDebug("waitformore ");
QTimer::singleShot( 100, this , SLOT (readFileFromSocket( ) ));
return;
}
QString fileName = mFileName;
QFile file ( fileName );
if (!file.open( IO_WriteOnly ) ) {
mFileString = "";
mRetVal = errorR;
- qDebug("Error open temp calender file for writing: %s",fileName.latin1() );
+ qDebug("KSS:Error open temp sync file for writing: %s",fileName.latin1() );
deleteSocket();
return ;
}
// mView->setLoadedFileVersion(QDateTime::currentDateTime().addSecs( -1));
QTextStream ts ( &file );
ts.setEncoding( QTextStream::Latin1 );
ts << mFileString;
file.close();
mFileString = "";
mRetVal = successR;
mSocket->close();
// if state is not idle, deleteSocket(); is called via
// connect( mSocket, SIGNAL(delayedCloseFinished ()), this, SLOT(deleteSocket()) );
if ( mSocket->state() == QSocket::Idle )
deleteSocket();
}
void KCommandSocket::deleteSocket()
{
//qDebug("KCommandSocket::deleteSocket() ");
if ( mTimerSocket->isActive () ) {
mTimerSocket->stop();
mRetVal = errorTO;
qDebug("Connection to remote host timed out");
if ( mSocket ) {
mSocket->close();
//if ( mSocket->state() == QSocket::Idle )
// deleteSocket();
delete mSocket;
mSocket = 0;
}
KMessageBox::error( 0, i18n("Connection to remote\nhost timed out!\nDid you forgot to enable\nsyncing on remote host? "));
emit commandFinished( this, mRetVal );
return;
}
//qDebug("KCommandSocket::deleteSocket() %d", mRetVal );
if ( mSocket)
delete mSocket;
mSocket = 0;
emit commandFinished( this, mRetVal );
}
diff --git a/microkde/kconfig.cpp b/microkde/kconfig.cpp
index ba41f6c..5b685d3 100644
--- a/microkde/kconfig.cpp
+++ b/microkde/kconfig.cpp
@@ -1,547 +1,547 @@
#include <qfile.h>
#include <qtextstream.h>
#include <qwidget.h>
#include "kdebug.h"
#include "kurl.h"
#include "kstandarddirs.h"
#include "kconfig.h"
QString KConfig::mGroup = "";
//QString KConfig::mGroup = "General";
KConfig::KConfig( const QString &fileName )
: mFileName( fileName ), mDirty( false )
{
mTempGroup = "";
load();
}
KConfig::~KConfig()
{
sync();
}
// we need the temp group for plugins on windows
void KConfig::setTempGroup( const QString &group )
{
mTempGroup = group;
if ( mTempGroup.right( 1 ) != "/" ) mTempGroup += "/";
}
QString KConfig::tempGroup() const {
return mTempGroup;
}
void KConfig::setGroup( const QString &group )
{
mGroup = group;
if ( mGroup.right( 1 ) != "/" ) mGroup += "/";
}
//US
QString KConfig::group() const {
return mGroup;
}
//US added method
QValueList<int> KConfig::readIntListEntry( const QString & key)
{
// qDebug("KConfig::readIntListEntry key=%s:", key.latin1());
QValueList<int> result;
QMap<QString,QString>::ConstIterator mit = mStringMap.find( mGroup + key );
if ( mit == mStringMap.end() ) {
return result;
}
QStringList valuesAsStrings = QStringList::split(":", *mit );
bool ok = false;
bool ok2 = true;
int val;
for ( QStringList::Iterator sit = valuesAsStrings.begin(); sit != valuesAsStrings.end(); ++sit ) {
val = (*sit).toInt(&ok);
result << val;
if (ok == false) {
qDebug("KConfig::readIntListEntry str=%s , int=%n:", (*sit).latin1(), &val);
ok2 = false;
}
}
if (ok2 == false)
{
qDebug("KConfig::readIntListEntry: error while reading one of the intvalues.");
}
return result;
}
int KConfig::readNumEntry( const QString & key, int def )
{
QString res = readEntry(key, QString::number(def ) );
bool ok = false;
int result = res.toInt(&ok);
if ( ok )
return result;
return def;
}
QString KConfig::readEntry( const QString &key, const QString &def )
{
QMap<QString,QString>::ConstIterator it = mStringMap.find( mGroup + key );
if ( it == mStringMap.end() ) {
return def;
}
return *it;
}
QSize KConfig::readSizeEntry( const QString &key, QSize* def )
{
QValueList<int> intlist = readIntListEntry(key);
if (intlist.count() < 2)
{
if (def)
return *def;
else
return QSize();
}
QSize ret;
ret.setWidth(intlist[0]);
ret.setHeight(intlist[1]);
return ret;
}
QStringList KConfig::readListEntry( const QString &key )
{
QMap<QString,QString>::ConstIterator it = mStringMap.find( mGroup + key );
if ( it == mStringMap.end() ) {
return QStringList();
}
return QStringList::split(":", *it );
}
bool KConfig::readBoolEntry( const QString &key, bool def )
{
QMap<QString,bool>::ConstIterator it = mBoolMap.find( mGroup + key );
if ( it == mBoolMap.end() ) {
return def;
}
return *it;
}
QColor KConfig::readColorEntry( const QString & e, QColor *def )
{
QStringList l;
l = readListEntry( e );
if (l.count() != 3 ) {
if ( def )
return *def;
else
return QColor();
}
QColor c ( l[0].toInt(), l[1].toInt(), l[2].toInt() );
return c;
}
QFont KConfig::readFontEntry( const QString & e, QFont *def )
{
QStringList font = readListEntry( e );
if ( font.isEmpty() )
return *def;
QFont f;
f.setFamily( font[0]);
f.setBold ( font[1] == "bold");
f.setPointSize ( font[2].toInt());
f.setItalic( font[3] == "italic" );
return f;
}
QDateTime KConfig::readDateTimeEntry( const QString &key, const QDateTime *def )
{
QMap<QString,QDateTime>::ConstIterator it = mDateTimeMap.find( mGroup + key );
if ( it == mDateTimeMap.end() ) {
if ( def ) return *def;
else return QDateTime();
}
return *it;
}
//US added method
void KConfig::writeEntry( const QString &key, const QValueList<int> &value)
{
QStringList valuesAsStrings;
QValueList<int>::ConstIterator it;
for( it = value.begin(); it != value.end(); ++it )
{
valuesAsStrings << QString::number(*it);
}
mStringMap.insert( mGroup + key, valuesAsStrings.join(":") );
mDirty = true;
}
void KConfig::writeEntry( const QString & key , int num )
{
writeEntry( key, QString::number ( num ) );
}
void KConfig::writeEntry( const QString &key, const QString &value )
{
mStringMap.insert( mGroup + key, value );
mDirty = true;
}
void KConfig::writeEntry( const QString &key, const QStringList &value )
{
mStringMap.insert( mGroup + key, value.join(":") );
mDirty = true;
}
void KConfig::writeEntry( const QString &key, bool value)
{
mBoolMap.insert( mGroup + key, value );
mDirty = true;
}
void KConfig::writeEntry( const QString & e, const QColor & c )
{
QStringList l;
l.append( QString::number ( c.red() ) );
l.append( QString::number ( c.green() ) );
l.append( QString::number ( c.blue() ) );
writeEntry( e, l );
}
void KConfig::writeEntry( const QString & e, const QSize & s )
{
QValueList<int> intlist;
intlist << s.width() << s.height();
writeEntry( e, intlist );
}
void KConfig::writeEntry( const QString & e , const QFont & f )
{
QStringList font;
font.append( f.family());
font.append( (!f.bold ()?"nonbold":"bold") );
font.append( QString::number ( f.pointSize () ) );
font.append( !f.italic ()?"nonitalic":"italic" );
writeEntry( e, font );
}
void KConfig::writeEntry( const QString &key, const QDateTime &dt )
{
mDateTimeMap.insert( mGroup + key, dt );
}
void KConfig::load()
{
QFile f( mFileName );
if ( !f.open( IO_ReadOnly ) ) {
- qDebug("KConfig: could not open file %s ",mFileName.latin1() );
- return;
+ //qDebug("KConfig: could not open file %s ",mFileName.latin1() );
+ return;
}
mBoolMap.clear();
mStringMap.clear();
QTextStream t( &f );
QString line = t.readLine();
while ( !line.isNull() ) {
QStringList tokens = QStringList::split( ",", line );
if ( tokens[0] == "bool" ) {
bool value = false;
if ( tokens[2] == "1" ) value = true;
mBoolMap.insert( tokens[1], value );
} else if ( tokens[0] == "QString" ) {
QString value = tokens[2];
mStringMap.insert( tokens[1], value );
} else if ( tokens[0] == "QDateTime" ) {
#if 0
int year = tokens[2].toInt();
QDateTime dt( QDate( year,
tokens[3].toInt(),
tokens[4].toInt() ),
QTime( tokens[5].toInt(), tokens[6].toInt(),
tokens[7].toInt() ) );
mDateTimeMap.insert( tokens[1], dt );
#endif
}
line = t.readLine();
}
}
void KConfig::sync()
{
if ( !mDirty ) return;
//qDebug("KConfig::sync() %s ",mFileName.latin1() );
//kdDebug() << "KConfig::sync(): " << mFileName << endl;
//US I took the following code from a newer version of KDE
// Create the containing dir if needed
KURL path;
path.setPath(mFileName);
QString dir=path.directory();
KStandardDirs::makeDir(dir);
QFile f( mFileName );
if ( !f.open( IO_WriteOnly ) ) {
qDebug("KConfig::sync() Can't open file %s ",mFileName.latin1() );
return;
}
QTextStream t( &f );
QMap<QString,bool>::ConstIterator itBool;
for( itBool = mBoolMap.begin(); itBool != mBoolMap.end(); ++itBool ) {
t << "bool," << itBool.key() << "," << ( *itBool ? "1" : "0" ) << endl;
}
QMap<QString,QString>::ConstIterator itString;
for( itString = mStringMap.begin(); itString != mStringMap.end(); ++itString ) {
t << "QString," << itString.key() << "," << (*itString ) << endl;
}
QMap<QString,QDateTime>::ConstIterator itDateTime;
for( itDateTime = mDateTimeMap.begin(); itDateTime != mDateTimeMap.end(); ++itDateTime ) {
QDateTime dt = *itDateTime;
t << "QDateTime," << itDateTime.key() << ","
<< dt.date().year() << ","
<< dt.date().month() << ","
<< dt.date().day() << ","
<< dt.time().hour() << ","
<< dt.time().minute() << ","
<< dt.time().second() << endl;
}
f.close();
mDirty = false;
}
//US I took the following deleteGroup method from a newer version from KDE.
/**
* Deletes a configuration entry group
*
* If the group is not empty and bDeep is false, nothing gets
* deleted and false is returned.
* If this group is the current group and it is deleted, the
* current group is undefined and should be set with setGroup()
* before the next operation on the configuration object.
*
* @param group The name of the group
* returns true if we deleted at least one entry.
*/
bool KConfig::deleteGroup( const QString& group)
{
bool dirty = false;
int pos;
QMap<QString,bool>::Iterator itBool = mBoolMap.begin();
QMap<QString,bool>::Iterator delBool;
while ( itBool != mBoolMap.end() ) {
pos = itBool.key().find( group );
if (pos == 0) {
delBool = itBool;
++itBool;
mBoolMap.remove(delBool);
dirty = true;
} else
++itBool;
}
/*
for( itBool = mBoolMap.begin(); itBool != mBoolMap.end(); ++itBool )
{
pos = itBool.key().find( group );
if (pos == 0) {
mBoolMap.remove(itBool);
dirty = true;
}
}
*/
QMap<QString,QString>::Iterator itString = mStringMap.begin();
QMap<QString,QString>::Iterator delString ;
while( itString != mStringMap.end() ) {
pos = itString.key().find( group );
if (pos == 0) {
delString = itString;
++itString;
mStringMap.remove(delString);
//qDebug("delte++++++++++++++++++ ");
dirty = true;
} else
++itString;
}
/* this leads to a memory access violation
for( itString = mStringMap.begin(); itString != mStringMap.end(); ++itString )
{
pos = itString.key().find( group );
if (pos == 0) {
mStringMap.remove(itString);
dirty = true;
}
}
*/
QMap<QString,QDateTime>::Iterator itDateTime= mDateTimeMap.begin();
QMap<QString,QDateTime>::Iterator delDateTime;
while ( itDateTime != mDateTimeMap.end() ) {
pos = itDateTime.key().find( group );
if (pos == 0) {
delDateTime = itDateTime;
++itDateTime;
mDateTimeMap.remove(delDateTime);
dirty = true;
} else
++itDateTime;
}
/*
for( itDateTime = mDateTimeMap.begin(); itDateTime != mDateTimeMap.end(); ++itDateTime )
{
pos = itDateTime.key().find( group );
if (pos == 0) {
mDateTimeMap.remove(itDateTime);
dirty = true;
}
}
*/
if (dirty)
mDirty = true;
return dirty;
}
//US I took the following hasGroup method from a newer version from KDE.
/**
* Returns true if the specified group is known about.
*
* @param group The group to search for.
* @return Whether the group exists.
*/
bool KConfig::hasGroup(const QString &group) const
{
QMap<QString,bool>::ConstIterator itBool;
for( itBool = mBoolMap.begin(); itBool != mBoolMap.end(); ++itBool )
{
if (itBool.key().find( group ) == 0) {
return true;
}
}
QMap<QString,QString>::ConstIterator itString;
for( itString = mStringMap.begin(); itString != mStringMap.end(); ++itString )
{
if (itString.key().find( group ) == 0) {
return true;
}
}
QMap<QString,QDateTime>::ConstIterator itDateTime;
for( itDateTime = mDateTimeMap.begin(); itDateTime != mDateTimeMap.end(); ++itDateTime )
{
if (itDateTime.key().find( group ) == 0) {
return true;
}
}
return false;
}
void KConfig::deleteEntry( const QString &key)
{
bool dirty = false;
QMap<QString,bool>::Iterator itBool = mBoolMap.find( mGroup + key );
if ( itBool != mBoolMap.end() ) {
mBoolMap.remove(itBool);
dirty = true;
}
QMap<QString,QString>::Iterator itString = mStringMap.find( mGroup + key );
if ( itString != mStringMap.end() ) {
mStringMap.remove(itString);
dirty = true;
}
QMap<QString,QDateTime>::Iterator itDateTime = mDateTimeMap.find( mGroup + key );
if ( itDateTime != mDateTimeMap.end() ) {
mDateTimeMap.remove(itDateTime);
dirty = true;
}
if (dirty)
mDirty = true;
}
//US
QString KConfig::getFileName()
{
return mFileName;
}
bool KConfig::hasKey( const QString &key)
{
QMap<QString,bool>::Iterator itBool = mBoolMap.find( mGroup + key );
if ( itBool != mBoolMap.end() ) {
return true;
}
QMap<QString,QString>::Iterator itString = mStringMap.find( mGroup + key );
if ( itString != mStringMap.end() ) {
return true;
}
QMap<QString,QDateTime>::Iterator itDateTime = mDateTimeMap.find( mGroup + key );
if ( itDateTime != mDateTimeMap.end() ) {
return true;
}
return false;
}
diff --git a/microkde/kdecore/kstandarddirs.cpp b/microkde/kdecore/kstandarddirs.cpp
index 1c3e0ae..4c03c15 100644
--- a/microkde/kdecore/kstandarddirs.cpp
+++ b/microkde/kdecore/kstandarddirs.cpp
@@ -1,1662 +1,1662 @@
/* This file is part of the KDE libraries
Copyright (C) 1999 Sirtaj Singh Kang <taj@kde.org>
Copyright (C) 1999 Stephan Kulow <coolo@kde.org>
Copyright (C) 1999 Waldo Bastian <bastian@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 version 2 as published by the Free Software Foundation.
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.
*/
/*
* Author: Stephan Kulow <coolo@kde.org> and Sirtaj Singh Kang <taj@kde.org>
* Version: $Id$
* Generated: Thu Mar 5 16:05:28 EST 1998
*/
//US #include "config.h"
#include <stdlib.h>
#include <assert.h>
//US#include <errno.h>
//US #ifdef HAVE_SYS_STAT_H
//US #include <sys/stat.h>
//US #endif
//US#include <sys/types.h>
//US#include <dirent.h>
//US#include <pwd.h>
#include <qregexp.h>
#include <qasciidict.h>
#include <qdict.h>
#include <qdir.h>
#include <qfileinfo.h>
#include <qstring.h>
#include <qmessagebox.h>
#include <qapplication.h>
#include <qstringlist.h>
#include "kstandarddirs.h"
#include "kconfig.h"
#include "kdebug.h"
//US #include "kinstance.h"
#include "kshell.h"
//US#include <sys/param.h>
//US#include <unistd.h>
//US
QString KStandardDirs::mAppDir = QString::null;
template class QDict<QStringList>;
#if 0
#include <qtextedit.h>
void ddd( QString op )
{
static QTextEdit * dot = 0;
if ( ! dot )
dot = new QTextEdit();
dot->show();
dot->append( op );
}
#endif
class KStandardDirs::KStandardDirsPrivate
{
public:
KStandardDirsPrivate()
: restrictionsActive(false),
dataRestrictionActive(false)
{ }
bool restrictionsActive;
bool dataRestrictionActive;
QAsciiDict<bool> restrictions;
QStringList xdgdata_prefixes;
QStringList xdgconf_prefixes;
};
static const char* const types[] = {"html", "icon", "apps", "sound",
"data", "locale", "services", "mime",
"servicetypes", "config", "exe", "tmp",
"wallpaper", "lib", "pixmap", "templates",
"module", "qtplugins",
"xdgdata-apps", "xdgdata-dirs", "xdgconf-menu", 0 };
static int tokenize( QStringList& token, const QString& str,
const QString& delim );
KStandardDirs::KStandardDirs( ) : addedCustoms(false)
{
d = new KStandardDirsPrivate;
dircache.setAutoDelete(true);
relatives.setAutoDelete(true);
absolutes.setAutoDelete(true);
savelocations.setAutoDelete(true);
addKDEDefaults();
}
KStandardDirs::~KStandardDirs()
{
delete d;
}
bool KStandardDirs::isRestrictedResource(const char *type, const QString& relPath) const
{
if (!d || !d->restrictionsActive)
return false;
if (d->restrictions[type])
return true;
if (strcmp(type, "data")==0)
{
applyDataRestrictions(relPath);
if (d->dataRestrictionActive)
{
d->dataRestrictionActive = false;
return true;
}
}
return false;
}
void KStandardDirs::applyDataRestrictions(const QString &relPath) const
{
QString key;
int i = relPath.find('/');
if (i != -1)
key = "data_"+relPath.left(i);
else
key = "data_"+relPath;
if (d && d->restrictions[key.latin1()])
d->dataRestrictionActive = true;
}
QStringList KStandardDirs::allTypes() const
{
QStringList list;
for (int i = 0; types[i] != 0; ++i)
list.append(QString::fromLatin1(types[i]));
return list;
}
void KStandardDirs::addPrefix( const QString& _dir )
{
if (_dir.isNull())
return;
QString dir = _dir;
if (dir.at(dir.length() - 1) != '/')
dir += '/';
if (!prefixes.contains(dir)) {
prefixes.append(dir);
dircache.clear();
}
}
void KStandardDirs::addXdgConfigPrefix( const QString& _dir )
{
if (_dir.isNull())
return;
QString dir = _dir;
if (dir.at(dir.length() - 1) != '/')
dir += '/';
if (!d->xdgconf_prefixes.contains(dir)) {
d->xdgconf_prefixes.append(dir);
dircache.clear();
}
}
void KStandardDirs::addXdgDataPrefix( const QString& _dir )
{
if (_dir.isNull())
return;
QString dir = _dir;
if (dir.at(dir.length() - 1) != '/')
dir += '/';
if (!d->xdgdata_prefixes.contains(dir)) {
d->xdgdata_prefixes.append(dir);
dircache.clear();
}
}
QString KStandardDirs::kfsstnd_prefixes()
{
return prefixes.join(":");
}
bool KStandardDirs::addResourceType( const char *type,
const QString& relativename )
{
if (relativename.isNull())
return false;
QStringList *rels = relatives.find(type);
if (!rels) {
rels = new QStringList();
relatives.insert(type, rels);
}
QString copy = relativename;
if (copy.at(copy.length() - 1) != '/')
copy += '/';
if (!rels->contains(copy)) {
rels->prepend(copy);
dircache.remove(type); // clean the cache
return true;
}
return false;
}
bool KStandardDirs::addResourceDir( const char *type,
const QString& absdir)
{
QStringList *paths = absolutes.find(type);
if (!paths) {
paths = new QStringList();
absolutes.insert(type, paths);
}
QString copy = absdir;
if (copy.at(copy.length() - 1) != '/')
copy += '/';
if (!paths->contains(copy)) {
paths->append(copy);
dircache.remove(type); // clean the cache
return true;
}
return false;
}
QString KStandardDirs::findResource( const char *type,
const QString& filename ) const
{
if (filename.at(0) == '/')
return filename; // absolute dirs are absolute dirs, right? :-/
#if 0
kdDebug() << "Find resource: " << type << endl;
for (QStringList::ConstIterator pit = prefixes.begin();
pit != prefixes.end();
pit++)
{
kdDebug() << "Prefix: " << *pit << endl;
}
#endif
QString dir = findResourceDir(type, filename);
if (dir.isNull())
return dir;
else return dir + filename;
}
/*US
static Q_UINT32 updateHash(const QString &file, Q_UINT32 hash)
{
QCString cFile = QFile::encodeName(file);
//US struct stat buff;
//US if ((access(cFile, R_OK) == 0) &&
//US (stat( cFile, &buff ) == 0) &&
//US (S_ISREG( buff.st_mode )))
QFileInfo pathfnInfo(cFile);
if (( pathfnInfo.isReadable() == true ) &&
( pathfnInfo.isFile()) )
{
//US hash = hash + (Q_UINT32) buff.st_ctime;
hash = hash + (Q_UINT32) pathfnInfo.lastModified();
}
return hash;
}
*/
/*US
Q_UINT32 KStandardDirs::calcResourceHash( const char *type,
const QString& filename, bool deep) const
{
Q_UINT32 hash = 0;
if (filename.at(0) == '/')
{
// absolute dirs are absolute dirs, right? :-/
return updateHash(filename, hash);
}
if (d && d->restrictionsActive && (strcmp(type, "data")==0))
applyDataRestrictions(filename);
QStringList candidates = resourceDirs(type);
QString fullPath;
for (QStringList::ConstIterator it = candidates.begin();
it != candidates.end(); it++)
{
hash = updateHash(*it + filename, hash);
if (!deep && hash)
return hash;
}
return hash;
}
*/
QStringList KStandardDirs::findDirs( const char *type,
const QString& reldir ) const
{
QStringList list;
checkConfig();
if (d && d->restrictionsActive && (strcmp(type, "data")==0))
applyDataRestrictions(reldir);
QStringList candidates = resourceDirs(type);
QDir testdir;
for (QStringList::ConstIterator it = candidates.begin();
it != candidates.end(); it++) {
testdir.setPath(*it + reldir);
if (testdir.exists())
list.append(testdir.absPath() + '/');
}
return list;
}
QString KStandardDirs::findResourceDir( const char *type,
const QString& filename) const
{
#ifndef NDEBUG
if (filename.isEmpty()) {
kdWarning() << "filename for type " << type << " in KStandardDirs::findResourceDir is not supposed to be empty!!" << endl;
return QString::null;
}
#endif
if (d && d->restrictionsActive && (strcmp(type, "data")==0))
applyDataRestrictions(filename);
QStringList candidates = resourceDirs(type);
QString fullPath;
#ifdef DESKTOP_VERSION
#ifdef _WIN32_
candidates.prepend( qApp->applicationDirPath () +"\\");
#else
candidates.prepend( qApp->applicationDirPath () +"/");
#endif
#endif
for (QStringList::ConstIterator it = candidates.begin(); it != candidates.end(); it++)
{
//qDebug("looking for dir %s - file %s", (*it).latin1(), filename.latin1());
if (exists(*it + filename))
return *it;
}
#ifndef NDEBUG
if(false && type != "locale")
qDebug("KStdDirs::findResDir(): can't find %s ", filename.latin1());
#endif
return QString::null;
}
bool KStandardDirs::exists(const QString &fullPath)
{
//US struct stat buff;
QFileInfo fullPathInfo(QFile::encodeName(fullPath));
//US if (access(QFile::encodeName(fullPath), R_OK) == 0 && fullPathInfo.isReadable())
if (fullPathInfo.isReadable())
{
if (fullPath.at(fullPath.length() - 1) != '/') {
//US if (S_ISREG( buff.st_mode ))
if (fullPathInfo.isFile())
return true;
}
else {
//US if (S_ISDIR( buff.st_mode ))
if (fullPathInfo.isDir())
return true;
}
}
return false;
}
static void lookupDirectory(const QString& path, const QString &relPart,
const QRegExp &regexp,
QStringList& list,
QStringList& relList,
bool recursive, bool uniq)
{
QString pattern = regexp.pattern();
if (recursive || pattern.contains('?') || pattern.contains('*'))
{
// We look for a set of files.
//US DIR *dp = opendir( QFile::encodeName(path));
QDir dp(QFile::encodeName(path));
if (!dp.exists())
return;
static int iii = 0;
++iii;
if ( iii == 5 )
abort();
assert(path.at(path.length() - 1) == '/');
//US struct dirent *ep;
//US struct stat buff;
QString _dot(".");
QString _dotdot("..");
//US while( ( ep = readdir( dp ) ) != 0L )
QStringList direntries = dp.entryList();
QStringList::Iterator it = direntries.begin();
while ( it != list.end() ) // for each file...
{
//US QString fn( QFile::decodeName(ep->d_name));
QString fn = (*it); // dp.entryList already decodes
it++;
if ( fn.isNull() )
break;
if (fn == _dot || fn == _dotdot || fn.at(fn.length() - 1).latin1() == '~' )
continue;
/*US
if (!recursive && !regexp.exactMatch(fn))
continue; // No match
*/
//US this should do the same:
int pos = regexp.match(fn);
if (!recursive && !pos == 0)
continue; // No match
QString pathfn = path + fn;
/*US
if ( stat( QFile::encodeName(pathfn), &buff ) != 0 ) {
kdDebug() << "Error stat'ing " << pathfn << " : " << perror << endl;
continue; // Couldn't stat (e.g. no read permissions)
}
if ( recursive )
{
if ( S_ISDIR( buff.st_mode )) {
lookupDirectory(pathfn + '/', relPart + fn + '/', regexp, list, relList, recursive, uniq);
}
*/
//US replacement:
QFileInfo pathfnInfo(QFile::encodeName(pathfn));
if ( pathfnInfo.isReadable() == false )
{
//US kdDebug() << "Error stat'ing " << pathfn << " : " << perror << endl;
continue; // Couldn't stat (e.g. no read permissions)
}
if ( recursive )
{
if ( pathfnInfo.isDir()) {
lookupDirectory(pathfn + '/', relPart + fn + '/', regexp, list, relList, recursive, uniq);
}
/*US
if (!regexp.exactMatch(fn))
continue; // No match
*/
//US this should do the same:
pos = regexp.match(fn);
if (!pos == 0)
continue; // No match
}
//US if ( S_ISREG( buff.st_mode))
if ( pathfnInfo.isFile())
{
if (!uniq || !relList.contains(relPart + fn))
{
list.append( pathfn );
relList.append( relPart + fn );
}
}
}
//US closedir( dp );
}
else
{
// We look for a single file.
QString fn = pattern;
QString pathfn = path + fn;
//US struct stat buff;
QFileInfo pathfnInfo(QFile::encodeName(pathfn));
//US if ( stat( QFile::encodeName(pathfn), &buff ) != 0 )
if ( pathfnInfo.isReadable() == false )
return; // File not found
//US if ( S_ISREG( buff.st_mode))
if ( pathfnInfo.isFile())
{
if (!uniq || !relList.contains(relPart + fn))
{
list.append( pathfn );
relList.append( relPart + fn );
}
}
}
}
static void lookupPrefix(const QString& prefix, const QString& relpath,
const QString& relPart,
const QRegExp &regexp,
QStringList& list,
QStringList& relList,
bool recursive, bool uniq)
{
if (relpath.isNull()) {
lookupDirectory(prefix, relPart, regexp, list,
relList, recursive, uniq);
return;
}
QString path;
QString rest;
if (relpath.length())
{
int slash = relpath.find('/');
if (slash < 0)
rest = relpath.left(relpath.length() - 1);
else {
path = relpath.left(slash);
rest = relpath.mid(slash + 1);
}
}
assert(prefix.at(prefix.length() - 1) == '/');
//US struct stat buff;
if (path.contains('*') || path.contains('?')) {
QRegExp pathExp(path, true, true);
//US DIR *dp = opendir( QFile::encodeName(prefix) );
QDir dp(QFile::encodeName(prefix));
//US if (!dp)
if (!dp.exists())
{
return;
}
//US struct dirent *ep;
QString _dot(".");
QString _dotdot("..");
//US while( ( ep = readdir( dp ) ) != 0L )
QStringList direntries = dp.entryList();
QStringList::Iterator it = direntries.begin();
while ( it != list.end() ) // for each file...
{
//US QString fn( QFile::decodeName(ep->d_name));
QString fn = (*it); // dp.entryList() already encodes the strings
it++;
if (fn == _dot || fn == _dotdot || fn.at(fn.length() - 1) == '~')
continue;
#ifdef DESKTOP_VERSION
if (pathExp.search(fn) == -1)
continue; // No match
#else
//US this should do the same:
if (pathExp.find(fn, 0) == -1)
continue; // No match
#endif
QString rfn = relPart+fn;
fn = prefix + fn;
//US if ( stat( QFile::encodeName(fn), &buff ) != 0 )
QFileInfo fnInfo(QFile::encodeName(fn));
if ( fnInfo.isReadable() == false )
{
//US kdDebug() << "Error statting " << fn << " : " << perror << endl;
continue; // Couldn't stat (e.g. no permissions)
}
//US if ( S_ISDIR( buff.st_mode ))
if ( fnInfo.isDir() )
lookupPrefix(fn + '/', rest, rfn + '/', regexp, list, relList, recursive, uniq);
}
//US closedir( dp );
} else {
// Don't stat, if the dir doesn't exist we will find out
// when we try to open it.
lookupPrefix(prefix + path + '/', rest,
relPart + path + '/', regexp, list,
relList, recursive, uniq);
}
}
QStringList
KStandardDirs::findAllResources( const char *type,
const QString& filter,
bool recursive,
bool uniq,
QStringList &relList) const
{
QStringList list;
if (filter.at(0) == '/') // absolute paths we return
{
list.append( filter);
return list;
}
QString filterPath;
QString filterFile;
if (filter.length())
{
int slash = filter.findRev('/');
if (slash < 0)
filterFile = filter;
else {
filterPath = filter.left(slash + 1);
filterFile = filter.mid(slash + 1);
}
}
checkConfig();
if (d && d->restrictionsActive && (strcmp(type, "data")==0))
applyDataRestrictions(filter);
QStringList candidates = resourceDirs(type);
if (filterFile.isEmpty())
filterFile = "*";
QRegExp regExp(filterFile, true, true);
for (QStringList::ConstIterator it = candidates.begin();
it != candidates.end(); it++)
{
lookupPrefix(*it, filterPath, "", regExp, list,
relList, recursive, uniq);
}
return list;
}
QStringList
KStandardDirs::findAllResources( const char *type,
const QString& filter,
bool recursive,
bool uniq) const
{
QStringList relList;
return findAllResources(type, filter, recursive, uniq, relList);
}
QString
KStandardDirs::realPath(const QString &dirname)
{
#ifdef _WIN32_
return dirname;
#else
//US char realpath_buffer[MAXPATHLEN + 1];
//US memset(realpath_buffer, 0, MAXPATHLEN + 1);
char realpath_buffer[250 + 1];
memset(realpath_buffer, 0, 250 + 1);
/* If the path contains symlinks, get the real name */
if (realpath( QFile::encodeName(dirname).data(), realpath_buffer) != 0) {
// succes, use result from realpath
int len = strlen(realpath_buffer);
realpath_buffer[len] = '/';
realpath_buffer[len+1] = 0;
return QFile::decodeName(realpath_buffer);
}
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)
{
//#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
{
localKdeDir = QDir::homeDirPath() + "/kdepim/";
}
}
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());
+ //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/kdeui/kactioncollection.cpp b/microkde/kdeui/kactioncollection.cpp
index b819e76..69e5d02 100644
--- a/microkde/kdeui/kactioncollection.cpp
+++ b/microkde/kdeui/kactioncollection.cpp
@@ -1,839 +1,840 @@
/* This file is part of the KDE libraries
Copyright (C) 1999 Reginald Stadlbauer <reggie@kde.org>
(C) 1999 Simon Hausmann <hausmann@kde.org>
(C) 2000 Nicolas Hadacek <haadcek@kde.org>
(C) 2000 Kurt Granroth <granroth@kde.org>
(C) 2000 Michael Koch <koch@kde.org>
(C) 2001 Holger Freyther <freyther@kde.org>
(C) 2002 Ellis Whitehead <ellis@kde.org>
(C) 2002 Joseph Wenninger <jowenn@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 version 2 as published by the Free Software Foundation.
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 "kactioncollection.h"
//US#include "kactionshortcutlist.h"
#include <qptrdict.h>
//US#include <qvariant.h>
//US#include <kaccel.h>
//US#include <kaccelbase.h>
//US#include <kapplication.h>
#include <kdebug.h>
//US#include <kxmlguifactory.h>
//US I included the following files
#include <qasciidict.h>
#include <qptrlist.h>
#include "kaction.h"
#include <kglobal.h>
#include <qobject.h>
#include <qwidget.h>
class KActionCollection::KActionCollectionPrivate
{
public:
KActionCollectionPrivate()
{
//US m_instance = 0;
//m_bOneKAccelOnly = false;
//m_iWidgetCurrent = 0;
m_bAutoConnectShortcuts = true;
m_widget = 0;
m_kaccel = m_builderKAccel = 0;
m_dctHighlightContainers.setAutoDelete( true );
m_highlight = false;
m_currentHighlightAction = 0;
m_statusCleared = true;
}
//US KInstance *m_instance;
//US QString m_sXMLFile;
bool m_bAutoConnectShortcuts;
//bool m_bOneKAccelOnly;
//int m_iWidgetCurrent;
//QValueList<QWidget*> m_widgetList;
//QValueList<KAccel*> m_kaccelList;
QValueList<KActionCollection*> m_docList;
QWidget *m_widget;
KAccel *m_kaccel;
KAccel *m_builderKAccel;
QAsciiDict<KAction> m_actionDict;
QPtrDict< QPtrList<KAction> > m_dctHighlightContainers;
bool m_highlight;
KAction *m_currentHighlightAction;
bool m_statusCleared;
};
KActionCollection::KActionCollection( QWidget *parent, const char *name /*US,
KInstance *instance */)
: QObject( (QObject*)parent, name )
{
kdDebug(129) << "KActionCollection::KActionCollection( " << parent << ", " << name << " ): this = " << this << endl; // ellis
d = new KActionCollectionPrivate;
if( parent )
setWidget( parent );
//d->m_bOneKAccelOnly = (d->m_kaccelList.count() > 0);
//US setInstance( instance );
}
KActionCollection::KActionCollection( QWidget *watch, QObject* parent, const char *name /*US,
KInstance *instance */)
: QObject( parent, name )
{
kdDebug(129) << "KActionCollection::KActionCollection( " << watch << ", " << parent << ", " << name << " ): this = " << this << endl; //ellis
d = new KActionCollectionPrivate;
if( watch )
setWidget( watch );
//d->m_bOneKAccelOnly = (d->m_kaccelList.count() > 0);
//US setInstance( instance );
}
// KDE 4: remove
KActionCollection::KActionCollection( QObject *parent, const char *name /*US,
KInstance *instance */)
: QObject( parent, name )
{
kdWarning(129) << "KActionCollection::KActionCollection( QObject *parent, const char *name, KInstance *instance )" << endl; //ellis
//US kdBacktrace not available
//US kdDebug(129) << kdBacktrace() << endl;
d = new KActionCollectionPrivate;
//US QWidget* w = dynamic_cast<QWidget*>( parent );
QWidget* w = (QWidget*)( parent );
if( w )
setWidget( w );
//d->m_bOneKAccelOnly = (d->m_kaccelList.count() > 0);
//US setInstance( instance );
}
KActionCollection::KActionCollection( const KActionCollection &copy )
: QObject()
{
kdWarning(129) << "KActionCollection::KActionCollection( const KActionCollection & ): function is severely deprecated." << endl;
d = new KActionCollectionPrivate;
*this = copy;
}
// KDE 4: remove end
KActionCollection::~KActionCollection()
{
kdDebug(129) << "KActionCollection::~KActionCollection(): this = " << this << endl;
for ( QAsciiDictIterator<KAction> it( d->m_actionDict ); it.current(); ++it ) {
KAction* pAction = it.current();
if ( pAction->m_parentCollection == this )
pAction->m_parentCollection = 0L;
}
//US delete d->m_kaccel;
//US delete d->m_builderKAccel;
delete d; d = 0;
}
void KActionCollection::setWidget( QWidget* w )
{
//if ( d->m_actionDict.count() > 0 ) {
// kdError(129) << "KActionCollection::setWidget(): must be called before any actions are added to collection!" << endl;
// kdDebug(129) << kdBacktrace() << endl;
//}
//else
if ( !d->m_widget ) {
d->m_widget = w;
- qDebug("KActionCollection::setWidget: warning: KAccel is never used in microkde");
+ //qDebug("KActionCollection::setWidget: warning: KAccel is never used in microkde");
//US d->m_kaccel = new KAccel( w, this, "KActionCollection-KAccel" );
}
else if ( d->m_widget != w )
- kdWarning(129) << "KActionCollection::setWidget(): tried to change widget from " << d->m_widget << " to " << w << endl;
+ ;
+
}
void KActionCollection::setAutoConnectShortcuts( bool b )
{
d->m_bAutoConnectShortcuts = b;
}
bool KActionCollection::isAutoConnectShortcuts()
{
return d->m_bAutoConnectShortcuts;
}
bool KActionCollection::addDocCollection( KActionCollection* pDoc )
{
d->m_docList.append( pDoc );
return true;
}
void KActionCollection::beginXMLPlug( QWidget *widget )
{
qDebug("KActionCollection::beginXMLPlug has to be fixed");
/*US
kdDebug(129) << "KActionCollection::beginXMLPlug( buildWidget = " << widget << " ): this = " << this << " d->m_builderKAccel = " << d->m_builderKAccel << endl;
if( widget && !d->m_builderKAccel ) {
d->m_builderKAccel = new KAccel( widget, this, "KActionCollection-BuilderKAccel" );
}
*/
}
void KActionCollection::endXMLPlug()
{
kdDebug(129) << "KActionCollection::endXMLPlug(): this = " << this << endl;
//s_kaccelXML = 0;
}
void KActionCollection::prepareXMLUnplug()
{
qDebug("KActionCollection::prepareXMLUnplug has to be fixed");
/*US
kdDebug(129) << "KActionCollection::prepareXMLUnplug(): this = " << this << endl;
unplugShortcuts( d->m_kaccel );
if( d->m_builderKAccel ) {
unplugShortcuts( d->m_builderKAccel );
delete d->m_builderKAccel;
d->m_builderKAccel = 0;
}
*/
}
void KActionCollection::unplugShortcuts( KAccel* kaccel )
{
qDebug("KActionCollection::unplugShortcuts has to be fixed");
/*US
for ( QAsciiDictIterator<KAction> it( d->m_actionDict ); it.current(); ++it ) {
KAction* pAction = it.current();
pAction->removeKAccel( kaccel );
}
for( uint i = 0; i < d->m_docList.count(); i++ )
d->m_docList[i]->unplugShortcuts( kaccel );
*/
}
/*void KActionCollection::addWidget( QWidget* w )
{
if( !d->m_bOneKAccelOnly ) {
kdDebug(129) << "KActionCollection::addWidget( " << w << " ): this = " << this << endl;
for( uint i = 0; i < d->m_widgetList.count(); i++ ) {
if( d->m_widgetList[i] == w ) {
d->m_iWidgetCurrent = i;
return;
}
}
d->m_iWidgetCurrent = d->m_widgetList.count();
d->m_widgetList.append( w );
d->m_kaccelList.append( new KAccel( w, this, "KActionCollection-KAccel" ) );
}
}
void KActionCollection::removeWidget( QWidget* w )
{
if( !d->m_bOneKAccelOnly ) {
kdDebug(129) << "KActionCollection::removeWidget( " << w << " ): this = " << this << endl;
for( uint i = 0; i < d->m_widgetList.count(); i++ ) {
if( d->m_widgetList[i] == w ) {
// Remove KAccel object from children.
KAccel* pKAccel = d->m_kaccelList[i];
for ( QAsciiDictIterator<KAction> it( d->m_actionDict ); it.current(); ++it ) {
KAction* pAction = it.current();
if ( pAction->m_parentCollection == this ) {
pAction->removeKAccel( pKAccel );
}
}
delete pKAccel;
d->m_widgetList.remove( d->m_widgetList.at( i ) );
d->m_kaccelList.remove( d->m_kaccelList.at( i ) );
if( d->m_iWidgetCurrent == (int)i )
d->m_iWidgetCurrent = -1;
else if( d->m_iWidgetCurrent > (int)i )
d->m_iWidgetCurrent--;
return;
}
}
kdWarning(129) << "KActionCollection::removeWidget( " << w << " ): widget not in list." << endl;
}
}
bool KActionCollection::ownsKAccel() const
{
return d->m_bOneKAccelOnly;
}
uint KActionCollection::widgetCount() const
{
return d->m_widgetList.count();
}
const KAccel* KActionCollection::widgetKAccel( uint i ) const
{
return d->m_kaccelList[i];
}*/
//US we are using no accelerators so far. So just setup an empty implementation.
KAccel* KActionCollection::kaccel()
{
//if( d->m_kaccelList.count() > 0 )
// return d->m_kaccelList[d->m_iWidgetCurrent];
//else
// return 0;
//US return d->m_kaccel;
return 0;
}
//US we are using no accelerators so far. So just setup an empty implementation.
const KAccel* KActionCollection::kaccel() const
{
//if( d->m_kaccelList.count() > 0 )
// return d->m_kaccelList[d->m_iWidgetCurrent];
//else
// return 0;
//USreturn d->m_kaccel;
return 0;
}
/*void KActionCollection::findMainWindow( QWidget *w )
{
// Note: topLevelWidget() stops too early, we can't use it.
QWidget * tl = w;
while ( tl->parentWidget() ) // lookup parent and store
tl = tl->parentWidget();
KMainWindow * mw = dynamic_cast<KMainWindow *>(tl); // try to see if it's a kmainwindow
if (mw)
d->m_mainwindow = mw;
else
kdDebug(129) << "KAction::plugMainWindowAccel: Toplevel widget isn't a KMainWindow, can't plug accel. " << tl << endl;
}*/
void KActionCollection::_insert( KAction* action )
{
char unnamed_name[100];
const char *name = action->name();
if( qstrcmp( name, "unnamed" ) == 0 )
{
sprintf(unnamed_name, "unnamed-%p", (void *)action);
name = unnamed_name;
}
KAction *a = d->m_actionDict[ name ];
if ( a == action )
return;
d->m_actionDict.insert( name, action );
emit inserted( action );
}
void KActionCollection::_remove( KAction* action )
{
delete _take( action );
}
KAction* KActionCollection::_take( KAction* action )
{
char unnamed_name[100];
const char *name = action->name();
if( qstrcmp( name, "unnamed" ) == 0 )
{
sprintf(unnamed_name, "unnamed-%p", (void *) action);
name = unnamed_name;
}
KAction *a = d->m_actionDict.take( name );
if ( !a || a != action )
return 0;
emit removed( action );
return a;
}
void KActionCollection::_clear()
{
QAsciiDictIterator<KAction> it( d->m_actionDict );
while ( it.current() )
_remove( it.current() );
}
void KActionCollection::insert( KAction* action ) { _insert( action ); }
void KActionCollection::remove( KAction* action ) { _remove( action ); }
KAction* KActionCollection::take( KAction* action ) { return _take( action ); }
void KActionCollection::clear() { _clear(); }
KAccel* KActionCollection::accel() { return kaccel(); }
const KAccel* KActionCollection::accel() const { return kaccel(); }
KAccel* KActionCollection::builderKAccel() const { return d->m_builderKAccel; }
KAction* KActionCollection::action( const char* name, const char* classname ) const
{
KAction* pAction = 0;
if ( !classname && name )
pAction = d->m_actionDict[ name ];
else {
QAsciiDictIterator<KAction> it( d->m_actionDict );
for( ; it.current(); ++it )
{
if ( ( !name || strcmp( it.current()->name(), name ) == 0 ) &&
( !classname || strcmp( it.current()->className(), classname ) == 0 ) ) {
pAction = it.current();
break;
}
}
}
if( !pAction ) {
for( uint i = 0; i < d->m_docList.count() && !pAction; i++ )
pAction = d->m_docList[i]->action( name, classname );
}
return pAction;
}
KAction* KActionCollection::action( int index ) const
{
QAsciiDictIterator<KAction> it( d->m_actionDict );
it += index;
return it.current();
// return d->m_actions.at( index );
}
/*US
bool KActionCollection::readShortcutSettings( const QString& sConfigGroup, KConfigBase* pConfig )
{
return KActionShortcutList(this).readSettings( sConfigGroup, pConfig );
}
bool KActionCollection::writeShortcutSettings( const QString& sConfigGroup, KConfigBase* pConfig ) const
{
return KActionShortcutList((KActionCollection*)this).writeSettings( sConfigGroup, pConfig );
}
*/
uint KActionCollection::count() const
{
return d->m_actionDict.count();
}
QStringList KActionCollection::groups() const
{
QStringList lst;
QAsciiDictIterator<KAction> it( d->m_actionDict );
for( ; it.current(); ++it )
if ( !it.current()->group().isEmpty() && !lst.contains( it.current()->group() ) )
lst.append( it.current()->group() );
return lst;
}
KActionPtrList KActionCollection::actions( const QString& group ) const
{
KActionPtrList lst;
QAsciiDictIterator<KAction> it( d->m_actionDict );
for( ; it.current(); ++it )
if ( it.current()->group() == group )
lst.append( it.current() );
else if ( it.current()->group().isEmpty() && group.isEmpty() )
lst.append( it.current() );
return lst;
}
KActionPtrList KActionCollection::actions() const
{
KActionPtrList lst;
QAsciiDictIterator<KAction> it( d->m_actionDict );
for( ; it.current(); ++it )
lst.append( it.current() );
return lst;
}
/*US we have no instance object. Use KGlobal instead
void KActionCollection::setInstance( KInstance *instance )
{
if ( instance )
d->m_instance = instance;
qDebug("KActionCollection::setInstance has to be fixed");
else
d->m_instance = KGlobal::instance();
}
KInstance *KActionCollection::instance() const
{
return d->m_instance;
}
*/
/*US we have no XML facility in microkde
void KActionCollection::setXMLFile( const QString& sXMLFile )
{
d->m_sXMLFile = sXMLFile;
}
const QString& KActionCollection::xmlFile() const
{
return d->m_sXMLFile;
}
*/
void KActionCollection::setHighlightingEnabled( bool enable )
{
d->m_highlight = enable;
}
bool KActionCollection::highlightingEnabled() const
{
return d->m_highlight;
}
void KActionCollection::connectHighlight( QWidget *container, KAction *action )
{
if ( !d->m_highlight )
return;
QPtrList<KAction> *actionList = d->m_dctHighlightContainers[ container ];
if ( !actionList )
{
actionList = new QPtrList<KAction>;
if ( container->inherits( "QPopupMenu" ) )
{
connect( container, SIGNAL( highlighted( int ) ),
this, SLOT( slotMenuItemHighlighted( int ) ) );
connect( container, SIGNAL( aboutToHide() ),
this, SLOT( slotMenuAboutToHide() ) );
}
//US else if ( container->inherits( "KToolBar" ) )
else if ( container->inherits( "QToolBar" ) )
{
connect( container, SIGNAL( highlighted( int, bool ) ),
this, SLOT( slotToolBarButtonHighlighted( int, bool ) ) );
}
connect( container, SIGNAL( destroyed() ),
this, SLOT( slotDestroyed() ) );
d->m_dctHighlightContainers.insert( container, actionList );
}
actionList->append( action );
}
void KActionCollection::disconnectHighlight( QWidget *container, KAction *action )
{
if ( !d->m_highlight )
return;
QPtrList<KAction> *actionList = d->m_dctHighlightContainers[ container ];
if ( !actionList )
return;
actionList->removeRef( action );
if ( actionList->count() == 0 )
d->m_dctHighlightContainers.remove( container );
}
void KActionCollection::slotMenuItemHighlighted( int id )
{
if ( !d->m_highlight )
return;
if ( d->m_currentHighlightAction )
emit actionHighlighted( d->m_currentHighlightAction, false );
QWidget *container = static_cast<QWidget *>( const_cast<QObject *>( sender() ) );
d->m_currentHighlightAction = findAction( container, id );
if ( !d->m_currentHighlightAction )
{
if ( !d->m_statusCleared )
emit clearStatusText();
d->m_statusCleared = true;
return;
}
d->m_statusCleared = false;
emit actionHighlighted( d->m_currentHighlightAction );
emit actionHighlighted( d->m_currentHighlightAction, true );
emit actionStatusText( d->m_currentHighlightAction->toolTip() );
}
void KActionCollection::slotMenuAboutToHide()
{
if ( d->m_currentHighlightAction )
emit actionHighlighted( d->m_currentHighlightAction, false );
d->m_currentHighlightAction = 0;
if ( !d->m_statusCleared )
emit clearStatusText();
d->m_statusCleared = true;
}
void KActionCollection::slotToolBarButtonHighlighted( int id, bool highlight )
{
if ( !d->m_highlight )
return;
QWidget *container = static_cast<QWidget *>( const_cast<QObject *>( sender() ) );
KAction *action = findAction( container, id );
if ( !action )
{
d->m_currentHighlightAction = 0;
// use tooltip groups for toolbar status text stuff instead (Simon)
// emit clearStatusText();
return;
}
emit actionHighlighted( action, highlight );
if ( highlight )
d->m_currentHighlightAction = action;
else
{
d->m_currentHighlightAction = 0;
// emit clearStatusText();
}
}
void KActionCollection::slotDestroyed()
{
d->m_dctHighlightContainers.remove( reinterpret_cast<void *>( const_cast<QObject *>(sender()) ) );
}
KAction *KActionCollection::findAction( QWidget *container, int id )
{
QPtrList<KAction> *actionList = d->m_dctHighlightContainers[ reinterpret_cast<void *>( container ) ];
if ( !actionList )
return 0;
QPtrListIterator<KAction> it( *actionList );
for (; it.current(); ++it )
if ( it.current()->isPlugged( container, id ) )
return it.current();
return 0;
}
// KDE 4: remove
KActionCollection KActionCollection::operator+(const KActionCollection &c ) const
{
kdWarning(129) << "KActionCollection::operator+(): function is severely deprecated." << endl;
KActionCollection ret( *this );
QValueList<KAction *> actions = c.actions();
QValueList<KAction *>::ConstIterator it = actions.begin();
QValueList<KAction *>::ConstIterator end = actions.end();
for (; it != end; ++it )
ret.insert( *it );
return ret;
}
KActionCollection &KActionCollection::operator=( const KActionCollection &copy )
{
kdWarning(129) << "KActionCollection::operator=(): function is severely deprecated." << endl;
//d->m_bOneKAccelOnly = copy.d->m_bOneKAccelOnly;
//d->m_iWidgetCurrent = copy.d->m_iWidgetCurrent;
//d->m_widgetList = copy.d->m_widgetList;
//d->m_kaccelList = copy.d->m_kaccelList;
d->m_widget = copy.d->m_widget;
d->m_kaccel = copy.d->m_kaccel;
d->m_actionDict = copy.d->m_actionDict;
//US setInstance( copy.instance() );
return *this;
}
KActionCollection &KActionCollection::operator+=( const KActionCollection &c )
{
kdWarning(129) << "KActionCollection::operator+=(): function is severely deprecated." << endl;
QAsciiDictIterator<KAction> it(c.d->m_actionDict);
for ( ; it.current(); ++it )
insert( it.current() );
return *this;
}
// KDE 4: remove end
//---------------------------------------------------------------------
// KActionShortcutList
//---------------------------------------------------------------------
/*US
KActionShortcutList::KActionShortcutList( KActionCollection* pColl )
: m_actions( *pColl )
{ }
KActionShortcutList::~KActionShortcutList()
{ }
uint KActionShortcutList::count() const
{ return m_actions.count(); }
QString KActionShortcutList::name( uint i ) const
{ return m_actions.action(i)->name(); }
QString KActionShortcutList::label( uint i ) const
{ return m_actions.action(i)->text(); }
QString KActionShortcutList::whatsThis( uint i ) const
{ return m_actions.action(i)->whatsThis(); }
const KShortcut& KActionShortcutList::shortcut( uint i ) const
{ return m_actions.action(i)->shortcut(); }
const KShortcut& KActionShortcutList::shortcutDefault( uint i ) const
{ return m_actions.action(i)->shortcutDefault(); }
bool KActionShortcutList::isConfigurable( uint i ) const
{ return m_actions.action(i)->isShortcutConfigurable(); }
bool KActionShortcutList::setShortcut( uint i, const KShortcut& cut )
{ return m_actions.action(i)->setShortcut( cut ); }
const KInstance* KActionShortcutList::instance() const
{ return m_actions.instance(); }
QVariant KActionShortcutList::getOther( Other, uint ) const
{ return QVariant(); }
bool KActionShortcutList::setOther( Other, uint, QVariant )
{ return false; }
bool KActionShortcutList::save() const
{
kdDebug(129) << "KActionShortcutList::save(): xmlFile = " << m_actions.xmlFile() << endl;
if( m_actions.xmlFile().isEmpty() )
return writeSettings();
QString tagActionProp = QString::fromLatin1("ActionProperties");
QString tagAction = QString::fromLatin1("Action");
QString attrName = QString::fromLatin1("name");
QString attrShortcut = QString::fromLatin1("shortcut");
QString attrAccel = QString::fromLatin1("accel"); // Depricated attribute
// Read XML file
QString sXml( KXMLGUIFactory::readConfigFile( m_actions.xmlFile(), false, instance() ) );
QDomDocument doc;
doc.setContent( sXml );
// Process XML data
// first, lets see if we have existing properties
QDomElement elem;
QDomElement it = doc.documentElement();
// KXMLGUIFactory::removeDOMComments( it ); <-- What was this for? --ellis
it = it.firstChild().toElement();
for( ; !it.isNull(); it = it.nextSibling().toElement() ) {
if( it.tagName() == tagActionProp ) {
elem = it;
break;
}
}
// if there was none, create one
if( elem.isNull() ) {
elem = doc.createElement( tagActionProp );
doc.documentElement().appendChild( elem );
}
// now, iterate through our actions
uint nSize = count();
for( uint i = 0; i < nSize; i++ ) {
const QString& sName = name(i);
bool bSameAsDefault = (shortcut(i) == shortcutDefault(i));
//kdDebug(129) << "name = " << sName << " shortcut = " << shortcut(i).toStringInternal() << " def = " << shortcutDefault(i).toStringInternal() << endl;
// now see if this element already exists
QDomElement act_elem;
for( it = elem.firstChild().toElement(); !it.isNull(); it = it.nextSibling().toElement() ) {
if( it.attribute( attrName ) == sName ) {
act_elem = it;
break;
}
}
// nope, create a new one
if( act_elem.isNull() ) {
if( bSameAsDefault )
continue;
//kdDebug(129) << "\tnode doesn't exist." << endl;
act_elem = doc.createElement( tagAction );
act_elem.setAttribute( attrName, sName );
}
act_elem.removeAttribute( attrAccel );
if( bSameAsDefault ) {
act_elem.removeAttribute( attrShortcut );
//kdDebug(129) << "act_elem.attributes().count() = " << act_elem.attributes().count() << endl;
if( act_elem.attributes().count() == 1 )
elem.removeChild( act_elem );
} else {
act_elem.setAttribute( attrShortcut, shortcut(i).toStringInternal() );
elem.appendChild( act_elem );
}
}
// Write back to XML file
return KXMLGUIFactory::saveConfigFile( doc, m_actions.xmlFile(), instance() );
}
//---------------------------------------------------------------------
// KActionPtrShortcutList
//---------------------------------------------------------------------
KActionPtrShortcutList::KActionPtrShortcutList( KActionPtrList& list )
: m_actions( list )
{ }
KActionPtrShortcutList::~KActionPtrShortcutList()
{ }
uint KActionPtrShortcutList::count() const
{ return m_actions.count(); }
QString KActionPtrShortcutList::name( uint i ) const
{ return m_actions[i]->name(); }
QString KActionPtrShortcutList::label( uint i ) const
{ return m_actions[i]->text(); }
QString KActionPtrShortcutList::whatsThis( uint i ) const
{ return m_actions[i]->whatsThis(); }
const KShortcut& KActionPtrShortcutList::shortcut( uint i ) const
{ return m_actions[i]->shortcut(); }
const KShortcut& KActionPtrShortcutList::shortcutDefault( uint i ) const
{ return m_actions[i]->shortcutDefault(); }
bool KActionPtrShortcutList::isConfigurable( uint i ) const
{ return m_actions[i]->isShortcutConfigurable(); }
bool KActionPtrShortcutList::setShortcut( uint i, const KShortcut& cut )
{ return m_actions[i]->setShortcut( cut ); }
QVariant KActionPtrShortcutList::getOther( Other, uint ) const
{ return QVariant(); }
bool KActionPtrShortcutList::setOther( Other, uint, QVariant )
{ return false; }
bool KActionPtrShortcutList::save() const
{ return false; }
void KActionShortcutList::virtual_hook( int id, void* data )
{ KShortcutList::virtual_hook( id, data ); }
void KActionPtrShortcutList::virtual_hook( int id, void* data )
{ KShortcutList::virtual_hook( id, data ); }
*/
void KActionCollection::virtual_hook( int, void* )
{ /*BASE::virtual_hook( id, data );*/ }
/* vim: et sw=2 ts=2
*/
/*US
#include "kactioncollection.moc"
*/
diff --git a/microkde/kdeui/klistview.cpp b/microkde/kdeui/klistview.cpp
index b53a88a..2856f2d 100644
--- a/microkde/kdeui/klistview.cpp
+++ b/microkde/kdeui/klistview.cpp
@@ -1,2191 +1,2191 @@
/* This file is part of the KDE libraries
Copyright (C) 2000 Reginald Stadlbauer <reggie@kde.org>
Copyright (C) 2000 Charles Samuels <charles@kde.org>
Copyright (C) 2000 Peter Putzer
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License version 2 as published by the Free Software Foundation.
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 <qdragobject.h>
#include <qtimer.h>
#include <qheader.h>
#include <qcursor.h>
#include <qtooltip.h>
#include <qstyle.h>
#include <qpainter.h>
#include <kglobalsettings.h>
#include <kconfig.h>
#include <kconfigbase.h>
//US #include <kcursor.h>
#include <kapplication.h>
//US #include <kipc.h>
#include <kdebug.h>
#ifdef _WIN32_
#define Q_WS_QWS
#endif
#ifndef _WIN32_
#define private public
#include <qlistview.h>
#undef private
#endif
#include "klistview.h"
//US #include "klistviewlineedit.h"
#ifndef DESKTOP_VERSION
#include <qpe/qpeapplication.h>
#endif
// /*US
class KListView::Tooltip : public QToolTip
{
public:
Tooltip (KListView* parent, QToolTipGroup* group = 0L);
virtual ~Tooltip () {}
protected:
// */
/**
* Reimplemented from QToolTip for internal reasons.
*/
// /*US
virtual void maybeTip (const QPoint&);
private:
KListView* mParent;
};
KListView::Tooltip::Tooltip (KListView* parent, QToolTipGroup* group)
: QToolTip (parent, group),
mParent (parent)
{
}
void KListView::Tooltip::maybeTip (const QPoint&)
{
// FIXME
}
// */
class KListView::KListViewPrivate
{
public:
KListViewPrivate (KListView* listview)
: pCurrentItem (0L),
autoSelectDelay(1),
//US dragDelay (KGlobalSettings::dndEventDelay()),
dragDelay (10),
//US editor (new KListViewLineEdit (listview)),
cursorInExecuteArea(false),
bUseSingle(false),
bChangeCursorOverItem(false),
itemsMovable (true),
selectedBySimpleMove(false),
selectedUsingMouse(false),
showContextMenusOnPress(true),
itemsRenameable (false),
validDrag (false),
dragEnabled (false),
autoOpen (true),
dropVisualizer (true),
dropHighlighter (false),
createChildren (true),
pressedOnSelected (false),
wasShiftEvent (false),
fullWidth (false),
sortAscending(true),
tabRename(true),
sortColumn(0),
selectionDirection(0),
tooltipColumn (0),
selectionMode (Single),
//US contextMenuKey (KGlobalSettings::contextMenuKey()),
//US showContextMenusOnPress (KGlobalSettings::showContextMenusOnPress()),
mDropVisualizerWidth (4)
{
renameable += 0;
//US connect(editor, SIGNAL(done(QListViewItem*,int)), listview, SLOT(doneEditing(QListViewItem*,int)));
}
~KListViewPrivate ()
{
//US delete editor;
}
QListViewItem* pCurrentItem;
QTimer autoSelect;
int autoSelectDelay;
QTimer dragExpand;
QListViewItem* dragOverItem;
QPoint dragOverPoint;
QPoint startDragPos;
int dragDelay;
//US KListViewLineEdit *editor;
QValueList<int> renameable;
bool cursorInExecuteArea:1;
bool bUseSingle:1;
bool bChangeCursorOverItem:1;
bool itemsMovable:1;
bool selectedBySimpleMove : 1;
bool selectedUsingMouse:1;
bool itemsRenameable:1;
bool validDrag:1;
bool dragEnabled:1;
bool autoOpen:1;
bool dropVisualizer:1;
bool dropHighlighter:1;
bool createChildren:1;
bool pressedOnSelected:1;
bool wasShiftEvent:1;
bool fullWidth:1;
bool sortAscending:1;
bool tabRename:1;
int sortColumn;
//+1 means downwards (y increases, -1 means upwards, 0 means not selected), aleXXX
int selectionDirection;
int tooltipColumn;
SelectionModeExt selectionMode;
int contextMenuKey;
bool showContextMenusOnPress;
QRect mOldDropVisualizer;
int mDropVisualizerWidth;
QRect mOldDropHighlighter;
QListViewItem *afterItemDrop;
QListViewItem *parentItemDrop;
QColor alternateBackground;
};
/*US
KListViewLineEdit::KListViewLineEdit(KListView *parent)
: KLineEdit(parent->viewport()), item(0), col(0), p(parent)
{
setFrame( false );
hide();
connect( parent, SIGNAL( selectionChanged() ), SLOT( slotSelectionChanged() ));
}
KListViewLineEdit::~KListViewLineEdit()
{
}
void KListViewLineEdit::load(QListViewItem *i, int c)
{
item=i;
col=c;
QRect rect(p->itemRect(i));
setText(item->text(c));
int fieldX = rect.x() - 1;
int fieldW = p->columnWidth(col) + 2;
int pos = p->header()->mapToIndex(col);
for ( int index = 0; index < pos; index++ )
fieldX += p->columnWidth( p->header()->mapToSection( index ));
if ( col == 0 ) {
int d = i->depth() + (p->rootIsDecorated() ? 1 : 0);
d *= p->treeStepSize();
fieldX += d;
fieldW -= d;
}
if ( i->pixmap( col ) ) {// add width of pixmap
int d = i->pixmap( col )->width();
fieldX += d;
fieldW -= d;
}
setGeometry(fieldX, rect.y() - 1, fieldW, rect.height() + 2);
show();
setFocus();
}
*/
/* Helper functions to for
* tabOrderedRename functionality.
*/
static int nextCol (KListView *pl, QListViewItem *pi, int start, int dir)
{
if (pi)
{
// Find the next renameable column in the current row
for (; ((dir == +1) ? (start < pl->columns()) : (start >= 0)); start += dir)
if (pl->isRenameable(start))
return start;
}
return -1;
}
static QListViewItem *prevItem (QListViewItem *pi)
{
QListViewItem *pa = pi->itemAbove();
/* Does what the QListViewItem::previousSibling()
* of my dreams would do.
*/
if (pa && pa->parent() == pi->parent())
return pa;
return NULL;
}
static QListViewItem *lastQChild (QListViewItem *pi)
{
if (pi)
{
/* Since there's no QListViewItem::lastChild().
* This finds the last sibling for the given
* item.
*/
for (QListViewItem *pt = pi->nextSibling(); pt; pt = pt->nextSibling())
pi = pt;
}
return pi;
}
/*US
void KListViewLineEdit::selectNextCell (QListViewItem *pitem, int column, bool forward)
{
const int ncols = p->columns();
const int dir = forward ? +1 : -1;
const int restart = forward ? 0 : (ncols - 1);
QListViewItem *top = (pitem && pitem->parent())
? pitem->parent()->firstChild()
: p->firstChild();
QListViewItem *pi = pitem;
terminate(); // Save current changes
do
{
*/
/* Check the rest of the current row for an editable column,
* if that fails, check the entire next/previous row. The
* last case goes back to the first item in the current branch
* or the last item in the current branch depending on the
* direction.
*/
/*US
if ((column = nextCol(p, pi, column + dir, dir)) != -1 ||
(column = nextCol(p, (pi = (forward ? pi->nextSibling() : prevItem(pi))), restart, dir)) != -1 ||
(column = nextCol(p, (pi = (forward ? top : lastQChild(pitem))), restart, dir)) != -1)
{
if (pi)
{
p->setCurrentItem(pi); // Calls terminate
p->rename(pi, column);
*/
/* Some listviews may override rename() to
* prevent certain items from being renamed,
* if this is done, [m_]item will be NULL
* after the rename() call... try again.
*/
/*US
if (!item)
continue;
break;
}
}
}
while (pi && !item);
}
*/
/*US
#ifdef KeyPress
#undef KeyPress
#endif
bool KListViewLineEdit::event (QEvent *pe)
{
if (pe->type() == QEvent::KeyPress)
{
QKeyEvent *k = (QKeyEvent *) pe;
if ((k->key() == Qt::Key_Backtab || k->key() == Qt::Key_Tab) &&
p->tabOrderedRenaming() && p->itemsRenameable() &&
!(k->state() & ControlButton || k->state() & AltButton))
{
selectNextCell(item, col,
(k->key() == Key_Tab && !(k->state() & ShiftButton)));
return true;
}
}
return KLineEdit::event(pe);
}
void KListViewLineEdit::keyPressEvent(QKeyEvent *e)
{
if(e->key() == Qt::Key_Return || e->key() == Qt::Key_Enter )
terminate(true);
else if(e->key() == Qt::Key_Escape)
terminate(false);
else if (e->key() == Qt::Key_Down || e->key() == Qt::Key_Up)
{
terminate(true);
KLineEdit::keyPressEvent(e);
}
else
KLineEdit::keyPressEvent(e);
}
void KListViewLineEdit::terminate()
{
terminate(true);
}
void KListViewLineEdit::terminate(bool commit)
{
if ( item )
{
//kdDebug() << "KListViewLineEdit::terminate " << commit << endl;
if (commit)
item->setText(col, text());
int c=col;
QListViewItem *i=item;
col=0;
item=0;
hide(); // will call focusOutEvent, that's why we set item=0 before
emit done(i,c);
}
}
void KListViewLineEdit::focusOutEvent(QFocusEvent *ev)
{
QFocusEvent * focusEv = static_cast<QFocusEvent*>(ev);
// Don't let a RMB close the editor
if (focusEv->reason() != QFocusEvent::Popup && focusEv->reason() != QFocusEvent::ActiveWindow)
terminate(true);
}
void KListViewLineEdit::paintEvent( QPaintEvent *e )
{
KLineEdit::paintEvent( e );
if ( !frame() ) {
QPainter p( this );
p.setClipRegion( e->region() );
p.drawRect( rect() );
}
}
// selection changed -> terminate. As our "item" can be already deleted,
// we can't call terminate(false), because that would emit done() with
// a dangling pointer to "item".
void KListViewLineEdit::slotSelectionChanged()
{
item = 0;
col = 0;
hide();
}
*/
KListView::KListView( QWidget *parent, const char *name )
: QListView( parent, name ),
d (new KListViewPrivate (this))
{
#ifndef DESKTOP_VERSION
QPEApplication::setStylusOperation( viewport(), QPEApplication::RightOnHold );
#endif
//US setDragAutoScroll(true);
connect( this, SIGNAL( onViewport() ),
this, SLOT( slotOnViewport() ) );
connect( this, SIGNAL( onItem( QListViewItem * ) ),
this, SLOT( slotOnItem( QListViewItem * ) ) );
connect (this, SIGNAL(contentsMoving(int,int)),
this, SLOT(cleanDropVisualizer()));
connect (this, SIGNAL(contentsMoving(int,int)),
this, SLOT(cleanItemHighlighter()));
/*US
slotSettingsChanged(KApplication::SETTINGS_MOUSE);
if (kapp)
{
connect( kapp, SIGNAL( settingsChanged(int) ), SLOT( slotSettingsChanged(int) ) );
kapp->addKipcEventMask( KIPC::SettingsChanged );
}
*/
slotSettingsChanged(1); //US do this to initialize the connections
connect(&d->autoSelect, SIGNAL( timeout() ),
this, SLOT( slotAutoSelect() ) );
connect(&d->dragExpand, SIGNAL( timeout() ),
this, SLOT( slotDragExpand() ) );
// context menu handling
if (d->showContextMenusOnPress)
{
connect (this, SIGNAL (rightButtonPressed (QListViewItem*, const QPoint&, int)),
this, SLOT (emitContextMenu (QListViewItem*, const QPoint&, int)));
}
else
{
connect (this, SIGNAL (rightButtonClicked (QListViewItem*, const QPoint&, int)),
this, SLOT (emitContextMenu (QListViewItem*, const QPoint&, int)));
}
connect (this, SIGNAL (menuShortCutPressed (KListView*, QListViewItem*)),
this, SLOT (emitContextMenu (KListView*, QListViewItem*)));
//qDebug("KListView::KListView make alternate color configurable");
//US d->alternateBackground = KGlobalSettings::alternateBackgroundColor();
d->alternateBackground = QColor(240, 240, 240);
}
KListView::~KListView()
{
delete d;
}
bool KListView::isExecuteArea( const QPoint& point )
{
if ( itemAt( point ) )
return isExecuteArea( point.x() );
return false;
}
bool KListView::isExecuteArea( int x )
{
if( allColumnsShowFocus() )
return true;
else {
int offset = 0;
int width = columnWidth( 0 );
int pos = header()->mapToIndex( 0 );
for ( int index = 0; index < pos; index++ )
offset += columnWidth( header()->mapToSection( index ) );
x += contentsX(); // in case of a horizontal scrollbar
return ( x > offset && x < ( offset + width ) );
}
}
void KListView::slotOnItem( QListViewItem *item )
{
QPoint vp = viewport()->mapFromGlobal( QCursor::pos() );
if ( item && isExecuteArea( vp.x() ) && (d->autoSelectDelay > -1) && d->bUseSingle ) {
d->autoSelect.start( d->autoSelectDelay, true );
d->pCurrentItem = item;
}
}
void KListView::slotOnViewport()
{
if ( d->bChangeCursorOverItem )
viewport()->unsetCursor();
d->autoSelect.stop();
d->pCurrentItem = 0L;
}
void KListView::slotSettingsChanged(int category)
{
-qDebug("KListView::slotSettingsChanged has to be verified");
+ //qDebug("KListView::slotSettingsChanged has to be verified");
/*US
switch (category)
{
case KApplication::SETTINGS_MOUSE:
d->dragDelay = KGlobalSettings::dndEventDelay();
d->bUseSingle = KGlobalSettings::singleClick();
disconnect(this, SIGNAL (mouseButtonClicked (int, QListViewItem*, const QPoint &, int)),
this, SLOT (slotMouseButtonClicked (int, QListViewItem*, const QPoint &, int)));
if( d->bUseSingle )
connect (this, SIGNAL (mouseButtonClicked (int, QListViewItem*, const QPoint &, int)),
this, SLOT (slotMouseButtonClicked( int, QListViewItem*, const QPoint &, int)));
d->bChangeCursorOverItem = KGlobalSettings::changeCursorOverIcon();
d->autoSelectDelay = KGlobalSettings::autoSelectDelay();
if( !d->bUseSingle || !d->bChangeCursorOverItem )
viewport()->unsetCursor();
break;
case KApplication::SETTINGS_POPUPMENU:
d->contextMenuKey = KGlobalSettings::contextMenuKey ();
d->showContextMenusOnPress = KGlobalSettings::showContextMenusOnPress ();
if (d->showContextMenusOnPress)
{
disconnect (0L, 0L, this, SLOT (emitContextMenu (QListViewItem*, const QPoint&, int)));
connect(this, SIGNAL (rightButtonPressed (QListViewItem*, const QPoint&, int)),
this, SLOT (emitContextMenu (QListViewItem*, const QPoint&, int)));
}
else
{
disconnect (0L, 0L, this, SLOT (emitContextMenu (QListViewItem*, const QPoint&, int)));
connect(this, SIGNAL (rightButtonClicked (QListViewItem*, const QPoint&, int)),
this, SLOT (emitContextMenu (QListViewItem*, const QPoint&, int)));
}
break;
default:
break;
}
*/
if( d->bUseSingle )
connect (this, SIGNAL (mouseButtonClicked (int, QListViewItem*, const QPoint &, int)),
this, SLOT (slotMouseButtonClicked( int, QListViewItem*, const QPoint &, int)));
}
void KListView::slotAutoSelect()
{
// check that the item still exists
if( itemIndex( d->pCurrentItem ) == -1 )
return;
if (!isActiveWindow())
{
d->autoSelect.stop();
return;
}
//Give this widget the keyboard focus.
if( !hasFocus() )
setFocus();
QListViewItem* previousItem = currentItem();
setCurrentItem( d->pCurrentItem );
#if 0
#ifndef Q_WS_QWS
// FIXME(E): Implement for Qt Embedded
if( d->pCurrentItem ) {
//Shift pressed?
if( (keybstate & ShiftMask) ) {
bool block = signalsBlocked();
blockSignals( true );
//No Ctrl? Then clear before!
if( !(keybstate & ControlMask) )
clearSelection();
bool select = !d->pCurrentItem->isSelected();
bool update = viewport()->isUpdatesEnabled();
viewport()->setUpdatesEnabled( false );
bool down = previousItem->itemPos() < d->pCurrentItem->itemPos();
QListViewItemIterator lit( down ? previousItem : d->pCurrentItem );
for ( ; lit.current(); ++lit ) {
if ( down && lit.current() == d->pCurrentItem ) {
d->pCurrentItem->setSelected( select );
break;
}
if ( !down && lit.current() == previousItem ) {
previousItem->setSelected( select );
break;
}
lit.current()->setSelected( select );
}
blockSignals( block );
viewport()->setUpdatesEnabled( update );
triggerUpdate();
emit selectionChanged();
if( selectionMode() == QListView::Single )
emit selectionChanged( d->pCurrentItem );
}
else if( (keybstate & ControlMask) )
setSelected( d->pCurrentItem, !d->pCurrentItem->isSelected() );
else {
bool block = signalsBlocked();
blockSignals( true );
if( !d->pCurrentItem->isSelected() )
clearSelection();
blockSignals( block );
setSelected( d->pCurrentItem, true );
}
}
else
kdDebug() << "KListView::slotAutoSelect: Thats not supposed to happen!!!!" << endl;
#endif
#endif
}
void KListView::slotHeaderChanged()
{
if (d->fullWidth && columns())
{
int w = 0;
for (int i = 0; i < columns() - 1; ++i) w += columnWidth(i);
setColumnWidth( columns() - 1, viewport()->width() - w - 1 );
}
}
void KListView::emitExecute( QListViewItem *item, const QPoint &pos, int c )
{
if( isExecuteArea( viewport()->mapFromGlobal(pos) ) ) {
// Double click mode ?
if ( !d->bUseSingle )
{
emit executed( item );
emit executed( item, pos, c );
}
else
{
#if 0
#ifndef Q_WS_QWS
// FIXME(E): Implement for Qt Embedded
Window root;
Window child;
int root_x, root_y, win_x, win_y;
uint keybstate;
XQueryPointer( qt_xdisplay(), qt_xrootwin(), &root, &child,
&root_x, &root_y, &win_x, &win_y, &keybstate );
d->autoSelect.stop();
//Dont emit executed if in SC mode and Shift or Ctrl are pressed
if( !( ((keybstate & ShiftMask) || (keybstate & ControlMask)) ) ) {
emit executed( item );
emit executed( item, pos, c );
}
#endif
#endif
}
}
}
void KListView::focusInEvent( QFocusEvent *fe )
{
// kdDebug()<<"KListView::focusInEvent()"<<endl;
QListView::focusInEvent( fe );
if ((d->selectedBySimpleMove)
&& (d->selectionMode == FileManager)
&& (fe->reason()!=QFocusEvent::Popup)
&& (fe->reason()!=QFocusEvent::ActiveWindow)
&& (currentItem()!=0))
{
currentItem()->setSelected(true);
currentItem()->repaint();
emit selectionChanged();
};
}
void KListView::focusOutEvent( QFocusEvent *fe )
{
cleanDropVisualizer();
cleanItemHighlighter();
d->autoSelect.stop();
if ((d->selectedBySimpleMove)
&& (d->selectionMode == FileManager)
&& (fe->reason()!=QFocusEvent::Popup)
&& (fe->reason()!=QFocusEvent::ActiveWindow)
&& (currentItem()!=0)
/*US && (!d->editor->isVisible()) */
)
{
currentItem()->setSelected(false);
currentItem()->repaint();
emit selectionChanged();
};
QListView::focusOutEvent( fe );
}
void KListView::leaveEvent( QEvent *e )
{
d->autoSelect.stop();
QListView::leaveEvent( e );
}
bool KListView::event( QEvent *e )
{
if (e->type() == QEvent::ApplicationPaletteChange) {
qDebug("KListView::event make alternate color configurable");
//US d->alternateBackground=KGlobalSettings::alternateBackgroundColor();
d->alternateBackground = QColor(240, 240, 240);
}
return QListView::event(e);
}
void KListView::contentsMousePressEvent( QMouseEvent *e )
{
if( (selectionModeExt() == Extended) && (e->state() & ShiftButton) && !(e->state() & ControlButton) )
{
bool block = signalsBlocked();
blockSignals( true );
clearSelection();
blockSignals( block );
}
else if ((selectionModeExt()==FileManager) && (d->selectedBySimpleMove))
{
d->selectedBySimpleMove=false;
d->selectedUsingMouse=true;
if (currentItem()!=0)
{
currentItem()->setSelected(false);
currentItem()->repaint();
// emit selectionChanged();
};
};
QPoint p( contentsToViewport( e->pos() ) );
QListViewItem *at = itemAt (p);
// true if the root decoration of the item "at" was clicked (i.e. the +/- sign)
bool rootDecoClicked = at
&& ( p.x() <= header()->cellPos( header()->mapToActual( 0 ) ) +
treeStepSize() * ( at->depth() + ( rootIsDecorated() ? 1 : 0) ) + itemMargin() )
&& ( p.x() >= header()->cellPos( header()->mapToActual( 0 ) ) );
if (e->button() == LeftButton && !rootDecoClicked)
{
//Start a drag
d->startDragPos = e->pos();
if (at)
{
d->validDrag = true;
d->pressedOnSelected = at->isSelected();
}
}
QListView::contentsMousePressEvent( e );
}
void KListView::contentsMouseMoveEvent( QMouseEvent *e )
{
if (!dragEnabled() || d->startDragPos.isNull() || !d->validDrag) {
QListView::contentsMouseMoveEvent (e);
return;
}
QPoint vp = contentsToViewport(e->pos());
QListViewItem *item = itemAt( vp );
//do we process cursor changes at all?
if ( item && d->bChangeCursorOverItem && d->bUseSingle )
{
//Cursor moved on a new item or in/out the execute area
if( (item != d->pCurrentItem) ||
(isExecuteArea(vp) != d->cursorInExecuteArea) )
{
d->cursorInExecuteArea = isExecuteArea(vp);
qDebug("KListView::contentsMouseMoveEvent drag&drop not supported yet");
/*US
if( d->cursorInExecuteArea ) //cursor moved in execute area
viewport()->setCursor( KCursor::handCursor() );
else //cursor moved out of execute area
viewport()->unsetCursor();
*/
}
}
bool dragOn = dragEnabled();
QPoint newPos = e->pos();
if (dragOn && d->validDrag &&
(newPos.x() > d->startDragPos.x()+d->dragDelay ||
newPos.x() < d->startDragPos.x()-d->dragDelay ||
newPos.y() > d->startDragPos.y()+d->dragDelay ||
newPos.y() < d->startDragPos.y()-d->dragDelay))
//(d->startDragPos - e->pos()).manhattanLength() > QApplication::startDragDistance())
{
QListView::contentsMouseReleaseEvent( 0 );
startDrag();
d->startDragPos = QPoint();
d->validDrag = false;
}
}
void KListView::contentsMouseReleaseEvent( QMouseEvent *e )
{
if (e->button() == LeftButton)
{
// If the row was already selected, maybe we want to start an in-place editing
if ( d->pressedOnSelected && itemsRenameable() )
{
QPoint p( contentsToViewport( e->pos() ) );
QListViewItem *at = itemAt (p);
if ( at )
{
// true if the root decoration of the item "at" was clicked (i.e. the +/- sign)
bool rootDecoClicked =
( p.x() <= header()->cellPos( header()->mapToActual( 0 ) ) +
treeStepSize() * ( at->depth() + ( rootIsDecorated() ? 1 : 0) ) + itemMargin() )
&& ( p.x() >= header()->cellPos( header()->mapToActual( 0 ) ) );
if (!rootDecoClicked)
{
int col = header()->mapToLogical( header()->cellAt( p.x() ) );
if ( d->renameable.contains(col) )
rename(at, col);
}
}
}
d->pressedOnSelected = false;
d->validDrag = false;
d->startDragPos = QPoint();
}
QListView::contentsMouseReleaseEvent( e );
}
void KListView::contentsMouseDoubleClickEvent ( QMouseEvent *e )
{
// We don't want to call the parent method because it does setOpen,
// whereas we don't do it in single click mode... (David)
//QListView::contentsMouseDoubleClickEvent( e );
QPoint vp = contentsToViewport(e->pos());
QListViewItem *item = itemAt( vp );
emit QListView::doubleClicked( item ); // we do it now
int col = item ? header()->mapToLogical( header()->cellAt( vp.x() ) ) : -1;
if( item ) {
emit doubleClicked( item, e->globalPos(), col );
if( (e->button() == LeftButton) && !d->bUseSingle )
emitExecute( item, e->globalPos(), col );
}
}
void KListView::slotMouseButtonClicked( int btn, QListViewItem *item, const QPoint &pos, int c )
{
if( (btn == LeftButton) && item )
emitExecute(item, pos, c);
}
void KListView::contentsDropEvent(QDropEvent* e)
{
qDebug("KListView::contentsDropEvent drag&drop not supported yet");
/*US
cleanDropVisualizer();
cleanItemHighlighter();
d->dragExpand.stop();
if (acceptDrag (e))
{
e->acceptAction();
QListViewItem *afterme;
QListViewItem *parent;
findDrop(e->pos(), parent, afterme);
if (e->source() == viewport() && itemsMovable())
movableDropEvent(parent, afterme);
else
{
emit dropped(e, afterme);
emit dropped(this, e, afterme);
emit dropped(e, parent, afterme);
emit dropped(this, e, parent, afterme);
}
}
*/
}
void KListView::movableDropEvent (QListViewItem* parent, QListViewItem* afterme)
{
QPtrList<QListViewItem> items, afterFirsts, afterNows;
QListViewItem *current=currentItem();
bool hasMoved=false;
for (QListViewItem *i = firstChild(), *iNext=0; i != 0; i = iNext)
{
iNext=i->itemBelow();
if (!i->isSelected())
continue;
// don't drop an item after itself, or else
// it moves to the top of the list
if (i==afterme)
continue;
i->setSelected(false);
QListViewItem *afterFirst = i->itemAbove();
if (!hasMoved)
{
emit aboutToMove();
hasMoved=true;
}
moveItem(i, parent, afterme);
// ###### This should include the new parent !!! -> KDE 3.0
// If you need this right now, have a look at keditbookmarks.
emit moved(i, afterFirst, afterme);
items.append (i);
afterFirsts.append (afterFirst);
afterNows.append (afterme);
afterme = i;
}
clearSelection();
for (QListViewItem *i=items.first(); i != 0; i=items.next() )
i->setSelected(true);
if (current)
setCurrentItem(current);
emit moved(items,afterFirsts,afterNows);
if (firstChild())
emit moved();
}
void KListView::contentsDragMoveEvent(QDragMoveEvent *event)
{
qDebug("KListView::contentsDropEvent drag&drop not supported yet");
/*US
if (acceptDrag(event))
{
event->acceptAction();
//Clean up the view
findDrop(event->pos(), d->parentItemDrop, d->afterItemDrop);
QPoint vp = contentsToViewport( event->pos() );
QListViewItem *item = isExecuteArea( vp ) ? itemAt( vp ) : 0L;
if ( item != d->dragOverItem )
{
d->dragExpand.stop();
d->dragOverItem = item;
d->dragOverPoint = vp;
if ( d->dragOverItem && d->dragOverItem->isExpandable() && !d->dragOverItem->isOpen() )
d->dragExpand.start( QApplication::startDragTime(), true );
}
if (dropVisualizer())
{
QRect tmpRect = drawDropVisualizer(0, d->parentItemDrop, d->afterItemDrop);
if (tmpRect != d->mOldDropVisualizer)
{
cleanDropVisualizer();
d->mOldDropVisualizer=tmpRect;
viewport()->repaint(tmpRect);
}
}
if (dropHighlighter())
{
QRect tmpRect = drawItemHighlighter(0, d->afterItemDrop);
if (tmpRect != d->mOldDropHighlighter)
{
cleanItemHighlighter();
d->mOldDropHighlighter=tmpRect;
viewport()->repaint(tmpRect);
}
}
}
else
event->ignore();
*/
}
void KListView::slotDragExpand()
{
if ( itemAt( d->dragOverPoint ) == d->dragOverItem )
d->dragOverItem->setOpen( true );
}
void KListView::contentsDragLeaveEvent (QDragLeaveEvent*)
{
d->dragExpand.stop();
cleanDropVisualizer();
cleanItemHighlighter();
}
void KListView::cleanDropVisualizer()
{
if (d->mOldDropVisualizer.isValid())
{
QRect rect=d->mOldDropVisualizer;
d->mOldDropVisualizer = QRect();
viewport()->repaint(rect, true);
}
}
int KListView::depthToPixels( int depth )
{
return treeStepSize() * ( depth + (rootIsDecorated() ? 1 : 0) ) + itemMargin();
}
void KListView::findDrop(const QPoint &pos, QListViewItem *&parent, QListViewItem *&after)
{
QPoint p (contentsToViewport(pos));
// Get the position to put it in
QListViewItem *atpos = itemAt(p);
QListViewItem *above;
if (!atpos) // put it at the end
above = lastItem();
else
{
// Get the closest item before us ('atpos' or the one above, if any)
if (p.y() - itemRect(atpos).topLeft().y() < (atpos->height()/2))
above = atpos->itemAbove();
else
above = atpos;
}
if (above)
{
// Now, we know we want to go after "above". But as a child or as a sibling ?
// We have to ask the "above" item if it accepts children.
if (above->isExpandable())
{
// The mouse is sufficiently on the right ? - doesn't matter if 'above' has visible children
if (p.x() >= depthToPixels( above->depth() + 1 ) ||
(above->isOpen() && above->childCount() > 0) )
{
parent = above;
after = 0L;
return;
}
}
// Ok, there's one more level of complexity. We may want to become a new
// sibling, but of an upper-level group, rather than the "above" item
QListViewItem * betterAbove = above->parent();
QListViewItem * last = above;
while ( betterAbove )
{
// We are allowed to become a sibling of "betterAbove" only if we are
// after its last child
if ( last->nextSibling() == 0 )
{
if (p.x() < depthToPixels ( betterAbove->depth() + 1 ))
above = betterAbove; // store this one, but don't stop yet, there may be a better one
else
break; // not enough on the left, so stop
last = betterAbove;
betterAbove = betterAbove->parent(); // up one level
} else
break; // we're among the child of betterAbove, not after the last one
}
}
// set as sibling
after = above;
parent = after ? after->parent() : 0L ;
}
QListViewItem* KListView::lastChild () const
{
QListViewItem* lastchild = firstChild();
if (lastchild)
for (; lastchild->nextSibling(); lastchild = lastchild->nextSibling());
return lastchild;
}
QListViewItem *KListView::lastItem() const
{
QListViewItem* last = lastChild();
for (QListViewItemIterator it (last); it.current(); ++it)
last = it.current();
return last;
}
KLineEdit *KListView::renameLineEdit() const
{
//US return d->editor;
qDebug("KListView::renameLineEdit returns 0. Might crash");
return 0;
}
void KListView::startDrag()
{
qDebug("KListView::startDrag drag&drop not supported yet.");
/*US
QDragObject *drag = dragObject();
if (!drag)
return;
if (drag->drag() && drag->target() != viewport())
emit moved();
*/
}
QDragObject *KListView::dragObject()
{
if (!currentItem())
return 0;
return new QStoredDrag("application/x-qlistviewitem", viewport());
}
void KListView::setItemsMovable(bool b)
{
d->itemsMovable=b;
}
bool KListView::itemsMovable() const
{
return d->itemsMovable;
}
void KListView::setItemsRenameable(bool b)
{
d->itemsRenameable=b;
}
bool KListView::itemsRenameable() const
{
return d->itemsRenameable;
}
void KListView::setDragEnabled(bool b)
{
d->dragEnabled=b;
}
bool KListView::dragEnabled() const
{
return d->dragEnabled;
}
void KListView::setAutoOpen(bool b)
{
d->autoOpen=b;
}
bool KListView::autoOpen() const
{
return d->autoOpen;
}
bool KListView::dropVisualizer() const
{
return d->dropVisualizer;
}
void KListView::setDropVisualizer(bool b)
{
d->dropVisualizer=b;
}
QPtrList<QListViewItem> KListView::selectedItems() const
{
QPtrList<QListViewItem> list;
for (QListViewItem *i=firstChild(); i!=0; i=i->itemBelow())
if (i->isSelected()) list.append(i);
return list;
}
void KListView::moveItem(QListViewItem *item, QListViewItem *parent, QListViewItem *after)
{
// sanity check - don't move a item into it's own child structure
QListViewItem *i = parent;
while(i)
{
if(i == item)
return;
i = i->parent();
}
// Basically reimplementing the QListViewItem(QListViewItem*, QListViewItem*) constructor
// in here, without ever deleting the item.
if (item->parent())
item->parent()->takeItem(item);
else
takeItem(item);
if (parent)
parent->insertItem(item);
else
insertItem(item);
if (after)
;//item->moveToJustAfter(after);
}
void KListView::contentsDragEnterEvent(QDragEnterEvent *event)
{
qDebug("KListView::contentsDragEnterEvent drag&drop not supported yet.");
/*US
if (acceptDrag (event))
event->accept();
*/
}
void KListView::setDropVisualizerWidth (int w)
{
d->mDropVisualizerWidth = w > 0 ? w : 1;
}
QRect KListView::drawDropVisualizer(QPainter *p, QListViewItem *parent,
QListViewItem *after)
{
QRect insertmarker;
if (!after && !parent)
insertmarker = QRect (0, 0, viewport()->width(), d->mDropVisualizerWidth/2);
else
{
int level = 0;
if (after)
{
QListViewItem* it = 0L;
if (after->isOpen())
{
// Look for the last child (recursively)
it = after->firstChild();
if (it)
while (it->nextSibling() || it->firstChild())
if ( it->nextSibling() )
it = it->nextSibling();
else
it = it->firstChild();
}
insertmarker = itemRect (it ? it : after);
level = after->depth();
}
else if (parent)
{
insertmarker = itemRect (parent);
level = parent->depth() + 1;
}
insertmarker.setLeft( treeStepSize() * ( level + (rootIsDecorated() ? 1 : 0) ) + itemMargin() );
insertmarker.setRight (viewport()->width());
insertmarker.setTop (insertmarker.bottom() - d->mDropVisualizerWidth/2 + 1);
insertmarker.setBottom (insertmarker.bottom() + d->mDropVisualizerWidth/2);
}
// This is not used anymore, at least by KListView itself (see viewportPaintEvent)
// Remove for KDE 3.0.
if (p)
p->fillRect(insertmarker, Dense4Pattern);
return insertmarker;
}
QRect KListView::drawItemHighlighter(QPainter *painter, QListViewItem *item)
{
QRect r;
if (item)
{
r = itemRect(item);
r.setLeft(r.left()+(item->depth()+1)*treeStepSize());
if (painter) {
//US style().drawPrimitive(QStyle::PE_FocusRect, painter, r, colorGroup(),
//US QStyle::Style_FocusAtBorder, colorGroup().highlight());
const QColor* pHighl = &(colorGroup().highlight());
//LR style().drawFocusRect(painter, r, colorGroup(), pHighl, true);
qDebug("KListView::drawItemHighlighter has to be verified");
}
}
return r;
}
void KListView::cleanItemHighlighter ()
{
if (d->mOldDropHighlighter.isValid())
{
QRect rect=d->mOldDropHighlighter;
d->mOldDropHighlighter = QRect();
viewport()->repaint(rect, true);
}
}
void KListView::rename(QListViewItem *item, int c)
{
if (d->renameable.contains(c))
{
ensureItemVisible(item);
//US d->editor->load(item,c);
qDebug("KListView::rename has to be verified");
}
}
bool KListView::isRenameable (int col) const
{
return d->renameable.contains(col);
}
void KListView::setRenameable (int col, bool yesno)
{
if (col>=header()->count()) return;
d->renameable.remove(col);
if (yesno && d->renameable.find(col)==d->renameable.end())
d->renameable+=col;
else if (!yesno && d->renameable.find(col)!=d->renameable.end())
d->renameable.remove(col);
}
void KListView::doneEditing(QListViewItem *item, int row)
{
emit itemRenamed(item, item->text(row), row);
emit itemRenamed(item);
}
bool KListView::acceptDrag(QDropEvent* e) const
{
qDebug("KListView::acceptDrag drag&drop not supported yet");
//US return acceptDrops() && itemsMovable() && (e->source()==viewport());
return false;
}
void KListView::setCreateChildren(bool b)
{
d->createChildren=b;
}
bool KListView::createChildren() const
{
return d->createChildren;
}
int KListView::tooltipColumn() const
{
return d->tooltipColumn;
}
void KListView::setTooltipColumn(int column)
{
d->tooltipColumn=column;
}
void KListView::setDropHighlighter(bool b)
{
d->dropHighlighter=b;
}
bool KListView::dropHighlighter() const
{
return d->dropHighlighter;
}
bool KListView::showTooltip(QListViewItem *item, const QPoint &, int column) const
{
return ((tooltip(item, column).length()>0) && (column==tooltipColumn()));
}
QString KListView::tooltip(QListViewItem *item, int column) const
{
return item->text(column);
}
void KListView::setTabOrderedRenaming(bool b)
{
d->tabRename = b;
}
bool KListView::tabOrderedRenaming() const
{
return d->tabRename;
}
void KListView::keyPressEvent (QKeyEvent* e)
{
//don't we need a contextMenuModifier too ? (aleXXX)
if (e->key() == d->contextMenuKey)
{
emit menuShortCutPressed (this, currentItem());
return;
}
if (e->key() == Qt::Key_Delete || e->key() == Qt::Key_Backspace)
{
emit signalDelete ( );
return;
}
if (d->selectionMode != FileManager)
QListView::keyPressEvent (e);
else
fileManagerKeyPressEvent (e);
}
void KListView::activateAutomaticSelection()
{
d->selectedBySimpleMove=true;
d->selectedUsingMouse=false;
if (currentItem()!=0)
{
selectAll(false);
currentItem()->setSelected(true);
currentItem()->repaint();
emit selectionChanged();
};
}
void KListView::deactivateAutomaticSelection()
{
d->selectedBySimpleMove=false;
}
bool KListView::automaticSelection() const
{
return d->selectedBySimpleMove;
}
void KListView::fileManagerKeyPressEvent (QKeyEvent* e)
{
//don't care whether it's on the keypad or not
int e_state=(e->state() & ~Keypad);
int oldSelectionDirection(d->selectionDirection);
if ((e->key()!=Key_Shift) && (e->key()!=Key_Control)
&& (e->key()!=Key_Meta) && (e->key()!=Key_Alt))
{
if ((e_state==ShiftButton) && (!d->wasShiftEvent) && (!d->selectedBySimpleMove))
selectAll(FALSE);
d->selectionDirection=0;
d->wasShiftEvent = (e_state == ShiftButton);
};
//d->wasShiftEvent = (e_state == ShiftButton);
QListViewItem* item = currentItem();
if (item==0) return;
QListViewItem* repaintItem1 = item;
QListViewItem* repaintItem2 = 0L;
QListViewItem* visItem = 0L;
QListViewItem* nextItem = 0L;
int items = 0;
bool shiftOrCtrl((e_state==ControlButton) || (e_state==ShiftButton));
int selectedItems(0);
for (QListViewItem *tmpItem=firstChild(); tmpItem!=0; tmpItem=tmpItem->nextSibling())
if (tmpItem->isSelected()) selectedItems++;
if (((selectedItems==0) || ((selectedItems==1) && (d->selectedUsingMouse)))
&& (e_state==NoButton)
&& ((e->key()==Key_Down)
|| (e->key()==Key_Up)
|| (e->key()==Key_Next)
|| (e->key()==Key_Prior)
|| (e->key()==Key_Home)
|| (e->key()==Key_End)))
{
d->selectedBySimpleMove=true;
d->selectedUsingMouse=false;
}
else if (selectedItems>1)
d->selectedBySimpleMove=false;
bool emitSelectionChanged(false);
switch (e->key())
{
case Key_Escape:
selectAll(FALSE);
emitSelectionChanged=TRUE;
break;
case Key_Space:
//toggle selection of current item
if (d->selectedBySimpleMove)
d->selectedBySimpleMove=false;
item->setSelected(!item->isSelected());
emitSelectionChanged=TRUE;
break;
case Key_Insert:
//toggle selection of current item and move to the next item
if (d->selectedBySimpleMove)
{
d->selectedBySimpleMove=false;
if (!item->isSelected()) item->setSelected(TRUE);
}
else
{
item->setSelected(!item->isSelected());
};
nextItem=item->itemBelow();
if (nextItem!=0)
{
repaintItem2=nextItem;
visItem=nextItem;
setCurrentItem(nextItem);
};
d->selectionDirection=1;
emitSelectionChanged=TRUE;
break;
case Key_Down:
nextItem=item->itemBelow();
//toggle selection of current item and move to the next item
if (shiftOrCtrl)
{
d->selectionDirection=1;
if (d->selectedBySimpleMove)
d->selectedBySimpleMove=false;
else
{
if (oldSelectionDirection!=-1)
{
item->setSelected(!item->isSelected());
emitSelectionChanged=TRUE;
};
};
}
else if ((d->selectedBySimpleMove) && (nextItem!=0))
{
item->setSelected(false);
emitSelectionChanged=TRUE;
};
if (nextItem!=0)
{
if (d->selectedBySimpleMove)
nextItem->setSelected(true);
repaintItem2=nextItem;
visItem=nextItem;
setCurrentItem(nextItem);
};
break;
case Key_Up:
nextItem=item->itemAbove();
d->selectionDirection=-1;
//move to the prev. item and toggle selection of this one
// => No, can't select the last item, with this. For symmetry, let's
// toggle selection and THEN move up, just like we do in down (David)
if (shiftOrCtrl)
{
if (d->selectedBySimpleMove)
d->selectedBySimpleMove=false;
else
{
if (oldSelectionDirection!=1)
{
item->setSelected(!item->isSelected());
emitSelectionChanged=TRUE;
};
}
}
else if ((d->selectedBySimpleMove) && (nextItem!=0))
{
item->setSelected(false);
emitSelectionChanged=TRUE;
};
if (nextItem!=0)
{
if (d->selectedBySimpleMove)
nextItem->setSelected(true);
repaintItem2=nextItem;
visItem=nextItem;
setCurrentItem(nextItem);
};
break;
case Key_End:
//move to the last item and toggle selection of all items inbetween
nextItem=item;
if (d->selectedBySimpleMove)
item->setSelected(false);
if (shiftOrCtrl)
d->selectedBySimpleMove=false;
while(nextItem!=0)
{
if (shiftOrCtrl)
nextItem->setSelected(!nextItem->isSelected());
if (nextItem->itemBelow()==0)
{
if (d->selectedBySimpleMove)
nextItem->setSelected(true);
repaintItem2=nextItem;
visItem=nextItem;
setCurrentItem(nextItem);
}
nextItem=nextItem->itemBelow();
}
emitSelectionChanged=TRUE;
break;
case Key_Home:
// move to the first item and toggle selection of all items inbetween
nextItem = firstChild();
visItem = nextItem;
repaintItem2 = visItem;
if (d->selectedBySimpleMove)
item->setSelected(false);
if (shiftOrCtrl)
{
d->selectedBySimpleMove=false;
while ( nextItem != item )
{
nextItem->setSelected( !nextItem->isSelected() );
nextItem = nextItem->itemBelow();
}
item->setSelected( !item->isSelected() );
}
setCurrentItem( firstChild() );
emitSelectionChanged=TRUE;
break;
case Key_Next:
items=visibleHeight()/item->height();
nextItem=item;
if (d->selectedBySimpleMove)
item->setSelected(false);
if (shiftOrCtrl)
{
d->selectedBySimpleMove=false;
d->selectionDirection=1;
};
for (int i=0; i<items; i++)
{
if (shiftOrCtrl)
nextItem->setSelected(!nextItem->isSelected());
//the end
if ((i==items-1) || (nextItem->itemBelow()==0))
{
if (shiftOrCtrl)
nextItem->setSelected(!nextItem->isSelected());
if (d->selectedBySimpleMove)
nextItem->setSelected(true);
ensureItemVisible(nextItem);
setCurrentItem(nextItem);
update();
if ((shiftOrCtrl) || (d->selectedBySimpleMove))
{
emit selectionChanged();
}
return;
}
nextItem=nextItem->itemBelow();
}
break;
case Key_Prior:
items=visibleHeight()/item->height();
nextItem=item;
if (d->selectedBySimpleMove)
item->setSelected(false);
if (shiftOrCtrl)
{
d->selectionDirection=-1;
d->selectedBySimpleMove=false;
};
for (int i=0; i<items; i++)
{
if ((nextItem!=item) &&(shiftOrCtrl))
nextItem->setSelected(!nextItem->isSelected());
//the end
if ((i==items-1) || (nextItem->itemAbove()==0))
{
if (d->selectedBySimpleMove)
nextItem->setSelected(true);
ensureItemVisible(nextItem);
setCurrentItem(nextItem);
update();
if ((shiftOrCtrl) || (d->selectedBySimpleMove))
{
emit selectionChanged();
}
return;
}
nextItem=nextItem->itemAbove();
}
break;
case Key_Minus:
if ( item->isOpen() )
setOpen( item, FALSE );
break;
case Key_Plus:
if ( !item->isOpen() && (item->isExpandable() || item->childCount()) )
setOpen( item, TRUE );
break;
default:
bool realKey = ((e->key()!=Key_Shift) && (e->key()!=Key_Control)
&& (e->key()!=Key_Meta) && (e->key()!=Key_Alt));
bool selectCurrentItem = (d->selectedBySimpleMove) && (item->isSelected());
if (realKey && selectCurrentItem)
item->setSelected(false);
//this is mainly for the "goto filename beginning with pressed char" feature (aleXXX)
QListView::SelectionMode oldSelectionMode = selectionMode();
setSelectionMode (QListView::Multi);
QListView::keyPressEvent (e);
setSelectionMode (oldSelectionMode);
if (realKey && selectCurrentItem)
{
currentItem()->setSelected(true);
emitSelectionChanged=TRUE;
}
repaintItem2=currentItem();
if (realKey)
visItem=currentItem();
break;
}
if (visItem)
ensureItemVisible(visItem);
QRect ir;
if (repaintItem1)
ir = ir.unite( itemRect(repaintItem1) );
if (repaintItem2)
ir = ir.unite( itemRect(repaintItem2) );
if ( !ir.isEmpty() )
{ // rectangle to be repainted
if ( ir.x() < 0 )
ir.moveBy( -ir.x(), 0 );
viewport()->repaint( ir, FALSE );
}
/*if (repaintItem1)
repaintItem1->repaint();
if (repaintItem2)
repaintItem2->repaint();*/
update();
if (emitSelectionChanged)
emit selectionChanged();
}
void KListView::setSelectionModeExt (SelectionModeExt mode)
{
d->selectionMode = mode;
switch (mode)
{
case Single:
case Multi:
case Extended:
case NoSelection:
setSelectionMode (static_cast<QListView::SelectionMode>(static_cast<int>(mode)));
break;
case FileManager:
setSelectionMode (QListView::Extended);
break;
default:
kdWarning () << "Warning: illegal selection mode " << int(mode) << " set!" << endl;
break;
}
}
KListView::SelectionModeExt KListView::selectionModeExt () const
{
return d->selectionMode;
}
int KListView::itemIndex( const QListViewItem *item ) const
{
if ( !item )
return -1;
if ( item == firstChild() )
return 0;
else {
QListViewItemIterator it(firstChild());
uint j = 0;
for (; it.current() && it.current() != item; ++it, ++j );
if( !it.current() )
return -1;
return j;
}
}
QListViewItem* KListView::itemAtIndex(int index)
{
if (index<0)
return 0;
int j(0);
for (QListViewItemIterator it=firstChild(); it.current(); it++)
{
if (j==index)
return it.current();
j++;
};
return 0;
}
void KListView::emitContextMenu (KListView*, QListViewItem* i)
{
QPoint p;
qDebug("KListView::emitContextMenu ");
if (i)
p = viewport()->mapToGlobal(itemRect(i).center());
else
p = mapToGlobal(rect().center());
emit contextMenu (this, i, p);
}
void KListView::emitContextMenu (QListViewItem* i, const QPoint& p, int)
{
qDebug("KListView::emitContextMenu ");
emit contextMenu (this, i, p);
}
void KListView::setAcceptDrops (bool val)
{
QListView::setAcceptDrops (val);
viewport()->setAcceptDrops (val);
}
int KListView::dropVisualizerWidth () const
{
return d->mDropVisualizerWidth;
}
void KListView::viewportPaintEvent(QPaintEvent *e)
{
QListView::viewportPaintEvent(e);
if (d->mOldDropVisualizer.isValid() && e->rect().intersects(d->mOldDropVisualizer))
{
QPainter painter(viewport());
// This is where we actually draw the drop-visualizer
painter.fillRect(d->mOldDropVisualizer, Dense4Pattern);
}
if (d->mOldDropHighlighter.isValid() && e->rect().intersects(d->mOldDropHighlighter))
{
QPainter painter(viewport());
qDebug("KListView::viewportPaintEvent has to be verified");
// This is where we actually draw the drop-highlighter
//US style().drawPrimitive(QStyle::PE_FocusRect, &painter, d->mOldDropHighlighter, colorGroup(),
//US QStyle::Style_FocusAtBorder);
//LR style().drawFocusRect(&painter, d->mOldDropHighlighter, colorGroup(), (const QColor*)0, true);
}
}
void KListView::setFullWidth()
{
setFullWidth(true);
}
void KListView::setFullWidth(bool fullWidth)
{
d->fullWidth = fullWidth;
//US header()->setStretchEnabled(fullWidth, columns()-1);
}
bool KListView::fullWidth() const
{
return d->fullWidth;
}
int KListView::addColumn(const QString& label, int width)
{
int result = QListView::addColumn(label, width);
if (d->fullWidth) {
//US header()->setStretchEnabled(false, columns()-2);
//US header()->setStretchEnabled(true, columns()-1);
}
return result;
}
int KListView::addColumn(const QIconSet& iconset, const QString& label, int width)
{
int result = QListView::addColumn(iconset, label, width);
if (d->fullWidth) {
//US header()->setStretchEnabled(false, columns()-2);
//US header()->setStretchEnabled(true, columns()-1);
}
return result;
}
void KListView::removeColumn(int index)
{
QListView::removeColumn(index);
//US if (d->fullWidth && index == columns()) header()->setStretchEnabled(true, columns()-1);
}
void KListView::viewportResizeEvent(QResizeEvent* e)
{
QListView::viewportResizeEvent(e);
}
const QColor &KListView::alternateBackground() const
{
return d->alternateBackground;
}
void KListView::setAlternateBackground(const QColor &c)
{
d->alternateBackground = c;
repaint();
}
void KListView::saveLayout(KConfig *config, const QString &group) const
{
KConfigGroupSaver saver(config, group);
QStringList widths, order;
for (int i = 0; i < columns(); ++i)
{
widths << QString::number(columnWidth(i));
order << QString::number(header()->mapToIndex(i));
}
config->writeEntry("ColumnWidths", widths);
config->writeEntry("ColumnOrder", order);
config->writeEntry("SortColumn", d->sortColumn);
config->writeEntry("SortAscending", d->sortAscending);
}
void KListView::restoreLayout(KConfig *config, const QString &group)
{
KConfigGroupSaver saver(config, group);
QStringList cols = config->readListEntry("ColumnWidths");
int i = 0;
for (QStringList::ConstIterator it = cols.begin(); it != cols.end(); ++it)
setColumnWidth(i++, (*it).toInt());
cols = config->readListEntry("ColumnOrder");
i = 0;
for (QStringList::ConstIterator it = cols.begin(); it != cols.end(); ++it)
header()->moveSection(i++, (*it).toInt());
/*US I changed the following code, because hasKey is not available.
!!! check if my version is correct
if (config->hasKey("SortColumn"))
setSorting(config->readNumEntry("SortColumn"), config->readBoolEntry("SortAscending", true));
*/
QStringList langLst = config->readListEntry( "SortColumn" );
if (!langLst.isEmpty())
setSorting(config->readNumEntry("SortColumn"), config->readBoolEntry("SortAscending", true));
}
void KListView::setSorting(int column, bool ascending)
{
d->sortColumn = column;
d->sortAscending = ascending;
QListView::setSorting(column, ascending);
}
int KListView::columnSorted(void) const
{
return d->sortColumn;
}
bool KListView::ascendingSort(void) const
{
return d->sortAscending;
}
KListViewItem::KListViewItem(QListView *parent)
: QListViewItem(parent)
{
init();
}
KListViewItem::KListViewItem(QListViewItem *parent)
: QListViewItem(parent)
{
init();
}
KListViewItem::KListViewItem(QListView *parent, QListViewItem *after)
: QListViewItem(parent, after)
{
init();
}
KListViewItem::KListViewItem(QListViewItem *parent, QListViewItem *after)
: QListViewItem(parent, after)
{
init();
}
KListViewItem::KListViewItem(QListView *parent,
QString label1, QString label2, QString label3, QString label4,
QString label5, QString label6, QString label7, QString label8)
: QListViewItem(parent, label1, label2, label3, label4, label5, label6, label7, label8)
{
init();
}
KListViewItem::KListViewItem(QListViewItem *parent,
QString label1, QString label2, QString label3, QString label4,
QString label5, QString label6, QString label7, QString label8)
: QListViewItem(parent, label1, label2, label3, label4, label5, label6, label7, label8)
{
init();
}
KListViewItem::KListViewItem(QListView *parent, QListViewItem *after,
QString label1, QString label2, QString label3, QString label4,
QString label5, QString label6, QString label7, QString label8)
: QListViewItem(parent, after, label1, label2, label3, label4, label5, label6, label7, label8)
{
init();
}
KListViewItem::KListViewItem(QListViewItem *parent, QListViewItem *after,
QString label1, QString label2, QString label3, QString label4,
QString label5, QString label6, QString label7, QString label8)
: QListViewItem(parent, after, label1, label2, label3, label4, label5, label6, label7, label8)
{
init();
}
KListViewItem::~KListViewItem()
{
}
void KListViewItem::init()
{
m_known = false;
}
const QColor &KListViewItem::backgroundColor()
{
if (isAlternate())
return static_cast< KListView* >(listView())->alternateBackground();
return listView()->viewport()->colorGroup().base();
}
bool KListViewItem::isAlternate()
{
KListView *lv = static_cast<KListView *>(listView());
if (lv && lv->alternateBackground().isValid())
{
KListViewItem *above = 0;
//US above = dynamic_cast<KListViewItem *>(itemAbove());
above = (KListViewItem *)(itemAbove());
m_known = above ? above->m_known : true;
if (m_known)
{
m_odd = above ? !above->m_odd : false;
}
else
{
KListViewItem *item;
bool previous = true;
if (parent())
{
//US item = dynamic_cast<KListViewItem *>(parent());
item = (KListViewItem *)(parent());
if (item)
previous = item->m_odd;
//US item = dynamic_cast<KListViewItem *>(parent()->firstChild());
item = (KListViewItem *)(parent()->firstChild());
}
else
{
//US item = dynamic_cast<KListViewItem *>(lv->firstChild());
item = (KListViewItem *)(lv->firstChild());
}
while(item)
{
item->m_odd = previous = !previous;
item->m_known = true;
//US item = dynamic_cast<KListViewItem *>(item->nextSibling());
item = (KListViewItem *)(item->nextSibling());
}
}
return m_odd;
}
return false;
}
void KListViewItem::paintCell(QPainter *p, const QColorGroup &cg, int column, int width, int alignment)
{
QColorGroup _cg = cg;
const QPixmap *pm = listView()->viewport()->backgroundPixmap();
if (pm && !pm->isNull())
{
_cg.setBrush(QColorGroup::Base, QBrush(backgroundColor(), *pm));
QPoint o = p->brushOrigin();
p->setBrushOrigin( o.x()-listView()->contentsX(), o.y()-listView()->contentsY() );
}
else if (isAlternate()) {
//US if (listView()->viewport()->backgroundMode()==Qt::FixedColor)
if (listView()->viewport()->backgroundMode()==QWidget::PaletteBackground)
_cg.setColor(QColorGroup::Background, static_cast< KListView* >(listView())->alternateBackground());
else
_cg.setColor(QColorGroup::Base, static_cast< KListView* >(listView())->alternateBackground());
}
QListViewItem::paintCell(p, _cg, column, width, alignment);
}
void KListView::virtual_hook( int, void* )
{ /*BASE::virtual_hook( id, data );*/ }
//US #include "klistview.moc"
//US #include "klistviewlineedit.moc"
// vim: ts=2 sw=2 et