113 files changed, 536 insertions, 531 deletions
diff --git a/core/applets/cardmon/cardmon.cpp b/core/applets/cardmon/cardmon.cpp index 7625545..e8072c6 100644 --- a/core/applets/cardmon/cardmon.cpp +++ b/core/applets/cardmon/cardmon.cpp @@ -1,253 +1,253 @@ /* * cardmon.cpp * * --------------------- * * copyright : (c) 2002 by Maximilian Reiss * email : max.reiss@gmx.de * based on two apps by Devin Butterfield */ /*************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #include "cardmon.h" /* OPIE */ #include <opie2/odevice.h> #include <opie2/otaskbarapplet.h> #include <qpe/applnk.h> #include <qpe/resource.h> /* QT */ #include <qcopchannel_qws.h> #include <qpainter.h> #include <qfile.h> #include <qtextstream.h> #include <qsound.h> #include <qtimer.h> /* STD */ #include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <string.h> #include <fcntl.h> #if defined(_OS_LINUX_) || defined(Q_OS_LINUX) #include <sys/vfs.h> #include <mntent.h> #endif using namespace Opie; CardMonitor::CardMonitor( QWidget * parent ) : QWidget( parent ), pm( Resource::loadPixmap( "cardmon/pcmcia" ) ) { QCopChannel * pcmciaChannel = new QCopChannel( "QPE/Card", this ); connect( pcmciaChannel, - SIGNAL( received( const QCString &, const QByteArray & ) ), this, - SLOT( cardMessage( const QCString &, const QByteArray & ) ) ); + SIGNAL( received(const QCString&,const QByteArray&) ), this, + SLOT( cardMessage(const QCString&,const QByteArray&) ) ); QCopChannel *sdChannel = new QCopChannel( "QPE/Card", this ); connect( sdChannel, - SIGNAL( received( const QCString &, const QByteArray & ) ), this, - SLOT( cardMessage( const QCString &, const QByteArray & ) ) ); + SIGNAL( received(const QCString&,const QByteArray&) ), this, + SLOT( cardMessage(const QCString&,const QByteArray&) ) ); cardInPcmcia0 = FALSE; cardInPcmcia1 = FALSE; cardInSd = FALSE; setFocusPolicy( NoFocus ); setFixedWidth ( AppLnk::smallIconSize() ); setFixedHeight ( AppLnk::smallIconSize() ); getStatusPcmcia( TRUE ); getStatusSd( TRUE ); repaint( FALSE ); popupMenu = 0; } CardMonitor::~CardMonitor() { if ( popupMenu ) { delete popupMenu; } } void CardMonitor::popUp( QString message, QString icon ) { if ( !popupMenu ) { popupMenu = new QPopupMenu( this ); } popupMenu->clear(); if ( icon.isEmpty() ) { popupMenu->insertItem( message, 0 ); } else { popupMenu->insertItem( QIconSet( Resource::loadPixmap( icon ) ), message, 0 ); } QPoint p = mapToGlobal( QPoint( 0, 0 ) ); QSize s = popupMenu->sizeHint(); popupMenu->popup( QPoint( p.x() + ( width() / 2 ) - ( s.width() / 2 ), p.y() - s.height() ), 0 ); QTimer::singleShot( 2000, this, SLOT( popupTimeout() ) ); } void CardMonitor::popupTimeout() { popupMenu->hide(); } void CardMonitor::mousePressEvent( QMouseEvent * ) { QPopupMenu * menu = new QPopupMenu( this ); QString cmd; int err = 0; if ( cardInSd ) { menu->insertItem( QIconSet( Resource::loadPixmap( "cardmon/ide" ) ), tr( "Eject SD/MMC card" ), 0 ); } if ( cardInPcmcia0 ) { menu-> insertItem( QIconSet ( Resource::loadPixmap( "cardmon/" + cardInPcmcia0Type ) ), tr( "Eject card 0: %1" ).arg( cardInPcmcia0Name ), 1 ); } if ( cardInPcmcia1 ) { menu-> insertItem( QIconSet ( Resource::loadPixmap( "cardmon/" + cardInPcmcia1Type ) ), tr( "Eject card 1: %1" ).arg( cardInPcmcia1Name ), 2 ); } QPoint p = mapToGlobal( QPoint( 0, 0 ) ); QSize s = menu->sizeHint(); int opt = menu->exec( QPoint( p.x() + ( width() / 2 ) - ( s.width() / 2 ), p.y() - s.height() ), 0 ); if ( opt == 1 ) { cmd = "/sbin/cardctl eject 0"; err = system( ( const char * ) cmd ); if ( err != 0 ) { qDebug( "Could not execute `/sbin/cardctl eject 0'! err=%d", err ); popUp( tr( "CF/PCMCIA card eject failed!" ) ); } } else if ( opt == 0 ) { if ( ODevice::inst() ->system() == System_Familiar ) { cmd = "umount /dev/mmc/part1"; } else { cmd = "umount /dev/mmcda1"; } err = system( ( const char * ) cmd ); if ( err != 0 ) { popUp( tr( "SD/MMC card eject failed!" ) ); } } else if ( opt == 2 ) { cmd = "/sbin/cardctl eject 1"; err = system( ( const char * ) cmd ); if ( err != 0 ) { qDebug( "Could not execute `/sbin/cardctl eject 1'! err=%d", err ); popUp( tr( "CF/PCMCIA card eject failed!" ) ); } } delete menu; } void CardMonitor::cardMessage( const QCString & msg, const QByteArray & ) { if ( msg == "stabChanged()" ) { // qDebug("Pcmcia: stabchanged"); getStatusPcmcia(); } else if ( msg == "mtabChanged()" ) { // qDebug("CARDMONAPPLET: mtabchanged"); getStatusSd(); } } bool CardMonitor::getStatusPcmcia( int showPopUp ) { bool cardWas0 = cardInPcmcia0; // remember last state bool cardWas1 = cardInPcmcia1; QString fileName; // one of these 3 files should exist if ( QFile::exists( "/var/run/stab" ) ) { fileName = "/var/run/stab"; } else if ( QFile::exists( "/var/state/pcmcia/stab" ) ) { fileName = "/var/state/pcmcia/stab"; } else { fileName = "/var/lib/pcmcia/stab"; } QFile f( fileName ); if ( f.open( IO_ReadOnly ) ) { QStringList list; QTextStream stream( &f ); QString streamIn; streamIn = stream.read(); list = QStringList::split( "\n", streamIn ); for ( QStringList::Iterator line = list.begin(); line != list.end(); line++ ) { if ( ( *line ).startsWith( "Socket 0:" ) ) { if ( ( *line ).startsWith( "Socket 0: empty" ) && cardInPcmcia0 ) { cardInPcmcia0 = FALSE; } else if ( !( *line ).startsWith( "Socket 0: empty" ) && !cardInPcmcia0 ) { cardInPcmcia0Name = ( *line ).mid( ( ( *line ).find( ':' ) + 1 ), ( *line ).length() - 9 ); cardInPcmcia0Name.stripWhiteSpace(); cardInPcmcia0 = TRUE; diff --git a/core/applets/clipboardapplet/clipboard.cpp b/core/applets/clipboardapplet/clipboard.cpp index 34d151e..4fc8076 100644 --- a/core/applets/clipboardapplet/clipboard.cpp +++ b/core/applets/clipboardapplet/clipboard.cpp @@ -1,189 +1,189 @@ /********************************************************************** ** Copyright (C) 2000 Trolltech AS. All rights reserved. ** ** This file is part of Qtopia Environment. ** ** This file may be distributed and/or modified under the terms of the ** GNU General Public License version 2 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. ** ** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE ** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. ** ** See http://www.trolltech.com/gpl/ for GPL licensing information. ** ** Contact info@trolltech.com if any conditions of this licensing are ** not clear to you. ** **********************************************************************/ #include "clipboard.h" #include <opie2/otaskbarapplet.h> #include <qpe/resource.h> #include <qpe/applnk.h> #include <qpainter.h> #include <qpopupmenu.h> #include <qwindowsystem_qws.h> #include <qapplication.h> #include <qclipboard.h> #include <qtimer.h> //=========================================================================== ClipboardApplet::ClipboardApplet( QWidget *parent, const char *name ) : QWidget( parent, name ) { setFixedWidth ( AppLnk::smallIconSize() ); setFixedHeight ( AppLnk::smallIconSize() ); QImage img = Resource::loadImage( "paste"); img = img.smoothScale( AppLnk::smallIconSize(), AppLnk::smallIconSize() ); m_clipboardPixmap.convertFromImage( img ); m_timer = new QTimer ( this ); - connect ( QApplication::clipboard ( ), SIGNAL( dataChanged ( )), this, SLOT( newData ( ))); - connect ( m_timer, SIGNAL( timeout ( )), this, SLOT( newData ( ))); - connect ( qApp, SIGNAL( aboutToQuit ( )), this, SLOT( shutdown ( ))); + connect ( QApplication::clipboard ( ), SIGNAL( dataChanged()), this, SLOT( newData())); + connect ( m_timer, SIGNAL( timeout()), this, SLOT( newData())); + connect ( qApp, SIGNAL( aboutToQuit()), this, SLOT( shutdown())); m_menu = 0; m_dirty = true; m_lasttext = QString::null; m_timer-> start ( 0, true ); } ClipboardApplet::~ClipboardApplet ( ) { } int ClipboardApplet::position() { return 6; } void ClipboardApplet::shutdown ( ) { // the timer has to be stopped, or Qt/E will hang on quit() // see launcher/desktop.cpp m_timer-> stop ( ); } void ClipboardApplet::mousePressEvent ( QMouseEvent *) { if ( m_dirty ) { delete m_menu; m_menu = new QPopupMenu ( this ); m_menu-> setCheckable ( true ); if ( m_history. count ( )) { for ( unsigned int i = 0; i < m_history. count ( ); i++ ) { QString str = m_history [i]; if ( str. length ( ) > 20 ) str = str. left ( 20 ) + "..."; m_menu-> insertItem ( QString ( "%1: %2" ). arg ( i + 1 ). arg ( str ), i ); m_menu-> setItemChecked ( i, false ); } m_menu-> setItemChecked ( m_history. count ( ) - 1, true ); m_menu-> insertSeparator ( ); } m_menu-> insertItem ( QIconSet ( Resource::loadPixmap ( "cut" )), tr( "Cut" ), 100 ); m_menu-> insertItem ( QIconSet ( Resource::loadPixmap ( "copy" )), tr( "Copy" ), 101 ); m_menu-> insertItem ( QIconSet ( Resource::loadPixmap ( "paste" )), tr( "Paste" ), 102 ); - connect ( m_menu, SIGNAL( activated ( int )), this, SLOT( action ( int ))); + connect ( m_menu, SIGNAL( activated(int)), this, SLOT( action(int))); m_dirty = false; } QPoint p = mapToGlobal ( QPoint ( 0, 0 )); QSize s = m_menu-> sizeHint ( ); m_menu-> popup ( QPoint ( p. x ( ) + ( width ( ) / 2 ) - ( s. width ( ) / 2 ), p. y ( ) - s. height ( ))); } void ClipboardApplet::action(int id) { ushort unicode = 0; int scan = 0; switch ( id ) { case 100: unicode = 'X' - '@'; scan = Key_X; // Cut break; case 101: unicode = 'C' - '@'; scan = Key_C; // Copy break; case 102: unicode = 'V' - '@'; scan = Key_V; // Paste break; default: if (( id >= 0 ) && ( uint( id ) < m_history. count ( ))) { QApplication::clipboard ( )-> setText ( m_history [id] ); for ( uint i = 0; i < m_history. count ( ); i++ ) m_menu-> setItemChecked ( i, i == uint( id )); unicode = 'V' - '@'; scan = Key_V; } break; } if ( scan ) { qwsServer-> sendKeyEvent ( unicode, scan, ControlButton, true, false ); qwsServer-> sendKeyEvent ( unicode, scan, ControlButton, false, false ); } } void ClipboardApplet::paintEvent ( QPaintEvent* ) { QPainter p ( this ); /* center the height but our pixmap is as big as the height ;)*/ p. drawPixmap( 0, 0, m_clipboardPixmap ); } void ClipboardApplet::newData ( ) { static bool excllock = false; if ( excllock ) return; else excllock = true; m_timer-> stop ( ); QCString type = "plain"; QString txt = QApplication::clipboard ( )-> text ( type ); if ( !txt. isEmpty ( ) && !m_history. contains ( txt )) { m_history. append ( txt ); if ( m_history. count ( ) > 5 ) m_history. remove ( m_history. begin ( )); m_dirty = true; } m_timer-> start ( 1500, true ); excllock = false; } Q_EXPORT_INTERFACE() { Q_CREATE_INSTANCE( OTaskbarAppletWrapper<ClipboardApplet> ); } diff --git a/core/applets/clockapplet/clock.cpp b/core/applets/clockapplet/clock.cpp index 9fead03..120a019 100644 --- a/core/applets/clockapplet/clock.cpp +++ b/core/applets/clockapplet/clock.cpp @@ -1,121 +1,121 @@ /********************************************************************** ** Copyright (C) 2000 Trolltech AS. All rights reserved. ** ** This file is part of Qtopia Environment. ** ** This file may be distributed and/or modified under the terms of the ** GNU General Public License version 2 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. ** ** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE ** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. ** ** See http://www.trolltech.com/gpl/ for GPL licensing information. ** ** Contact info@trolltech.com if any conditions of this licensing are ** not clear to you. ** **********************************************************************/ #include "clock.h" #include <opie2/otaskbarapplet.h> #include <qpe/qpeapplication.h> #include <qpe/qcopenvelope_qws.h> #include <qpe/config.h> LauncherClock::LauncherClock( QWidget *parent ) : QLabel( parent ) { // If you want a sunken border around the clock do this: // setFrameStyle( QFrame::Panel | QFrame::Sunken ); //setFont( QFont( "Helvetica", , QFont::Normal ) ); - connect( qApp, SIGNAL( timeChanged() ), this, SLOT( updateTime( ) ) ); - connect( qApp, SIGNAL( clockChanged( bool ) ), - this, SLOT( slotClockChanged( bool ) ) ); + connect( qApp, SIGNAL( timeChanged() ), this, SLOT( updateTime() ) ); + connect( qApp, SIGNAL( clockChanged(bool) ), + this, SLOT( slotClockChanged(bool) ) ); readConfig(); timerId = 0; timerEvent( 0 ); show(); } int LauncherClock::position() { return 10; } void LauncherClock::readConfig() { Config config( "qpe" ); config.setGroup( "Time" ); ampmFormat = config.readBoolEntry( "AMPM", TRUE ); config.setGroup( "Date" ); format = config.readNumEntry("ClockApplet",0); } void LauncherClock::mouseReleaseEvent( QMouseEvent * ) { QCString setTimeApp; setTimeApp="systemtime"; QCopEnvelope e("QPE/Application/"+setTimeApp, "raise()"); } void LauncherClock::timerEvent( QTimerEvent *e ) { if ( !e || e->timerId() == timerId ) { killTimer( timerId ); changeTime(); QTime t = QTime::currentTime(); int ms = (60 - t.second())*1000 - t.msec(); timerId = startTimer( ms ); } else { QLabel::timerEvent( e ); } } void LauncherClock::updateTime( void ) { changeTime(); } void LauncherClock::changeTime( void ) { QTime tm = QDateTime::currentDateTime().time(); QString s; if( ampmFormat ) { int hour = tm.hour(); if (hour == 0) hour = 12; if (hour > 12) hour -= 12; s.sprintf( "%2d:%02d %s", hour, tm.minute(), (tm.hour() >= 12) ? "PM" : "AM" ); } else s.sprintf( "%2d:%02d", tm.hour(), tm.minute() ); if (format==1) { QDate dm = QDate::currentDate(); QString d; d.sprintf("%d/%d ", dm.day(), dm.month()); setText( d+s ); } else if (format==2) { QDate dm = QDate::currentDate(); QString d; d.sprintf("%d/%d ", dm.month(), dm.day()); setText( d+s ); } else { setText( s ); } } void LauncherClock::slotClockChanged( bool pm ) { readConfig(); updateTime(); } Q_EXPORT_INTERFACE() { Q_CREATE_INSTANCE( OTaskbarAppletWrapper<LauncherClock> ); } diff --git a/core/applets/irdaapplet/irda.cpp b/core/applets/irdaapplet/irda.cpp index afc0592..dde8050 100644 --- a/core/applets/irdaapplet/irda.cpp +++ b/core/applets/irdaapplet/irda.cpp @@ -1,292 +1,292 @@ /********************************************************************** ** Copyright (C) 2002 David Woodhouse <dwmw2@infradead.org> ** Max Reiss <harlekin@handhelds.org> [trivial stuff] ** Robert Griebl <sandman@handhelds.org> ** Holger Freyther <zecke@handhelds.org> QCOP Interface ** ** This file may be distributed and/or modified under the terms of the ** GNU General Public License version 2 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. ** ** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE ** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. ** **********************************************************************/ #include "irda.h" /* OPIE */ #include <opie2/otaskbarapplet.h> #include <qpe/resource.h> #include <qpe/qcopenvelope_qws.h> /* QT */ #include <qpainter.h> #include <qfile.h> #include <qtimer.h> #include <qtextstream.h> /* STD */ #include <unistd.h> #include <net/if.h> #include <netinet/in.h> #include <sys/types.h> #include <sys/socket.h> #include <sys/ioctl.h> //=========================================================================== IrdaApplet::IrdaApplet ( QWidget *parent, const char *name ) : QWidget ( parent, name ) { setFixedHeight ( 18 ); setFixedWidth ( 14 ); m_sockfd = ::socket ( PF_INET, SOCK_DGRAM, IPPROTO_IP ); m_irdaOnPixmap = Resource::loadPixmap( "irdaapplet/irdaon" ); m_irdaOffPixmap = Resource::loadPixmap( "irdaapplet/irdaoff" ); m_irdaDiscoveryOnPixmap = Resource::loadPixmap( "irdaapplet/magglass" ); m_receiveActivePixmap = Resource::loadPixmap( "irdaapplet/receive" ); m_irda_active = false; m_irda_discovery_active = false; m_receive_active = false; m_receive_state_changed = false; m_popup = 0; m_wasOn = false; m_wasDiscover = false; QCopChannel* chan = new QCopChannel("QPE/IrDaApplet", this ); connect(chan, SIGNAL(received(const QCString&,const QByteArray&) ), - this, SLOT(slotMessage(const QCString&, const QByteArray& ) ) ); + this, SLOT(slotMessage(const QCString&,const QByteArray&) ) ); } int IrdaApplet::position() { return 6; } void IrdaApplet::show() { QWidget::show ( ); startTimer ( 2000 ); } IrdaApplet::~IrdaApplet() { if ( m_sockfd >= 0 ) ::close ( m_sockfd ); } void IrdaApplet::popup ( QString message, QString icon ) { if ( !m_popup ) m_popup = new QPopupMenu ( this ); m_popup-> clear ( ); if ( icon. isEmpty ( )) m_popup-> insertItem ( message, 0 ); else m_popup-> insertItem ( QIconSet ( Resource::loadPixmap ( icon )), message, 0 ); QPoint p = mapToGlobal ( QPoint ( 0, 0 )); QSize s = m_popup-> sizeHint ( ); m_popup-> popup ( QPoint ( p. x ( ) + ( width ( ) / 2 ) - ( s. width ( ) / 2 ), p. y ( ) - s. height ( ))); - QTimer::singleShot ( 2000, this, SLOT( popupTimeout ( ))); + QTimer::singleShot ( 2000, this, SLOT( popupTimeout())); } void IrdaApplet::popupTimeout ( ) { m_popup-> hide ( ); } bool IrdaApplet::checkIrdaStatus ( ) { struct ifreq ifr; strcpy ( ifr. ifr_name, "irda0" ); if ( ::ioctl ( m_sockfd, SIOCGIFFLAGS, &ifr ) < 0 ) return false; return ( ifr. ifr_flags & IFF_UP ); } bool IrdaApplet::setIrdaStatus ( bool b ) { struct ifreq ifr; strcpy ( ifr. ifr_name, "irda0" ); if ( ::ioctl ( m_sockfd, SIOCGIFFLAGS, &ifr ) < 0 ) return false; if ( b ) { ifr. ifr_flags |= IFF_UP; } else { setIrdaDiscoveryStatus ( 0 ); setIrdaReceiveStatus ( 0 ); ifr. ifr_flags &= ~IFF_UP; } if ( ::ioctl ( m_sockfd, SIOCSIFFLAGS, &ifr ) < 0 ) return false; return true; } bool IrdaApplet::checkIrdaDiscoveryStatus ( ) { QFile discovery ( "/proc/sys/net/irda/discovery" ); QString streamIn = "0"; if ( discovery. open ( IO_ReadOnly )) { QTextStream stream ( &discovery ); streamIn = stream. read ( ); } return streamIn. toInt ( ) > 0; } bool IrdaApplet::setIrdaDiscoveryStatus ( bool d ) { QFile discovery ( "/proc/sys/net/irda/discovery" ); if ( discovery. open ( IO_WriteOnly | IO_Raw )) { discovery.putch ( d ? '1' : '0' ); return true; } return false; } bool IrdaApplet::setIrdaReceiveStatus ( bool d ) { QCopEnvelope e ( "QPE/Obex", "receive(int)" ); e << ( d ? 1 : 0 ); m_receive_active = d; m_receive_state_changed = true; return true; } void IrdaApplet::showDiscovered ( ) { // static Sound snd_found ( "irdaapplet/irdaon" ); // static Sound snd_lost ( "irdaapplet/irdaoff" ); QFile discovery ( "/proc/net/irda/discovery" ); if ( discovery. open ( IO_ReadOnly )) { bool qcopsend = false; QString discoveredDevice; QString deviceAddr; // since it is /proc we _must_ use QTextStream QStringList list = QStringList::split ( "\n", QTextStream ( &discovery ). read ( )); QMap <QString, QString>::Iterator it; for ( it = m_devices. begin ( ); it != m_devices. end ( ); ++it ) it. data ( ). prepend ( "+++" ); for ( QStringList::Iterator lit = list. begin ( ); lit != list. end ( ); ++lit ) { const QString &line = *lit; if ( line. startsWith ( "nickname:" )) { discoveredDevice = line. mid ( line. find ( ':' ) + 2, line. find ( ',' ) - line. find ( ':' ) - 2 ); deviceAddr = line. mid ( line. find ( "daddr:" ) + 9, 8 ); // qDebug(discoveredDevice + "(" + deviceAddr + ")"); if ( !m_devices. contains ( deviceAddr )) { popup ( tr( "Found:" ) + " " + discoveredDevice ); //snd_found. play ( ); qcopsend = true; } m_devices. replace ( deviceAddr, discoveredDevice ); } } for ( it = m_devices. begin ( ); it != m_devices. end ( ); ) { // qDebug("IrdaMon: delete " + it.currentKey() + "=" + *devicesAvailable[it.currentKey()] + "?"); if ( it. data ( ). left ( 3 ) == "+++" ) { popup ( tr( "Lost:" ) + " " + it. data ( ). mid ( 3 )); //snd_lost. play ( ); QMap <QString, QString>::Iterator tmp = it; tmp++; m_devices. remove ( it ); // in contrast to QValueListIterator this remove doesn't return the next Iterator it = tmp; qcopsend = true; } else it++; } // XXX if( qcopsend ) { QCopEnvelope e ( "QPE/Network", "irdaSend(bool)" ); e << ( m_devices. count ( ) > 0 ); // } } } void IrdaApplet::mousePressEvent ( QMouseEvent * ) { QPopupMenu *menu = new QPopupMenu ( this ); QString cmd; /* Refresh active state */ timerEvent ( 0 ); // menu->insertItem( tr("More..."), 4 ); if ( m_irda_active && !m_devices. isEmpty ( )) { menu-> insertItem ( tr( "Discovered Device:" ), 9 ); for ( QMap<QString, QString>::Iterator it = m_devices. begin ( ); it != m_devices. end ( ); ++it ) menu-> insertItem ( *it ); menu-> insertSeparator ( ); } menu-> insertItem ( m_irda_active ? tr( "Disable IrDA" ) : tr( "Enable IrDA" ), 0 ); if ( m_irda_active ) { menu-> insertItem ( m_irda_discovery_active ? tr( "Disable Discovery" ) : tr( "Enable Discovery" ), 1 ); menu-> insertItem ( m_receive_active ? tr( "Disable Receive" ) : tr( "Enable Receive" ), 2 ); } QPoint p = mapToGlobal ( QPoint ( 0, 0 ) ); QSize s = menu-> sizeHint ( ); p = QPoint ( p. x ( ) + ( width ( ) / 2 ) - ( s. width ( ) / 2 ), p. y ( ) - s. height ( )); switch ( menu-> exec ( p )) { case 0: setIrdaStatus ( !m_irda_active ); timerEvent ( 0 ); break; case 1: setIrdaDiscoveryStatus ( !m_irda_discovery_active ); timerEvent ( 0 ); break; case 2: setIrdaReceiveStatus ( !m_receive_active ); timerEvent( 0 ); break; } delete menu; } diff --git a/core/applets/multikeyapplet/multikey.cpp b/core/applets/multikeyapplet/multikey.cpp index b17498d..fc5f093 100644 --- a/core/applets/multikeyapplet/multikey.cpp +++ b/core/applets/multikeyapplet/multikey.cpp @@ -1,143 +1,143 @@ /********************************************************************** ** Copyright (C) 2004 Anton Kachalov mouse@altlinux.ru ** All rights reserved. ** ** This file may be distributed and/or modified under the terms of the ** GNU General Public License version 2 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. ** ** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE ** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. ** **********************************************************************/ #include "multikey.h" /* OPIE */ #include <opie2/otaskbarapplet.h> #include <qpe/qcopenvelope_qws.h> /* QT */ #include <qdir.h> Multikey::Multikey(QWidget *parent) : QLabel(parent), popupMenu(this), current("EN") { QCopChannel* swChannel = new QCopChannel("MultiKey/Switcher", this); - connect( swChannel, SIGNAL(received(const QCString &, const QByteArray &)), - this, SLOT(message(const QCString &, const QByteArray &))); + connect( swChannel, SIGNAL(received(const QCString&,const QByteArray&)), + this, SLOT(message(const QCString&,const QByteArray&))); setFont( QFont( "Helvetica", 10, QFont::Normal ) ); QPEApplication::setStylusOperation(this, QPEApplication::RightOnHold); lang = 0; QCopEnvelope e("MultiKey/Keyboard", "getmultikey()"); setText("EN"); popupMenu.insertItem("EN", 0); show(); } void Multikey::mousePressEvent(QMouseEvent *ev) { if (!sw_maps.count()) return; if (ev->button() == RightButton) { QPoint p = mapToGlobal(QPoint(0, 0)); QSize s = popupMenu.sizeHint(); int opt = popupMenu.exec(QPoint(p.x() + (width() / 2) - (s.width() / 2), p.y() - s.height()), 0); if (opt == -1) return; lang = opt; QCopEnvelope e("MultiKey/Keyboard", "setmultikey(QString)"); e << sw_maps[lang]; setText(labels[lang]); } QWidget::mousePressEvent(ev); } void Multikey::mouseReleaseEvent(QMouseEvent *ev) { if (!sw_maps.count()) return; lang = lang < sw_maps.count()-1 ? lang+1 : 0; QCopEnvelope e("MultiKey/Keyboard", "setmultikey(QString)"); //qDebug("Lang=%d, count=%d, lab=%s", lang, sw_maps.count(), labels[lang].ascii()); e << sw_maps[lang]; setText(labels[lang]); } void Multikey::message(const QCString &message, const QByteArray &data) { if ( message == "setsw(QString,QString)" ) { QDataStream stream(data, IO_ReadOnly); QString maps, current_map; stream >> maps >> current_map; QStringList sw = QStringList::split(QChar('|'), maps); sw.append(current_map); QDir map_dir(QPEApplication::qpeDir() + "/share/multikey/", "*.keymap"); lang = 0; labels.clear(); sw_maps.clear(); popupMenu.clear(); for (uint i = 0; i < sw.count(); ++i) { QString keymap_map; if (sw[i][0] != '/') { keymap_map = map_dir.absPath() + "/" + sw[i]; } else { if ((map_dir.exists(QFileInfo(sw[i]).fileName(), false) && i != sw.count()-1) || !QFile::exists(sw[i])) { continue; } keymap_map = sw[i]; } QFile map(keymap_map); if (map.open(IO_ReadOnly)) { QString line; map.readLine(line, 1024); while (!map.atEnd()) { if (line.find(QRegExp("^sw\\s*=\\s*")) != -1) { if (i != sw.count()-1) { if (keymap_map == current_map) { lang = i; } sw_maps.append(keymap_map); labels.append(line.right(line.length() - line.find(QChar('=')) - 1).stripWhiteSpace()); popupMenu.insertItem(labels[labels.count()-1], labels.count()-1); } else { current = line.right(line.length() - line.find(QChar('=')) - 1).stripWhiteSpace(); } break; } map.readLine(line, 1024); } map.close(); } } setText(current); } } int Multikey::position() { return 10; } Q_EXPORT_INTERFACE() { Q_CREATE_INSTANCE( OTaskbarAppletWrapper<Multikey> ); } diff --git a/core/applets/rotateapplet/rotate.cpp b/core/applets/rotateapplet/rotate.cpp index dcbf809..0488c36 100644 --- a/core/applets/rotateapplet/rotate.cpp +++ b/core/applets/rotateapplet/rotate.cpp @@ -1,244 +1,244 @@ /* This file is part of the OPIE Project Copyright (C) 2003 Maximilian Reiss <harlekin@handhelds.org> Copyright (C) 2003 Greg Gilbert <ggilbert@treke.net> =. Copyright (C) 2004 Michael Lauer <mickey@Vanille.de> .=l. .>+-= _;:, .> :=|. This library is free software; you can .> <, > . <= redistribute it and/or modify it under :=1 )Y*s>-.-- : the terms of the GNU Library General Public .="- .-=="i, .._ License as published by the Free Software - . .-<_> .<> Foundation; either version 2 of the License, ._= =} : or (at your option) any later version. .%+i> _;_. .i_,=:_. -<s. 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 "rotate.h" /* OPIE */ #include <opie/odevice.h> #include <qpe/config.h> #include <qpe/power.h> #include <qpe/qcopenvelope_qws.h> #include <qpe/resource.h> using namespace Opie; /* QT */ #include <time.h> RotateApplet::RotateApplet() :QObject( 0, "RotateApplet" ), m_flipped( false ) { #if !defined(QT_NO_COP) QCopChannel *rotateChannel = new QCopChannel( "QPE/Rotation" , this ); - connect ( rotateChannel, SIGNAL( received( const QCString &, const QByteArray &) ), - this, SLOT ( channelReceived( const QCString &, const QByteArray &) ) ); + connect ( rotateChannel, SIGNAL( received(const QCString&,const QByteArray&) ), + this, SLOT ( channelReceived(const QCString&,const QByteArray&) ) ); #endif } RotateApplet::~RotateApplet ( ) {} /** * Qcop receive method. */ void RotateApplet::channelReceived( const QCString &msg, const QByteArray & data ) { qDebug( "RotateApplet::channelReceived( '%s' )", (const char*) msg ); if ( ODevice::inst()->hasHingeSensor() ) { struct timespec interval; struct timespec remain; interval.tv_sec = 0; interval.tv_nsec = 600000; ::nanosleep( &interval, &remain ); OHingeStatus status = ODevice::inst()->readHingeSensor(); qDebug( "RotateApplet::readHingeSensor = %d", (int) status ); Config cfg( "apm" ); cfg.setGroup( PowerStatusManager::readStatus().acStatus() == PowerStatus::Online ? "AC" : "Battery" ); int action = cfg.readNumEntry( "CloseHingeAction", 0 ); if ( status == CASE_CLOSED ) { switch ( action ) { case 1: /* DISPLAY OFF */ ODevice::inst()->setDisplayBrightness( 0 ); break; case 2: /* SUSPEND */ ODevice::inst()->suspend(); break; default: /* IGNORE */ break; } } else /* status != CASE_CLOSED */ { switch ( action ) { case 1: /* DISPLAY OFF */ ODevice::inst()->setDisplayBrightness( 127 ); break; case 2: /* SUSPEND */ /* How to wake up the device from kernel? */; break; default: /* IGNORE */ break; } } qDebug( "RotateApplet::switchAction %d performed.", cfg.readNumEntry( "CloseHingeAction", 0 ) ); } QDataStream stream( data, IO_ReadOnly ); if ( msg == "flip()" ) { activated ( ); } else if ( msg == "rotateDefault()") { rotateDefault(); } } int RotateApplet::position() const { return 3; } QString RotateApplet::name() const { return tr( "Rotate shortcut" ); } QString RotateApplet::text() const { return tr( "Rotate" ); } /*QString RotateApplet::tr( const char* s ) const { return qApp->translate( "RotateApplet", s, 0 ); } QString RotateApplet::tr( const char* s, const char* p ) const { return qApp->translate( "RotateApplet", s, p ); } */ QIconSet RotateApplet::icon() const { QPixmap pix; QImage img = Resource::loadImage( "Rotation" ); if ( !img.isNull() ) pix.convertFromImage( img.smoothScale( 14, 14 ) ); return pix; } QPopupMenu* RotateApplet::popup(QWidget*) const { return 0; } void RotateApplet::rotateDefault() { int rot = ODevice::inst()->rotation(); switch (rot) { case Rot0: rot=0; break; case Rot90: rot=90; break; case Rot180: rot=180; break; case Rot270: rot=270; break; default: rot=0; break; } Config cfg( "qpe" ); cfg.setGroup( "Appearance" ); bool rotateEnabled = cfg.readBoolEntry( "rotateEnabled",true ); if ( !rotateEnabled) return; // hide inputs methods before rotation QCopEnvelope en( "QPE/TaskBar", "hideInputMethod()" ); QCopEnvelope env( "QPE/System", "setCurrentRotation(int)" ); env << rot; m_flipped = false; } void RotateApplet::activated() { int defaultRotation = QPEApplication::defaultRotation(); int newRotation = defaultRotation; Config cfg( "qpe" ); cfg.setGroup( "Appearance" ); int rotDirection = cfg.readNumEntry( "rotatedir" ); ODirection rot = CW; if (rotDirection == -1) { rot = ODevice::inst()->direction(); } else { rot = (ODirection) rotDirection; } // hide inputs methods before rotation QCopEnvelope en( "QPE/TaskBar", "hideInputMethod()" ); if ( m_flipped ) { // if flipped, flip back to the original state, // regardless of rotation direction newRotation = defaultRotation; } else { if ( rot == CCW ) { newRotation = ( defaultRotation + 90 ) % 360; } else if ( rot == CW ) { newRotation = ( defaultRotation + 270 ) % 360; } else if ( rot == Flip ) { newRotation = ( defaultRotation + 180 ) % 360; } } QCopEnvelope env( "QPE/System", "setCurrentRotation(int)" ); env << newRotation; m_flipped = !m_flipped; } QRESULT RotateApplet::queryInterface( const QUuid &uuid, QUnknownInterface **iface ) { *iface = 0; if ( uuid == IID_QUnknown ) *iface = this; else if ( uuid == IID_MenuApplet ) *iface = this; else return QS_FALSE; if ( *iface ) diff --git a/core/applets/screenshotapplet/screenshot.cpp b/core/applets/screenshotapplet/screenshot.cpp index 5d6bce4..20e1c9b 100644 --- a/core/applets/screenshotapplet/screenshot.cpp +++ b/core/applets/screenshotapplet/screenshot.cpp @@ -110,387 +110,387 @@ static char * snapshot_xpm[] = { "B c #0A4DA0", "C c #4E5242", "D c #62362E", "E c #721A1A", "F c #6E0A0A", "G c #3E0E0E", "H c #6AB85E", "I c #7E8ECA", "J c #929CD4", "K c #9EAECA", "L c #9EBEAE", "M c #8EC26A", "N c #32A276", "O c #20518C", "P c #46566E", "Q c #614A51", "R c #AE2A26", "S c #C41C1A", "T c #CE0A0A", "U c #A60606", "V c #921616", "W c #863735", "X c #866A66", "Y c #9E9EA2", "Z c #1E5212", "` c #7EC652", " . c #B2B2F2", ".. c #CACAF6", "+. c #AECEC6", "@. c #92CE72", "#. c #42AA86", "$. c #365E96", "%. c #B82420", "&. c #E20E0E", "*. c #EF0E0B", "=. c #566A86", "-. c #92929A", ";. c #16260E", ">. c #2E571A", ",. c #7ED64E", "'. c #9ECEB2", "). c #C6D5EF", "!. c #E2E0FE", "~. c #A2DE8A", "{. c #4AAA5B", "]. c #2A6AB2", "^. c #9A7A6E", "/. c #D25A52", "(. c #F62626", "_. c #FA0206", ":. c #DE1E16", "<. c #B63A26", "[. c #865A2E", "}. c #26568E", "|. c #435F7D", "1. c #7AE246", "2. c #96EA6E", "3. c #BEEAAE", "4. c #D0EADC", "5. c #B6CEFE", "6. c #9ADE8A", "7. c #2A609A", "8. c #7E623E", "9. c #CA7A72", "0. c #F26E6E", "a. c #FE5252", "b. c #FA3638", "c. c #DA2E28", "d. c #9E3E3A", "e. c #3E7656", "f. c #76CB3A", "g. c #90DE44", "h. c #A2EE6A", "i. c #9EEA9A", "j. c #92BEDE", "k. c #7ADA7E", "l. c #5ECE52", "m. c #6A5E52", "n. c #A83238", "o. c #FA5656", "p. c #F29A92", "q. c #D29E92", "r. c #8A7A62", "s. c #05336B", "t. c #59C631", "u. c #8AD23A", "v. c #66E242", "w. c #1D6FC1", "x. c #E61212", "y. c #CA261E", "z. c #5A763E", "A. c #1E6E9A", "B. c #023272", "C. c #329696", "D. c #2074B6", "E. c #3E4E76", "F. c #5A525E", "G. c #425868", "H. c #04448E", "I. c #28828A", "J. c #2D8593", "K. c #12427A", "L. c #054696", "M. c #042B5E", "N. c #134F95", "O. c #1E6ABB", "P. c #1A5E96", "Q. c #022E67", "R. c #0C3E7C", "S. c #023E8A", "T. c #021A3E", " ", " ", " ", " . + @ # + ", " $ # % & * * = - # $ ", "; > % @ = , ' ) ' ! ~ { % @ . ] ^ / ( ", "; + ' * ) _ ) ) ' : : ! { { % < . [ ( } ", "| @ 1 2 3 _ _ ) ' : : : : 4 5 6 6 # 7 8 } ", "9 0 a b b b c _ ) : : ! ! ~ ~ 5 ~ d e f [ 8 g h h } ", "| i j k j l m n 3 ) : ! ! ! ~ o o o p 6 q f / r r r s ", "t u v w x y y z a 1 3 ' : ! ~ A A B A p = C D E F G ( s ", "| u H I J K L M H k N 3 3 : ~ o o 5 O P Q R S T T U V W X Y ", "| Z ` J .....+.@.z #.3 _ 3 3 ) $.P W %.S &.*.*.&.S W Q P =.-. ", ";.>.,.'.).!.!.).~.,.{.) : ) 3 ].h ^./.(._._._.:.<.[.g }.= & |. ", ";.>.1.2.3.4.4.5.6.,.{._ : : : 7.8.9.0.a.b.b.c.d.} e.4 = 6 q # ", ";.>.z f.g.h.i.j.k.l.N ) : ! ! 4 m.n.c.o.p.q.r.|.5 { d e e s.. ", "t Z l t.f.u.g.1.v.#.w.' : ! ~ ~ 7.|.n.x.y.z.A.A q - e e e B.> ", "| 0 c k t.t.l l C.D.) * * ! 5 { B o E.F.F.G.= H.e e e e q B.. ", "; + D.I.J.I.I.I.w.) : : * o K.7 - L.= O = }.6 6 e q q e q s.> ", "9 + ) ) ) ) ' ' , * : ! ! ! K.< . M.q 6 B N.{ d q e e e e s.9 ", "9 # O.) ) ' , , P.* ! ! ! ! = % . . M.e d p L.d B.B.e B.B.Q.9 ", "; < ' ' ' ' , , 4 4 ~ ! ! ~ ! 5 e q e e q A H.d q q e e B.Q.9 ", "; $ R.K.5 4 4 ' ! ! 4 ~ ! ~ ~ ~ o { B o A A L.S.B.B.B.B.B.Q.> ", " ] $ 0 R.= ' ' 4 4 5 4 5 5 o B o B p A A L.d e e B.B.B.Q.9 ", " # + - { 4 4 ~ ! o { o L.p p p p p H.S.B.B.s.Q.Q.M.T. ", " + s.6 B o o 5 B p L.p p L.p H.q B.Q.Q.Q.Q.M.; ", " < # s.- B o B p p L.L.H.L.H.d B.Q.Q.Q.Q.Q.9 ", " $ . s.d 6 B A p H.S.L.H.q B.Q.Q.M.M.. ; ", " ; 9 . 6 L.p L.d L.H.d Q.M.M.. 9 ; ] ", " | > e L.d L.H.e M.. ; ] ] ", " > 9 . S.Q.. ; ] ", " T.; ] "}; static const char *SCAP_hostname = "www.handhelds.org"; static const int SCAP_port = 80; ScreenshotControl::ScreenshotControl( QWidget *parent, const char *name ) : QFrame( parent, name, WDestructiveClose | WStyle_StaysOnTop | WType_Popup ) { setFrameStyle( QFrame::PopupPanel | QFrame::Raised ); QVBoxLayout *vbox = new QVBoxLayout ( this, 5, 3 ); QHBoxLayout *hbox; hbox = new QHBoxLayout ( vbox ); QLabel *l = new QLabel ( tr( "Delay" ), this ); hbox-> addWidget ( l ); delaySpin = new QSpinBox( 0, 60, 1, this, "Spinner" ); delaySpin-> setButtonSymbols ( QSpinBox::PlusMinus ); delaySpin-> setSuffix ( tr( "sec" )); delaySpin-> setFocusPolicy( QWidget::NoFocus ); delaySpin-> setValue ( 1 ); hbox-> addWidget ( delaySpin ); saveNamedCheck = new QCheckBox ( tr( "Save named" ), this); saveNamedCheck-> setFocusPolicy ( QWidget::NoFocus ); vbox->addWidget( saveNamedCheck); vbox-> addSpacing ( 3 ); l = new QLabel ( tr( "Save screenshot as..." ), this ); vbox-> addWidget ( l, AlignCenter ); hbox = new QHBoxLayout ( vbox ); grabItButton = new QPushButton( tr( "File" ), this, "GrabButton" ); grabItButton ->setFocusPolicy( QWidget::TabFocus ); hbox-> addWidget ( grabItButton ); scapButton = new QPushButton( tr( "Scap" ), this, "ScapButton" ); scapButton ->setFocusPolicy( QWidget::TabFocus ); hbox-> addWidget ( scapButton ); setFixedSize ( sizeHint ( )); setFocusPolicy ( QWidget::NoFocus ); grabTimer = new QTimer ( this, "grab timer"); - connect ( grabTimer, SIGNAL( timeout ( )), this, SLOT( performGrab ( ))); - connect ( grabItButton, SIGNAL( clicked ( )), SLOT( slotGrab ( ))); - connect ( scapButton, SIGNAL( clicked ( )), SLOT( slotScap ( ))); + connect ( grabTimer, SIGNAL( timeout()), this, SLOT( performGrab())); + connect ( grabItButton, SIGNAL( clicked()), SLOT( slotGrab())); + connect ( scapButton, SIGNAL( clicked()), SLOT( slotScap())); } void ScreenshotControl::slotGrab() { buttonPushed = 1; hide(); setFileName = FALSE; if ( saveNamedCheck->isChecked()) { setFileName = TRUE; InputDialog *fileDlg; fileDlg = new InputDialog( 0 , tr("Name of screenshot "), TRUE, 0); fileDlg->exec(); fileDlg->raise(); QString fileName, list; if ( fileDlg->result() == 1 ) { fileName = fileDlg->LineEdit1->text(); if (fileName.find("/", 0, TRUE) == -1) FileNamePath = QDir::homeDirPath() + "/Documents/image/png/" + fileName; else FileNamePath = fileName; } delete fileDlg; } if ( delaySpin->value() ) grabTimer->start( delaySpin->value() * 1000, true ); else show(); } void ScreenshotControl::slotScap() { buttonPushed = 2; hide(); if ( delaySpin->value() ) grabTimer->start( delaySpin->value() * 1000, true ); else show(); } void ScreenshotControl::savePixmap() { DocLnk lnk; QString fileName; if ( setFileName) { fileName = FileNamePath; //not sure why this is needed here, but it forgets fileName // if this is below the braces if (fileName.right(3) != "png") fileName = fileName + ".png"; lnk.setFile(fileName); //sets File property qDebug("saving file " + fileName); snapshot.save( fileName, "PNG"); QFileInfo fi( fileName); lnk.setName( fi.fileName()); //sets file name if (!lnk.writeLink()) qDebug("Writing doclink did not work"); } else { fileName = "sc_" + QDateTime::currentDateTime().toString(); fileName.replace(QRegExp("'"), ""); fileName.replace(QRegExp(" "), "_"); fileName.replace(QRegExp(":"), "."); fileName.replace(QRegExp(","), ""); QString dirName = QDir::homeDirPath() + "/Documents/image/png/"; if ( !QDir( dirName).exists() ) { qDebug("making dir " + dirName); QString msg = "mkdir -p " + dirName; system(msg.latin1()); } fileName = dirName + fileName; if (fileName.right(3) != "png") fileName = fileName + ".png"; lnk.setFile(fileName); //sets File property qDebug("saving file " + fileName); snapshot.save( fileName, "PNG"); QFileInfo fi( fileName); lnk.setName( fi.fileName()); //sets file name if (!lnk.writeLink()) qDebug("Writing doclink did not work"); } QPEApplication::beep(); } void ScreenshotControl::performGrab() { snapshot = QPixmap::grabWindow( QPEApplication::desktop()->winId(), 0, 0, QApplication::desktop()->width(), QApplication::desktop()->height() ); if (buttonPushed == 1) { qDebug("grabbing screen"); grabTimer->stop(); show(); qApp->processEvents(); savePixmap(); } else { grabTimer->stop(); struct sockaddr_in raddr; struct hostent *rhost_info; int sock = -1; bool ok = false; QString displayEnv = getenv("QWS_DISPLAY"); qDebug(displayEnv); if(( displayEnv.left(2) != ":0" ) && (!displayEnv.isEmpty())) { if (( rhost_info = (struct hostent *) ::gethostbyname ((char *) SCAP_hostname )) != 0 ) { ::memset ( &raddr, 0, sizeof (struct sockaddr_in)); ::memcpy ( &raddr. sin_addr, rhost_info-> h_addr, rhost_info-> h_length ); raddr. sin_family = rhost_info-> h_addrtype; raddr. sin_port = htons ( SCAP_port ); if (( sock = ::socket ( AF_INET, SOCK_STREAM, 0 )) >= 0 ) { if ( ::connect ( sock, (struct sockaddr *) & raddr, sizeof (struct sockaddr)) >= 0 ) { QString header; QPixmap pix; QString SCAP_model=""; #warning FIXME: model string should be filled with actual device model if( snapshot.width() > 320) SCAP_model ="Corgi"; if(displayEnv == "QVFb:0") {//set this if you plan on using this app in qvfb!! pix = snapshot.xForm(QWMatrix().rotate(90)); } else pix = ( snapshot.width() > snapshot.height() ) ? snapshot : snapshot.xForm( QWMatrix().rotate(90) ); QImage img = pix.convertToImage().convertDepth( 16 ); // could make that also depth independent, if hh.org/scap can handle it header = "POST /scap/capture.cgi?%1+%2 HTTP/1.1\n" // 1: model / 2: user "Content-length: %3\n" // 3: content length "Content-Type: image/png\n" "Host: %4\n" // 4: scap host "\n"; header = header.arg( SCAP_model).arg( ::getenv( "USER" ) ).arg( img.numBytes() ).arg( SCAP_hostname ); qDebug(header); if ( !pix.isNull() ) { const char *ascii = header.latin1( ); uint ascii_len = ::strlen( ascii ); ::write ( sock, ascii, ascii_len ); ::write ( sock, img.bits(), img.numBytes() ); ok = true; } } ::close ( sock ); } } if ( ok ) { QMessageBox::information( 0, tr( "Success" ), QString( "<p>%1</p>" ).arg ( tr( "Screenshot was uploaded to %1" )).arg( SCAP_hostname )); } else { QMessageBox::warning( 0, tr( "Error" ), QString( "<p>%1</p>" ).arg( tr( "Connection to %1 failed." )).arg( SCAP_hostname )); } } else { QMessageBox::warning( 0, tr( "Error" ),tr("Please set <b>QWS_DISPLAY</b> environmental variable.")); } } } //=========================================================================== ScreenshotApplet::ScreenshotApplet( QWidget *parent, const char *name ) : QWidget( parent, name ) { setFixedWidth( AppLnk::smallIconSize()); QImage img = (const char **)snapshot_xpm; img = img.smoothScale(AppLnk::smallIconSize(), AppLnk::smallIconSize()); m_icon.convertFromImage(img); diff --git a/core/applets/vmemo/vmemo.cpp b/core/applets/vmemo/vmemo.cpp index 563d110..27f6015 100644 --- a/core/applets/vmemo/vmemo.cpp +++ b/core/applets/vmemo/vmemo.cpp @@ -24,386 +24,386 @@ extern "C" { #include <errno.h> typedef struct _waveheader { u_long main_chunk; /* 'RIFF' */ u_long length; /* filelen */ u_long chunk_type; /* 'WAVE' */ u_long sub_chunk; /* 'fmt ' */ u_long sc_len; /* length of sub_chunk, =16 (chunckSize) format len */ u_short format; /* should be 1 for PCM-code (formatTag) */ u_short modus; /* 1 Mono, 2 Stereo (channels) */ u_long sample_fq; /* samples per second (samplesPerSecond) */ u_long byte_p_sec; /* avg bytes per second (avgBytePerSecond) */ u_short byte_p_spl; /* samplesize; 1 or 2 bytes (blockAlign) */ u_short bit_p_spl; /* 8, 12 or 16 bit (bitsPerSample) */ u_long data_chunk; /* 'data' */ u_long data_length;/* samplecount */ } WaveHeader; #define RIFF 0x46464952 #define WAVE 0x45564157 #define FMT 0x20746D66 #define DATA 0x61746164 #define PCM_CODE 1 #define WAVE_MONO 1 #define WAVE_STEREO 2 struct adpcm_state encoder_state; //struct adpcm_state decoder_state; #define WAVE_FORMAT_DVI_ADPCM (0x0011) #define WAVE_FORMAT_PCM (0x0001) #include "vmemo.h" #include <opie2/otaskbarapplet.h> #include <qpe/qpeapplication.h> #include <qpe/config.h> #include <qpainter.h> #include <qmessagebox.h> int seq = 0; /* XPM */ static char * vmemo_xpm[] = { "16 16 102 2", " c None", ". c #60636A", "+ c #6E6E72", "@ c #68696E", "# c #4D525C", "$ c #6B6C70", "% c #E3E3E8", "& c #EEEEF2", "* c #EAEAEF", "= c #CACAD0", "- c #474A51", "; c #171819", "> c #9B9B9F", ", c #EBEBF0", "' c #F4F4F7", ") c #F1F1F5", "! c #DEDEE4", "~ c #57575C", "{ c #010101", "] c #A2A2A6", "^ c #747477", "/ c #B5B5B8", "( c #AEAEB2", "_ c #69696D", ": c #525256", "< c #181C24", "[ c #97979B", "} c #A7A7AC", "| c #B0B0B4", "1 c #C8C8D1", "2 c #75757B", "3 c #46464A", "4 c #494A4F", "5 c #323234", "6 c #909095", "7 c #39393B", "8 c #757578", "9 c #87878E", "0 c #222224", "a c #414144", "b c #6A6A6E", "c c #020C16", "d c #6B6B6F", "e c #68686D", "f c #5B5B60", "g c #8A8A8F", "h c #6B6B6E", "i c #ADADB2", "j c #828289", "k c #3E3E41", "l c #CFCFD7", "m c #4C4C50", "n c #000000", "o c #66666A", "p c #505054", "q c #838388", "r c #A1A1A7", "s c #A9A9AE", "t c #A8A8B0", "u c #5E5E63", "v c #3A3A3E", "w c #BDBDC6", "x c #59595E", "y c #76767C", "z c #373738", "A c #717174", "B c #727278", "C c #1C1C1E", "D c #3C3C3F", "E c #ADADB6", "F c #54555A", "G c #8B8C94", "H c #5A5A5F", "I c #BBBBC3", "J c #C4C4CB", "K c #909098", "L c #737379", "M c #343437", "N c #8F8F98", "O c #000407", "P c #2D3137", "Q c #B0B1BC", "R c #3B3C40", "S c #6E6E74", "T c #95959C", "U c #74747A", "V c #1D1D1E", "W c #91929A", "X c #42444A", "Y c #22282E", "Z c #B0B2BC", "` c #898A90", " . c #65656A", ".. c #999AA2", "+. c #52535A", "@. c #151B21", "#. c #515257", "$. c #B5B5BE", "%. c #616167", "&. c #1A1D22", "*. c #000713", "=. c #1F1F21", " ", " . + @ # ", " $ % & * = - ", " ; > , ' ) ! ~ ", " { ] ^ / ( _ : ", " < [ } | 1 2 3 ", " 4 5 6 7 8 9 0 a b c ", " d e f g h i j 3 k l m n ", " o p q r s t u v w n ", " o x y z A B C D E n ", " F G H I J K L M N O ", " P Q R S T U V W X ", " Y Z ` b ...+. ", " @.#.$.%.&. ", " *.B =. ", " n n n n n n n n n "}; VMemo::VMemo( QWidget *parent, const char *_name ) : QWidget( parent, _name ) { setFixedHeight( 18 ); setFixedWidth( 14 ); t_timer = new QTimer( this ); connect( t_timer, SIGNAL( timeout() ), SLOT( timerBreak() ) ); Config vmCfg("Vmemo"); vmCfg.setGroup("Defaults"); int toggleKey = setToggleButton(vmCfg.readNumEntry("toggleKey", -1)); useADPCM = vmCfg.readBoolEntry("use_ADPCM", 0); qDebug("toggleKey %d", toggleKey); if ( QFile::exists ( "/dev/sharp_buz" ) || QFile::exists ( "/dev/sharp_led" )) systemZaurus=TRUE; else systemZaurus=FALSE; myChannel = new QCopChannel( "QPE/VMemo", this ); - connect( myChannel, SIGNAL(received(const QCString&, const QByteArray&)), - this, SLOT(receive(const QCString&, const QByteArray&)) ); + connect( myChannel, SIGNAL(received(const QCString&,const QByteArray&)), + this, SLOT(receive(const QCString&,const QByteArray&)) ); if( toggleKey != -1 ) { // keyRegister(key, channel, message) QCopEnvelope e("QPE/Launcher", "keyRegister(int,QCString,QCString)"); // e << 4096; // Key_Escape // e << Key_F5; //4148 e << toggleKey; e << QString("QPE/VMemo"); e << QString("toggleRecord()"); } if(toggleKey == 1) usingIcon=TRUE; else usingIcon=FALSE; if( vmCfg.readNumEntry("hideIcon",0) == 1) hide(); recording = FALSE; // } } VMemo::~VMemo() { } int VMemo::position() { return 6; } void VMemo::receive( const QCString &msg, const QByteArray &data ) { qDebug("receive"); QDataStream stream( data, IO_ReadOnly ); if (msg == "toggleRecord()") { if (recording) { fromToggle = TRUE; stopRecording(); } else { fromToggle = TRUE; startRecording(); } } } void VMemo::paintEvent( QPaintEvent* ) { QPainter p(this); p.drawPixmap( 0, 1,( const char** ) vmemo_xpm ); } void VMemo::mousePressEvent( QMouseEvent * me) { /* No mousePress/mouseRelease recording on the iPAQ. The REC button on the iPAQ calls these functions mousePressEvent and mouseReleaseEvent with a NULL parameter. */ // if (!systemZaurus && me != NULL) // return; // } if(!recording) startRecording(); else stopRecording(); } void VMemo::mouseReleaseEvent( QMouseEvent * ) { } bool VMemo::startRecording() { Config config( "Vmemo" ); config.setGroup( "System" ); useAlerts = config.readBoolEntry("Alert",1); if(useAlerts) { msgLabel = new QLabel( 0, "alertLabel" ); msgLabel->setText("<B><P><font size=+2>VMemo-Recording</font></B>"); msgLabel->show(); } qDebug("Start recording engines"); recording = TRUE; if (openDSP() == -1) { recording = FALSE; return FALSE; } config.setGroup("Defaults"); date = TimeString::dateString( QDateTime::currentDateTime(),false,true); date.replace(QRegExp("'"),""); date.replace(QRegExp(" "),"_"); date.replace(QRegExp(":"),"."); date.replace(QRegExp(","),""); QString fName; config.setGroup( "System" ); fName = QPEApplication::documentDir() ; fileName = config.readEntry("RecLocation", fName); int s; s=fileName.find(':'); if(s) fileName=fileName.right(fileName.length()-s-2); qDebug("pathname will be "+fileName); if( fileName.left(1).find('/') == -1) fileName="/"+fileName; if( fileName.right(1).find('/') == -1) fileName+="/"; fName = "vm_"+ date+ ".wav"; fileName+=fName; qDebug("filename is "+fileName); // open tmp file here char *pointer; pointer=tmpnam(NULL); qDebug("Opening tmp file %s",pointer); if(openWAV(pointer ) == -1) { QString err("Could not open the temp file\n"); err += fileName; QMessageBox::critical(0, "vmemo", err, "Abort"); ::close(dsp); return FALSE; } if( record() ) { QString cmd; if( fileName.find(".wav",0,TRUE) == -1) fileName += ".wav"; cmd.sprintf("mv %s "+fileName, pointer); // move tmp file to regular file here system(cmd.latin1()); QArray<int> cats(1); cats[0] = config.readNumEntry("Category", 0); QString dlName("vm_"); dlName += date; DocLnk l; l.setFile(fileName); l.setName(dlName); l.setType("audio/x-wav"); l.setCategories(cats); l.writeLink(); return TRUE; } else return FALSE; } void VMemo::stopRecording() { show(); qDebug("Stopped recording"); recording = FALSE; if(useAlerts) { msgLabel->close(); msgLabel=0; delete msgLabel; } t_timer->stop(); Config cfg("Vmemo"); cfg.setGroup("Defaults"); if( cfg.readNumEntry("hideIcon",0) == 1 ) hide(); } int VMemo::openDSP() { Config cfg("Vmemo"); cfg.setGroup("Record"); speed = cfg.readNumEntry("SampleRate", 22050); channels = cfg.readNumEntry("Stereo", 1) ? 2 : 1; // 1 = stereo(2), 0 = mono(1) if (cfg.readNumEntry("SixteenBit", 1)==1) { format = AFMT_S16_LE; resolution = 16; } else { format = AFMT_U8; resolution = 8; } qDebug("samplerate: %d, channels %d, resolution %d", speed, channels, resolution); if(systemZaurus) { dsp = open("/dev/dsp1", O_RDONLY); //Zaurus needs /dev/dsp1 channels=1; //zaurus has one input channel } else { dsp = open("/dev/dsp", O_RDONLY); } diff --git a/core/applets/volumeapplet/volume.cpp b/core/applets/volumeapplet/volume.cpp index 8fd88f6..942cebb 100644 --- a/core/applets/volumeapplet/volume.cpp +++ b/core/applets/volumeapplet/volume.cpp @@ -219,565 +219,565 @@ static const char * alarm_xpm[] = { " +2&3+$1*44 ", " (%_}_+/$:>/4 ", " 4%_}3+#;>:*4 ", " 4%_}&+#[1$/4 ", " 4%_,2')[~~>4 ", " 4%33'4#@~1>4 ", " 4%3344#[:>/4 ", " 42&_3'4#@>:*44 ", " 42|}}3'4#[;$)$44 ", "444{]]2^~~:!!#.@##/ ", "4444-%*:==!!=...../ ", " /:[.. ", " /@. ", " "}; VolumeControl::VolumeControl ( VolumeApplet *icon, bool /*showMic*/, QWidget *parent, const char *name ) : QFrame ( parent, name, WStyle_StaysOnTop | WType_Popup ) { m_icon = icon; bool has_wav_alarm = true; bool has_bass = true; bool has_treble = true; switch ( ODevice::inst ( )-> model ( )) { // we need to add other devices eventually case Model_Zaurus_SL5000: has_wav_alarm = false; //poor guys probably feeling left out... break; default: break; } if ( !ODevice::inst ( )-> series ( ) == Model_iPAQ ) { has_bass = false; has_treble = false; } setFrameStyle ( QFrame::PopupPanel | QFrame::Raised ); QGridLayout *grid = new QGridLayout ( this, 1, 1, 6, 4 ); grid-> setSpacing ( 4 ); grid-> setMargin ( 6 ); QVBoxLayout *vbox; QLabel *l; vbox = new QVBoxLayout ( ); vbox-> setSpacing ( 4 ); grid-> addLayout ( vbox, 1, 0 ); upButton = new QPushButton ( this ); upButton-> setSizePolicy ( QSizePolicy ( QSizePolicy::Minimum, QSizePolicy::Expanding )); upButton-> setPixmap ( Resource::loadPixmap ( "up" )); upButton-> setFocusPolicy ( QWidget::NoFocus ); vbox-> addWidget ( upButton ); downButton = new QPushButton ( this ); downButton-> setSizePolicy ( QSizePolicy ( QSizePolicy::Minimum, QSizePolicy::Expanding )); downButton-> setPixmap ( Resource::loadPixmap ( "down" )); downButton-> setFocusPolicy ( QWidget::NoFocus ); vbox-> addWidget ( downButton ); volSlider = new QSlider ( this ); volSlider-> setRange ( 0, 100 ); volSlider-> setTickmarks ( QSlider::Both ); volSlider-> setTickInterval ( 20 ); volSlider-> setFocusPolicy ( QWidget::NoFocus ); l = new QLabel ( this ); l-> setPixmap ( QPixmap ( vol_xpm )); grid-> addWidget ( l, 0, 1, AlignCenter ); grid-> addWidget ( volSlider, 1, 1, AlignCenter ); volLed = new OLedBox ( green, this ); volLed-> setFocusPolicy ( QWidget::NoFocus ); volLed-> setFixedSize ( 16, 16 ); grid-> addWidget ( volLed, 2, 1, AlignCenter ); QVBox *basstrebleBox = new QVBox( this ); trebleSlider = new QSlider ( basstrebleBox ); trebleSlider-> setRange ( 0, 100 ); trebleSlider-> setTickmarks ( QSlider::Both ); trebleSlider-> setTickInterval ( 20 ); trebleSlider->setMaximumHeight( 40 ); trebleSlider-> setFocusPolicy ( QWidget::NoFocus ); bassSlider = new QSlider ( basstrebleBox ); bassSlider-> setRange ( 0, 100 ); bassSlider-> setTickmarks ( QSlider::Both ); bassSlider-> setTickInterval ( 20 ); bassSlider->setMaximumHeight( 40 ); bassSlider-> setFocusPolicy ( QWidget::NoFocus ); QLabel *bassLabel = new QLabel ( this ); bassLabel-> setPixmap ( QPixmap ( bass_xpm )); QLabel *trebleLabel = new QLabel( this ); trebleLabel->setPixmap( QPixmap ( treble_xpm ) ); grid->addWidget( trebleLabel, 0, 4, AlignCenter ); grid->addWidget( basstrebleBox, 1, 4, AlignCenter ); grid-> addWidget ( bassLabel, 2, 4, AlignCenter ); if ( !has_bass ) { bassSlider->hide(); bassLabel->hide(); } if ( !has_treble ) { trebleSlider->hide(); trebleLabel->hide(); } micSlider = new QSlider ( this ); micSlider-> setRange ( 0, 100 ); micSlider-> setTickmarks ( QSlider::Both ); micSlider-> setTickInterval ( 20 ); micSlider-> setFocusPolicy ( QWidget::NoFocus ); l = new QLabel ( this ); l-> setPixmap ( QPixmap ( mic_xpm )); grid-> addWidget ( l, 0, 2, AlignCenter ); grid-> addWidget ( micSlider, 1, 2, AlignCenter ); micLed = new OLedBox ( red, this ); micLed-> setFocusPolicy ( QWidget::NoFocus ); micLed-> setFixedSize ( 16, 16 ); grid-> addWidget ( micLed, 2, 2, AlignCenter ); alarmSlider = new QSlider ( this ); alarmSlider-> setRange ( 0, 100 ); alarmSlider-> setTickmarks ( QSlider::Both ); alarmSlider-> setTickInterval ( 20 ); alarmSlider-> setFocusPolicy ( QWidget::NoFocus ); QLabel *alarmLabel = new QLabel ( this ); alarmLabel-> setPixmap ( QPixmap ( alarm_xpm )); grid-> addWidget ( alarmLabel, 0, 3, AlignCenter ); grid-> addWidget ( alarmSlider, 1, 3, AlignCenter ); alarmLed = new OLedBox ( yellow, this ); alarmLed-> setFocusPolicy ( QWidget::NoFocus ); alarmLed-> setFixedSize ( 16, 16 ); grid-> addWidget ( alarmLed, 2, 3, AlignCenter ); if ( !has_wav_alarm ) { alarmSlider-> hide ( ); alarmLabel-> hide ( ); alarmLed-> hide ( ); } grid-> addWidget ( new QLabel ( tr( "Enable Sounds for:" ), this ), 0, 6, AlignVCenter | AlignLeft ); vbox = new QVBoxLayout ( ); vbox-> setSpacing ( 4 ); grid-> addMultiCellLayout ( vbox, 1, 2, 6, 6 ); tapBox = new QCheckBox ( tr( "Screen Taps" ), this ); tapBox-> setFocusPolicy ( QWidget::NoFocus ); vbox-> addWidget ( tapBox, AlignVCenter | AlignLeft ); keyBox = new QCheckBox ( tr( "Key Clicks" ), this ); keyBox-> setFocusPolicy ( QWidget::NoFocus ); vbox-> addWidget ( keyBox, AlignVCenter | AlignLeft ); alarmBox = new QCheckBox ( tr( "Alarm Sound" ), this ); alarmBox-> setFocusPolicy ( QWidget::NoFocus ); vbox-> addWidget ( alarmBox, AlignVCenter | AlignLeft ); if ( has_wav_alarm ) { alarmBox-> hide ( ); } vbox-> addStretch ( 100 ); setFixedSize ( sizeHint ( )); setFocusPolicy ( QWidget::NoFocus ); rateTimer = new QTimer( this ); - connect ( rateTimer, SIGNAL( timeout ( )), this, SLOT( rateTimerDone ( ))); + connect ( rateTimer, SIGNAL( timeout()), this, SLOT( rateTimerDone())); - connect ( upButton, SIGNAL( pressed ( )), this, SLOT( buttonChanged ( ))); - connect ( upButton, SIGNAL( released ( )), this, SLOT( buttonChanged ( ))); - connect ( downButton, SIGNAL( pressed ( )), this, SLOT( buttonChanged ( ))); - connect ( downButton, SIGNAL( released ( )), this, SLOT( buttonChanged ( ))); + connect ( upButton, SIGNAL( pressed()), this, SLOT( buttonChanged())); + connect ( upButton, SIGNAL( released()), this, SLOT( buttonChanged())); + connect ( downButton, SIGNAL( pressed()), this, SLOT( buttonChanged())); + connect ( downButton, SIGNAL( released()), this, SLOT( buttonChanged())); - connect ( micSlider, SIGNAL( valueChanged ( int )), this, SLOT( micMoved( int ))); - connect ( volSlider, SIGNAL( valueChanged ( int )), this, SLOT( volMoved( int ))); - connect ( alarmSlider, SIGNAL( valueChanged ( int )), this, SLOT( alarmMoved( int ))); - connect ( bassSlider, SIGNAL( valueChanged ( int )), this, SLOT( bassMoved( int ))); - connect ( trebleSlider, SIGNAL( valueChanged ( int )), this, SLOT( trebleMoved( int ))); + connect ( micSlider, SIGNAL( valueChanged(int)), this, SLOT( micMoved(int))); + connect ( volSlider, SIGNAL( valueChanged(int)), this, SLOT( volMoved(int))); + connect ( alarmSlider, SIGNAL( valueChanged(int)), this, SLOT( alarmMoved(int))); + connect ( bassSlider, SIGNAL( valueChanged(int)), this, SLOT( bassMoved(int))); + connect ( trebleSlider, SIGNAL( valueChanged(int)), this, SLOT( trebleMoved(int))); - connect ( volLed, SIGNAL( toggled ( bool )), this, SLOT( volMuteToggled ( bool ))); - connect ( micLed, SIGNAL( toggled ( bool )), this, SLOT( micMuteToggled ( bool ))); - connect ( alarmLed, SIGNAL( toggled ( bool )), this, SLOT( alarmSoundToggled ( bool ))); + connect ( volLed, SIGNAL( toggled(bool)), this, SLOT( volMuteToggled(bool))); + connect ( micLed, SIGNAL( toggled(bool)), this, SLOT( micMuteToggled(bool))); + connect ( alarmLed, SIGNAL( toggled(bool)), this, SLOT( alarmSoundToggled(bool))); - connect ( alarmBox, SIGNAL( toggled ( bool )), this, SLOT( alarmSoundToggled ( bool ))); - connect ( keyBox, SIGNAL( toggled ( bool )), this, SLOT( keyClickToggled ( bool ))); - connect ( tapBox, SIGNAL( toggled ( bool )), this, SLOT( screenTapToggled ( bool ))); + connect ( alarmBox, SIGNAL( toggled(bool)), this, SLOT( alarmSoundToggled(bool))); + connect ( keyBox, SIGNAL( toggled(bool)), this, SLOT( keyClickToggled(bool))); + connect ( tapBox, SIGNAL( toggled(bool)), this, SLOT( screenTapToggled(bool))); // initialize variables readConfig ( true ); // initialize the config file, in case some entries are missing writeConfigEntry ( "VolumePercent", m_vol_percent, UPD_None ); writeConfigEntry ( "BassPercent", m_vol_percent, UPD_None ); writeConfigEntry ( "TreblePercent", m_vol_percent, UPD_None ); writeConfigEntry ( "Mute", m_vol_muted, UPD_None ); writeConfigEntry ( "AlarmPercent", m_alarm_percent, UPD_None ); writeConfigEntry ( "TouchSound", m_snd_touch, UPD_None ); writeConfigEntry ( "KeySound", m_snd_key, UPD_None ); writeConfigEntry ( "AlarmSound", m_snd_alarm, UPD_Vol ); writeConfigEntry ( "Mic", m_mic_percent, UPD_None ); writeConfigEntry ( "MicMute", m_mic_muted, UPD_Mic ); } bool VolumeControl::volMuted ( ) const { return m_vol_muted; } int VolumeControl::volPercent ( ) const { return m_vol_percent; } void VolumeControl::keyPressEvent ( QKeyEvent *e ) { switch ( e-> key ( )) { case Key_Up: volSlider-> subtractStep ( ); break; case Key_Down: volSlider-> addStep ( ); break; case Key_Space: volLed-> toggle ( ); break; case Key_Escape: hide ( ); break; } } void VolumeControl::buttonChanged ( ) { if ( upButton-> isDown ( ) || downButton->isDown ( )) { rateTimerDone ( ); // Call it one time manually, otherwise it wont get // called at all when a button is pressed for a time // shorter than RATE_TIMER_INTERVAL. rateTimer-> start ( RATE_TIMER_INTERVAL, false ); } else rateTimer-> stop ( ); } void VolumeControl::rateTimerDone ( ) { if ( upButton-> isDown ( )) volSlider-> setValue ( volSlider-> value ( ) - 2 ); else // if ( downButton-> isDown ( )) volSlider-> setValue ( volSlider-> value ( ) + 2 ); } void VolumeControl::show ( bool /*showMic*/ ) { readConfig ( ); QPoint curPos = m_icon-> mapToGlobal ( QPoint ( 0, 0 )); int w = sizeHint ( ). width ( ); int x = curPos.x ( ) - ( w / 2 ); if (( x + w ) > QPEApplication::desktop ( )-> width ( )) x = QPEApplication::desktop ( )-> width ( ) - w; move ( x, curPos. y ( ) - sizeHint ( ). height ( )); QFrame::show ( ); } void VolumeControl::readConfig ( bool force ) { Config cfg ( "qpe" ); cfg. setGroup ( "Volume" ); int old_vp = m_vol_percent; int old_mp = m_mic_percent; int old_bass = m_bass_percent; int old_treble = m_treble_percent; bool old_vm = m_vol_muted; bool old_mm = m_mic_muted; bool old_sk = m_snd_key; bool old_st = m_snd_touch; bool old_sa = m_snd_alarm; int old_ap = m_alarm_percent; m_vol_percent = cfg. readNumEntry ( "VolumePercent", 50 ); m_mic_percent = cfg. readNumEntry ( "Mic", 50 ); m_bass_percent = cfg. readNumEntry ( "BassPercent", 50 ); m_treble_percent = cfg. readNumEntry ( "TreblePercent", 50 ); m_vol_muted = cfg. readBoolEntry ( "Mute", 0 ); m_mic_muted = cfg. readBoolEntry ( "MicMute", 0 ); m_snd_key = cfg. readBoolEntry ( "KeySound", 0 ); m_snd_touch = cfg. readBoolEntry ( "TouchSound", 0 ); m_snd_alarm = cfg. readBoolEntry ( "AlarmSound", 1 ); m_alarm_percent = cfg. readNumEntry ( "AlarmPercent", 65 ); if ( force || ( m_vol_percent != old_vp )) volSlider-> setValue ( 100 - m_vol_percent ); if ( force || ( m_mic_percent != old_mp )) micSlider-> setValue ( 100 - m_mic_percent ); if ( force || ( m_alarm_percent != old_ap )) alarmSlider-> setValue ( 100 - m_alarm_percent ); if ( force || ( m_bass_percent != old_bass )) bassSlider-> setValue ( 100 - m_bass_percent ); if ( force || ( m_treble_percent != old_treble )) trebleSlider-> setValue ( 100 - m_treble_percent ); if ( force || ( m_vol_muted != old_vm )) volLed-> setOn ( !m_vol_muted ); if ( force || ( m_mic_muted != old_mm )) micLed-> setOn ( !m_mic_muted ); if ( force || ( m_snd_alarm != old_sa )) alarmLed-> setOn ( m_snd_alarm ); if ( force || ( m_snd_key != old_sk )) keyBox-> setChecked ( m_snd_key ); if ( force || ( m_snd_touch != old_st )) tapBox-> setChecked ( m_snd_touch ); if ( force || ( m_snd_alarm != old_sa )) alarmBox-> setChecked ( m_snd_alarm ); } void VolumeControl::volumeChanged ( bool /*nowMuted*/ ) { int prevVol = m_vol_percent; bool prevMute = m_vol_muted; readConfig ( ); // Handle case where muting it toggled if ( m_vol_muted != prevMute ) m_icon-> redraw ( true ); else if ( prevVol != m_vol_percent ) // Avoid over repainting m_icon-> redraw ( false ); } void VolumeControl::micChanged ( bool nowMuted ) { if ( !nowMuted ) readConfig ( ); m_mic_muted = nowMuted; } void VolumeControl::screenTapToggled ( bool b ) { m_snd_touch = b; writeConfigEntry ( "TouchSound", m_snd_touch, UPD_Vol ); } void VolumeControl::keyClickToggled ( bool b ) { m_snd_key = b; writeConfigEntry ( "KeySound", m_snd_key, UPD_Vol ); } void VolumeControl::alarmSoundToggled ( bool b ) { m_snd_alarm = b; writeConfigEntry ( "AlarmSound", m_snd_alarm, UPD_Vol ); } void VolumeControl::volMuteToggled ( bool b ) { m_vol_muted = !b; m_icon-> redraw ( true ); writeConfigEntry ( "Mute", m_vol_muted, UPD_Vol ); } void VolumeControl::micMuteToggled ( bool b ) { m_mic_muted = !b; writeConfigEntry ( "MicMute", m_mic_muted, UPD_Mic ); } void VolumeControl::volMoved ( int percent ) { m_vol_percent = 100 - percent; // clamp volume percent to be between 0 and 100 m_vol_percent = ( m_vol_percent < 0 ) ? 0 : (( m_vol_percent > 100 ) ? 100 : m_vol_percent ); // repaint just the little volume rectangle m_icon-> redraw ( false ); writeConfigEntry ( "VolumePercent", m_vol_percent, UPD_Vol ); } void VolumeControl::micMoved ( int percent ) { m_mic_percent = 100 - percent; // clamp volume percent to be between 0 and 100 m_mic_percent = ( m_mic_percent < 0 ) ? 0 : (( m_mic_percent > 100 ) ? 100 : m_mic_percent ); writeConfigEntry ( "Mic", m_mic_percent, UPD_Mic ); } void VolumeControl::alarmMoved ( int percent ) { m_alarm_percent = 100 - percent; // clamp volume percent to be between 0 and 100 m_alarm_percent = ( m_alarm_percent < 0 ) ? 0 : (( m_alarm_percent > 100 ) ? 100 : m_alarm_percent ); writeConfigEntry ( "AlarmPercent", m_alarm_percent, UPD_None ); } void VolumeControl::bassMoved ( int percent ) { m_bass_percent = 100 - percent; // clamp bass percent to be between 0 and 100 m_bass_percent = ( m_bass_percent < 0 ) ? 0 : (( m_bass_percent > 100 ) ? 100 : m_bass_percent ); writeConfigEntry ( "BassPercent", m_bass_percent, UPD_Bass ); } void VolumeControl::trebleMoved ( int percent ) { m_treble_percent = 100 - percent; // clamp treble percent to be between 0 and 100 m_treble_percent = ( m_treble_percent < 0 ) ? 0 : (( m_treble_percent > 100 ) ? 100 : m_treble_percent ); writeConfigEntry ( "TreblePercent", m_treble_percent, UPD_Treble ); } void VolumeControl::writeConfigEntry ( const char *entry, int val, eUpdate upd ) { Config cfg ( "qpe" ); cfg. setGroup ( "Volume" ); cfg. writeEntry ( entry, val ); // cfg. write ( ); #if ( defined Q_WS_QWS || defined(_WS_QWS_) ) && !defined(QT_NO_COP) switch ( upd ) { case UPD_Vol: { QCopEnvelope ( "QPE/System", "volumeChange(bool)" ) << m_vol_muted; break; } case UPD_Mic: { QCopEnvelope ( "QPE/System", "micChange(bool)" ) << m_mic_muted; break; } case UPD_Bass: { QCopEnvelope ( "QPE/System", "bassChange(bool)" ) << true; break; } case UPD_Treble: { QCopEnvelope ( "QPE/System", "trebleChange(bool)" ) << true; break; } case UPD_None: break; } #endif } //=========================================================================== VolumeApplet::VolumeApplet( QWidget *parent, const char *name ) : QWidget( parent, name ) { setFixedWidth ( AppLnk::smallIconSize() ); setFixedHeight ( AppLnk::smallIconSize()+4 ); m_pixmap = new QPixmap ( Resource::loadPixmap ( "volume" )); m_dialog = new VolumeControl ( this, true, this, "volumecontrol" ); - connect ( qApp, SIGNAL( volumeChanged ( bool )), m_dialog, SLOT( volumeChanged( bool ))); - connect ( qApp, SIGNAL( micChanged ( bool )), m_dialog, SLOT ( micChanged( bool ))); + connect ( qApp, SIGNAL( volumeChanged(bool)), m_dialog, SLOT( volumeChanged(bool))); + connect ( qApp, SIGNAL( micChanged(bool)), m_dialog, SLOT ( micChanged(bool))); } VolumeApplet::~VolumeApplet() { delete m_pixmap; } int VolumeApplet::position() { return 6; } void VolumeApplet::mousePressEvent ( QMouseEvent * ) { if ( m_dialog-> isVisible ( )) m_dialog-> hide ( ); else m_dialog-> show ( true ); } void VolumeApplet::redraw ( bool all ) { if ( all ) repaint ( true ); else repaint ( 2, height ( ) - 3, width ( ) - 4, 2, false ); } void VolumeApplet::paintEvent ( QPaintEvent * ) { QPainter p ( this ); p. drawPixmap ( (width()- m_pixmap->width())/2, QMAX( (height()-4-m_pixmap->height() )/2, 1), *m_pixmap ); p. setPen ( darkGray ); p. drawRect ( 1, height() - 4, width() - 2, 4 ); int pixelsWide = m_dialog-> volPercent ( ) * ( width() - 4 ) / 100; p. fillRect ( 2, height() - 3, pixelsWide, 2, red ); p. fillRect ( pixelsWide + 2, height() - 3, width() - 4 - pixelsWide, 2, lightGray ); if ( m_dialog-> volMuted ( )) { p. setPen ( red ); p. drawLine ( 1, 2, width() - 2, height() - 5 ); p. drawLine ( 1, 3, width() - 2, height() - 4 ); p. drawLine ( width() - 2, 2, 1, height() - 5 ); p. drawLine ( width() - 2, 3, 1, height() - 4 ); } } Q_EXPORT_INTERFACE() { Q_CREATE_INSTANCE( OTaskbarAppletWrapper<VolumeApplet> ); } diff --git a/core/apps/embeddedkonsole/commandeditdialog.cpp b/core/apps/embeddedkonsole/commandeditdialog.cpp index c0066d8..6587b26 100644 --- a/core/apps/embeddedkonsole/commandeditdialog.cpp +++ b/core/apps/embeddedkonsole/commandeditdialog.cpp @@ -1,191 +1,191 @@ //comandeditdialog.cpp #include "commandeditdialog.h" #include "playlistselection.h" #include <qpe/config.h> #include <qpe/resource.h> #include <qtoolbutton.h> #include <qlineedit.h> #include <qheader.h> #include <qlabel.h> #include "smallcommandeditdialogbase.h" CommandEditDialog::CommandEditDialog(QWidget *parent, const char* name, WFlags fl ) : CommandEditDialogBase(parent, name, TRUE, fl) { m_SuggestedCommandList->addColumn( tr("Command Selection") ); m_SuggestedCommandList->header()->hide(); m_SuggestedCommandList->setSorting(-1,FALSE); m_SuggestedCommandList->clearSelection(); m_SuggestedCommandList->setSorting(0,TRUE); QListViewItem *item; item = new QListViewItem( m_SuggestedCommandList,"export "); item = new QListViewItem( m_SuggestedCommandList,"ifconfig "); item = new QListViewItem( m_SuggestedCommandList,"ipkg "); item = new QListViewItem( m_SuggestedCommandList,"gzip "); item = new QListViewItem( m_SuggestedCommandList,"gunzip "); item = new QListViewItem( m_SuggestedCommandList,"chgrp "); item = new QListViewItem( m_SuggestedCommandList,"chown "); item = new QListViewItem( m_SuggestedCommandList,"date "); item = new QListViewItem( m_SuggestedCommandList,"dd "); item = new QListViewItem( m_SuggestedCommandList,"dmesg "); item = new QListViewItem( m_SuggestedCommandList,"fuser "); item = new QListViewItem( m_SuggestedCommandList,"hostname "); item = new QListViewItem( m_SuggestedCommandList,"kill "); item = new QListViewItem( m_SuggestedCommandList,"killall "); item = new QListViewItem( m_SuggestedCommandList,"ln "); item = new QListViewItem( m_SuggestedCommandList,"ln -s "); item = new QListViewItem( m_SuggestedCommandList,"lsmod"); item = new QListViewItem( m_SuggestedCommandList,"depmod -a"); item = new QListViewItem( m_SuggestedCommandList,"modprobe "); item = new QListViewItem( m_SuggestedCommandList,"mount "); item = new QListViewItem( m_SuggestedCommandList,"more "); item = new QListViewItem( m_SuggestedCommandList,"sort "); item = new QListViewItem( m_SuggestedCommandList,"touch "); item = new QListViewItem( m_SuggestedCommandList,"umount "); item = new QListViewItem( m_SuggestedCommandList,"mknod "); item = new QListViewItem( m_SuggestedCommandList,"netstat "); item = new QListViewItem( m_SuggestedCommandList,"route "); item = new QListViewItem( m_SuggestedCommandList,"cardctl eject "); m_SuggestedCommandList->setSelected(m_SuggestedCommandList->firstChild(),TRUE); m_SuggestedCommandList->sort(); - connect( m_SuggestedCommandList, SIGNAL( clicked( QListViewItem * ) ), m_PlayListSelection, SLOT( addToSelection( QListViewItem *) ) ); + connect( m_SuggestedCommandList, SIGNAL( clicked(QListViewItem*) ), m_PlayListSelection, SLOT( addToSelection(QListViewItem*) ) ); ToolButton1->setTextLabel("new"); ToolButton1->setPixmap(Resource::loadPixmap("new")); ToolButton1->setAutoRaise(TRUE); ToolButton1->setFocusPolicy(QWidget::NoFocus); connect(ToolButton1,SIGNAL(clicked()),this,SLOT(showAddDialog())); ToolButton2->setTextLabel("edit"); ToolButton2->setPixmap(Resource::loadPixmap("edit")); ToolButton2->setAutoRaise(TRUE); ToolButton2->setFocusPolicy(QWidget::NoFocus); connect(ToolButton2,SIGNAL(clicked()),this,SLOT(showEditDialog())); ToolButton3->setTextLabel("delete"); ToolButton3->setPixmap(Resource::loadPixmap("editdelete")); ToolButton3->setAutoRaise(TRUE); ToolButton3->setFocusPolicy(QWidget::NoFocus); connect(ToolButton3,SIGNAL(clicked()),m_PlayListSelection,SLOT(removeSelected())); ToolButton4->setTextLabel("up"); ToolButton4->setPixmap(Resource::loadPixmap("up")); ToolButton4->setAutoRaise(TRUE); ToolButton4->setFocusPolicy(QWidget::NoFocus); connect(ToolButton4,SIGNAL(clicked()),m_PlayListSelection,SLOT(moveSelectedUp())); ToolButton5->setTextLabel("down"); ToolButton5->setPixmap(Resource::loadPixmap("down")); ToolButton5->setAutoRaise(TRUE); ToolButton5->setFocusPolicy(QWidget::NoFocus); connect(ToolButton5,SIGNAL(clicked()),m_PlayListSelection,SLOT(moveSelectedDown())); QListViewItem *current = m_SuggestedCommandList->selectedItem(); if ( current ) item->moveItem( current ); m_SuggestedCommandList->setSelected( item, TRUE ); m_SuggestedCommandList->ensureItemVisible( m_SuggestedCommandList->selectedItem() ); Config cfg( "Konsole" ); cfg.setGroup("Commands"); if (cfg.readEntry("Commands Set","FALSE") == "TRUE") { for (int i = 0; i < 100; i++) { QString tmp; tmp = cfg.readEntry( QString::number(i),""); if (!tmp.isEmpty()) m_PlayListSelection->addStringToSelection(tmp); } } else { m_PlayListSelection->addStringToSelection("ls "); m_PlayListSelection->addStringToSelection("cardctl eject"); m_PlayListSelection->addStringToSelection("cat "); m_PlayListSelection->addStringToSelection("cd "); m_PlayListSelection->addStringToSelection("chmod "); m_PlayListSelection->addStringToSelection("cp "); m_PlayListSelection->addStringToSelection("dc "); m_PlayListSelection->addStringToSelection("df "); m_PlayListSelection->addStringToSelection("dmesg"); m_PlayListSelection->addStringToSelection("echo "); m_PlayListSelection->addStringToSelection("env"); m_PlayListSelection->addStringToSelection("find "); m_PlayListSelection->addStringToSelection("free"); m_PlayListSelection->addStringToSelection("grep "); m_PlayListSelection->addStringToSelection("ifconfig "); m_PlayListSelection->addStringToSelection("ipkg "); m_PlayListSelection->addStringToSelection("mkdir "); m_PlayListSelection->addStringToSelection("mv "); m_PlayListSelection->addStringToSelection("nc localhost 7776"); m_PlayListSelection->addStringToSelection("nc localhost 7777"); m_PlayListSelection->addStringToSelection("nslookup "); m_PlayListSelection->addStringToSelection("ping "); m_PlayListSelection->addStringToSelection("ps aux"); m_PlayListSelection->addStringToSelection("pwd "); m_PlayListSelection->addStringToSelection("rm "); m_PlayListSelection->addStringToSelection("rmdir "); m_PlayListSelection->addStringToSelection("route "); m_PlayListSelection->addStringToSelection("set "); m_PlayListSelection->addStringToSelection("traceroute"); } } CommandEditDialog::~CommandEditDialog() { } void CommandEditDialog::accept() { int i = 0; Config *cfg = new Config("Konsole"); cfg->setGroup("Commands"); cfg->clearGroup(); QListViewItemIterator it( m_PlayListSelection ); for ( ; it.current(); ++it ) { // qDebug(it.current()->text(0)); cfg->writeEntry(QString::number(i),it.current()->text(0)); i++; } cfg->writeEntry("Commands Set","TRUE"); // qDebug("CommandEditDialog::accept() - written"); delete cfg; emit commandsEdited(); close(); } void CommandEditDialog::showEditDialog() { editCommandBase *d = new editCommandBase(this,"smalleditdialog", TRUE); d->setCaption("Edit command"); d->TextLabel->setText("Edit command:"); d->commandEdit->setText(m_PlayListSelection->currentItem()->text(0)); int i = d->exec(); if ((i==1) && (!(d->commandEdit->text()).isEmpty())) m_PlayListSelection->currentItem()->setText(0,(d->commandEdit->text())); } void CommandEditDialog::showAddDialog() { editCommandBase *d = new editCommandBase(this,"smalleditdialog", TRUE); int i = d->exec(); if ((i==1) && (!(d->commandEdit->text()).isEmpty())) m_PlayListSelection->addStringToSelection(d->commandEdit->text()); } diff --git a/core/apps/embeddedkonsole/session.cpp b/core/apps/embeddedkonsole/session.cpp index 043b8db..a94712a 100644 --- a/core/apps/embeddedkonsole/session.cpp +++ b/core/apps/embeddedkonsole/session.cpp @@ -1,160 +1,160 @@ /* -------------------------------------------------------------------------- */ /* */ /* Ported Konsole to Qt/Embedded */ /* */ /* Copyright (C) 2000 by John Ryland <jryland@trolltech.com> */ /* */ /* -------------------------------------------------------------------------- */ #include "session.h" // #include <kdebug.h> #include <stdlib.h> #define HERE fprintf(stderr,"%s(%d): here\n",__FILE__,__LINE__) /*! \class TESession Sessions are combinations of TEPTy and Emulations. The stuff in here does not belong to the terminal emulation framework, but to main.C. It serves it's duty by providing a single reference to TEPTy/Emulation pairs. In fact, it is only there to demonstrate one of the abilities of the framework - multible sessions. */ TESession::TESession(QMainWindow* main, TEWidget* _te, const char* _pgm, QStrList & _args, const char *_term) : schema_no(0), font_no(3), pgm(_pgm), args(_args) { te = _te; term = _term; // sh = new TEPty(); sh = new MyPty(); em = new TEmuVt102(te); sh->setSize(te->Lines(),te->Columns()); // not absolutely nessesary QObject::connect( sh,SIGNAL(block_in(const char*,int)), em,SLOT(onRcvBlock(const char*,int)) ); QObject::connect( em,SIGNAL(ImageSizeChanged(int,int)), sh,SLOT(setSize(int,int))); // 'main' should do those connects itself, somehow. // These aren't KTMW's slots, but konsole's.(David) /* QObject::connect( em,SIGNAL(ImageSizeChanged(int,int)), main,SLOT(notifySize(int,int))); */ QObject::connect( em,SIGNAL(sndBlock(const char*,int)), sh,SLOT(send_bytes(const char*,int)) ); QObject::connect( em,SIGNAL(changeColumns(int)), main,SLOT(changeColumns(int)) ); - QObject::connect( em,SIGNAL(changeTitle(int, const QString&)), - this,SLOT(changeTitle(int, const QString&)) ); + QObject::connect( em,SIGNAL(changeTitle(int,const QString&)), + this,SLOT(changeTitle(int,const QString&)) ); QObject::connect( sh,SIGNAL(done(int)), this,SLOT(done(int)) ); } void TESession::run() { //kdDebug() << "Running the session!" << pgm << "\n"; sh->run(pgm,args,term.data(),FALSE); } void TESession::kill(int ) // signal) { // sh->kill(signal); } TESession::~TESession() { - QObject::disconnect( sh, SIGNAL( done( int ) ), - this, SLOT( done( int ) ) ); + QObject::disconnect( sh, SIGNAL( done(int) ), + this, SLOT( done(int) ) ); delete em; delete sh; } void TESession::setConnect(bool c) { em->setConnect(c); } void TESession::done(int status) { emit done(te,status); } void TESession::terminate() { delete this; } TEmulation* TESession::getEmulation() { return em; } // following interfaces might be misplaced /// int TESession::schemaNo() { return schema_no; } int TESession::keymap() { return keymap_no; } int TESession::fontNo() { return font_no; } const char* TESession::emuName() { return term.data(); } void TESession::setSchemaNo(int sn) { schema_no = sn; } void TESession::setKeymapNo(int kn) { keymap_no = kn; em->setKeytrans(kn); } void TESession::setFontNo(int fn) { font_no = fn; } void TESession::changeTitle(int, const QString& title) { this->title = title; emit changeTitle(te, title); } const QString& TESession::Title() { return title; } void TESession::setHistory(bool on) { em->setHistory( on ); } bool TESession::history() { return em->history(); } // #include "session.moc" diff --git a/core/apps/helpbrowser/helpbrowser.cpp b/core/apps/helpbrowser/helpbrowser.cpp index 8fb0161..336d9fb 100644 --- a/core/apps/helpbrowser/helpbrowser.cpp +++ b/core/apps/helpbrowser/helpbrowser.cpp @@ -1,228 +1,228 @@ /********************************************************************** ** Copyright (C) 2000-2002 Trolltech AS. All rights reserved. ** ** This file is part of the Qtopia Environment. ** ** This file may be distributed and/or modified under the terms of the ** GNU General Public License version 2 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. ** ** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE ** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. ** ** See http://www.trolltech.com/gpl/ for GPL licensing information. ** ** Contact info@trolltech.com if any conditions of this licensing are ** not clear to you. ** **********************************************************************/ #define QTOPIA_INTERNAL_LANGLIST #include "helpbrowser.h" #include <qpe/qpeapplication.h> #include <qpe/resource.h> #include <qmenubar.h> #include <qtoolbar.h> #include <qpe/qcopenvelope_qws.h> #include <qfileinfo.h> #include <qaction.h> #include <cctype> #include "magictextbrowser.h" HelpBrowser::HelpBrowser( QWidget* parent, const char *name, WFlags f ) : QMainWindow( parent, name, f ), selectedURL() { init( "index.html" ); } void HelpBrowser::init( const QString& _home ) { setIcon( Resource::loadPixmap( "HelpBrowser" ) ); setBackgroundMode( PaletteButton ); browser = new MagicTextBrowser( this ); browser->setFrameStyle( QFrame::Panel | QFrame::Sunken ); connect( browser, SIGNAL( textChanged() ), this, SLOT( textChanged() ) ); setCentralWidget( browser ); setToolBarsMovable( FALSE ); if ( !_home.isEmpty() ) browser->setSource( _home ); QToolBar* toolbar = new QToolBar( this ); toolbar->setHorizontalStretchable( TRUE ); QMenuBar *menu = new QMenuBar( toolbar ); toolbar = new QToolBar( this ); // addToolBar( toolbar, "Toolbar"); QPopupMenu* go = new QPopupMenu( this ); backAction = new QAction( tr( "Backward" ), Resource::loadIconSet( "back" ), QString::null, 0, this, 0 ); connect( backAction, SIGNAL( activated() ), browser, SLOT( backward() ) ); - connect( browser, SIGNAL( backwardAvailable( bool ) ), - backAction, SLOT( setEnabled( bool ) ) ); + connect( browser, SIGNAL( backwardAvailable(bool) ), + backAction, SLOT( setEnabled(bool) ) ); backAction->addTo( go ); backAction->addTo( toolbar ); backAction->setEnabled( FALSE ); forwardAction = new QAction( tr( "Forward" ), Resource::loadIconSet( "forward" ), QString::null, 0, this, 0 ); connect( forwardAction, SIGNAL( activated() ), browser, SLOT( forward() ) ); - connect( browser, SIGNAL( forwardAvailable( bool ) ), - forwardAction, SLOT( setEnabled( bool ) ) ); + connect( browser, SIGNAL( forwardAvailable(bool) ), + forwardAction, SLOT( setEnabled(bool) ) ); forwardAction->addTo( go ); forwardAction->addTo( toolbar ); forwardAction->setEnabled( FALSE ); QAction *a = new QAction( tr( "Home" ), Resource::loadIconSet( "home" ), QString::null, 0, this, 0 ); connect( a, SIGNAL( activated() ), browser, SLOT( home() ) ); a->addTo( go ); a->addTo( toolbar ); bookm = new QPopupMenu( this ); bookm->insertItem( tr( "Add Bookmark" ), this, SLOT( addBookmark() ) ); bookm->insertItem( tr( "Remove from Bookmarks" ), this, SLOT( removeBookmark() ) ); bookm->insertSeparator(); - connect( bookm, SIGNAL( activated( int ) ), - this, SLOT( bookmChosen( int ) ) ); + connect( bookm, SIGNAL( activated(int) ), + this, SLOT( bookmChosen(int) ) ); readBookmarks(); menu->insertItem( tr("Go"), go ); menu->insertItem( tr( "Bookmarks" ), bookm ); resize( 240, 300 ); browser->setFocus(); browser->setFrameStyle( QFrame::NoFrame ); #if !defined(QT_NO_COP) QCopChannel *addressChannel = new QCopChannel("QPE/HelpBrowser" , this ); - connect (addressChannel, SIGNAL( received(const QCString &, const QByteArray &)), - this, SLOT ( appMessage(const QCString &, const QByteArray &) ) ); + connect (addressChannel, SIGNAL( received(const QCString&,const QByteArray&)), + this, SLOT ( appMessage(const QCString&,const QByteArray&) ) ); #endif - connect( qApp, SIGNAL(appMessage(const QCString&, const QByteArray&)), - this, SLOT(appMessage(const QCString&, const QByteArray&)) ); + connect( qApp, SIGNAL(appMessage(const QCString&,const QByteArray&)), + this, SLOT(appMessage(const QCString&,const QByteArray&)) ); } void HelpBrowser::appMessage(const QCString& msg, const QByteArray& data) { qDebug("reached appMessage"); if ( msg == "showFile(QString)" ) { QDataStream ds(data,IO_ReadOnly); QString fn; ds >> fn; setDocument( fn ); QPEApplication::setKeepRunning(); showMaximized(); setActiveWindow(); raise(); } } void HelpBrowser::setDocument( const QString &doc ) { if ( !doc.isEmpty() ) browser->setSource( doc ); raise(); } void HelpBrowser::textChanged() { if ( browser->documentTitle().isNull() ) setCaption( tr("Help Browser") ); else setCaption( browser->documentTitle() ) ; selectedURL = caption(); } HelpBrowser::~HelpBrowser() { QStringList bookmarks; QMap<int, Bookmark>::Iterator it2 = mBookmarks.begin(); for ( ; it2 != mBookmarks.end(); ++it2 ) bookmarks.append( (*it2).name + "=" + (*it2).file ); QFile f2( Global::applicationFileName("helpbrowser", "bookmarks") ); if ( f2.open( IO_WriteOnly ) ) { QDataStream s2( &f2 ); s2 << bookmarks; f2.close(); } } void HelpBrowser::pathSelected( const QString &_path ) { browser->setSource( _path ); } void HelpBrowser::readBookmarks() { QString file = Global::applicationFileName("helpbrowser", "bookmarks"); if ( QFile::exists( file ) ) { QStringList bookmarks; QFile f( file ); if ( f.open( IO_ReadOnly ) ) { QDataStream s( &f ); s >> bookmarks; f.close(); } QStringList::Iterator it = bookmarks.begin(); for ( ; it != bookmarks.end(); ++it ) { Bookmark b; QString current = *it; int equal = current.find( "=" ); if ( equal < 1 || equal == (int)current.length() - 1 ) continue; b.name = current.left( equal ); b.file = current.mid( equal + 1 ); mBookmarks[ bookm->insertItem( b.name ) ] = b; } } } void HelpBrowser::bookmChosen( int i ) { if ( mBookmarks.contains( i ) ) browser->setSource( mBookmarks[ i ].file ); } void HelpBrowser::addBookmark() { Bookmark b; b.name = browser->documentTitle(); b.file = browser->source(); if (b.name.isEmpty() ) { b.name = b.file.left( b.file.length() - 5 ); // remove .html } QMap<int, Bookmark>::Iterator it; for( it = mBookmarks.begin(); it != mBookmarks.end(); ++it ) if ( (*it).file == b.file ) return; mBookmarks[ bookm->insertItem( b.name ) ] = b; } void HelpBrowser::removeBookmark() { QString file = browser->source(); QMap<int, Bookmark>::Iterator it = mBookmarks.begin(); for( ; it != mBookmarks.end(); ++it ) if ( (*it).file == file ) { bookm->removeItem( it.key() ); mBookmarks.remove( it ); break; } } diff --git a/core/apps/textedit/textedit.cpp b/core/apps/textedit/textedit.cpp index 55725cc..b54da34 100644 --- a/core/apps/textedit/textedit.cpp +++ b/core/apps/textedit/textedit.cpp @@ -1,779 +1,779 @@ /********************************************************************** // textedit.cpp ** Copyright (C) 2000 Trolltech AS. All rights reserved. ** ** This file is part of Opie Environment. ** ** This file may be distributed and/or modified under the terms of the ** GNU General Public License version 2 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. ** **********************************************************************/ // changes added by L. J. Potter Sun 02-17-2002 21:31:31 #include "textedit.h" #include "filePermissions.h" #include <opie2/ofileselector.h> #include <opie2/ofiledialog.h> #include <opie2/ofontselector.h> #include <qpe/resource.h> #include <qpe/config.h> #include <qpe/qpeapplication.h> #include <qmenubar.h> #include <qtoolbar.h> #include <qtextstream.h> #include <qclipboard.h> #include <qaction.h> #include <qlineedit.h> #include <qmessagebox.h> #include <qlayout.h> #include <qtimer.h> #include <qdir.h> #include <unistd.h> #include <sys/stat.h> #include <stdlib.h> //getenv using Opie::OFileDialog; using Opie::OFileSelector; using Opie::OFontSelector; #if QT_VERSION < 300 class QpeEditor : public QMultiLineEdit { public: QpeEditor( QWidget *parent, const char * name = 0 ) : QMultiLineEdit( parent, name ) { clearTableFlags(); setTableFlags( Tbl_vScrollBar | Tbl_autoHScrollBar ); } void find( const QString &txt, bool caseSensitive, bool backwards ); protected: bool markIt; int line1, line2, col1, col2; void mousePressEvent( QMouseEvent * ); void mouseReleaseEvent( QMouseEvent * ); //public slots: /* signals: void notFound(); void searchWrapped(); */ private: }; void QpeEditor::mousePressEvent( QMouseEvent *e ) { switch(e->button()) { case RightButton: { //rediculous workaround for qt popup menu //and the hold right click mechanism this->setSelection( line1, col1, line2, col2); QMultiLineEdit::mousePressEvent( e ); markIt = false; } break; default: { if(!markIt) { int line, col; this->getCursorPosition(&line, &col); line1=line2=line; col1=col2=col; } QMultiLineEdit::mousePressEvent( e ); } break; }; } void QpeEditor::mouseReleaseEvent( QMouseEvent * ) { if(this->hasMarkedText()) { markIt = true; this->getMarkedRegion( &line1, &col1, &line2, & col2 ); } else { markIt = false; } } void QpeEditor::find ( const QString &txt, bool caseSensitive, bool backwards ) { static bool wrap = false; int line, col; if ( wrap ) { if ( !backwards ) line = col = 0; wrap = false; // emit searchWrapped(); } else { getCursorPosition( &line, &col ); } //ignore backwards for now.... if ( !backwards ) { for ( ; ; ) { if ( line >= numLines() ) { wrap = true; //emit notFound(); break; } int findCol = getString( line )->find( txt, col, caseSensitive ); if ( findCol >= 0 ) { setCursorPosition( line, findCol, false ); col = findCol + txt.length(); setCursorPosition( line, col, true ); //found = true; break; } line++; col = 0; } } } #else #error "Must make a QpeEditor that inherits QTextEdit" #endif static const int nfontsizes = 6; static const int fontsize[nfontsizes] = {8,10,12,14,18,24}; TextEdit::TextEdit( QWidget *parent, const char *name, WFlags f ) : QMainWindow( parent, name, f ), bFromDocView( false ) { doc = 0; edited=false; fromSetDocument=false; setToolBarsMovable( false ); connect( qApp,SIGNAL( aboutToQuit()),SLOT( cleanUp()) ); channel = new QCopChannel( "QPE/Application/textedit", this ); - connect( channel, SIGNAL(received(const QCString&, const QByteArray&)), - this, SLOT(receive(const QCString&, const QByteArray&)) ); + connect( channel, SIGNAL(received(const QCString&,const QByteArray&)), + this, SLOT(receive(const QCString&,const QByteArray&)) ); setIcon( Resource::loadPixmap( "TextEditor" ) ); QToolBar *bar = new QToolBar( this ); bar->setHorizontalStretchable( true ); menu = bar; QMenuBar *mb = new QMenuBar( bar ); QPopupMenu *file = new QPopupMenu( this ); QPopupMenu *edit = new QPopupMenu( this ); QPopupMenu *advancedMenu = new QPopupMenu(this); font = new QPopupMenu( this ); bar = new QToolBar( this ); editBar = bar; QAction *a = new QAction( tr( "New" ), Resource::loadPixmap( "new" ), QString::null, 0, this, 0 ); connect( a, SIGNAL( activated() ), this, SLOT( fileNew() ) ); // a->addTo( bar ); a->addTo( file ); a = new QAction( tr( "Open" ), Resource::loadPixmap( "fileopen" ), QString::null, 0, this, 0 ); connect( a, SIGNAL( activated() ), this, SLOT( fileOpen() ) ); a->addTo( bar ); a->addTo( file ); a = new QAction( tr( "Save" ), Resource::loadPixmap("save") , QString::null, 0, this, 0 ); connect( a, SIGNAL( activated() ), this, SLOT( save() ) ); file->insertSeparator(); a->addTo( bar ); a->addTo( file ); a = new QAction( tr( "Save As" ), Resource::loadPixmap("save") , QString::null, 0, this, 0 ); connect( a, SIGNAL( activated() ), this, SLOT( saveAs() ) ); a->addTo( file ); a = new QAction( tr( "Cut" ), Resource::loadPixmap( "cut" ), QString::null, 0, this, 0 ); connect( a, SIGNAL( activated() ), this, SLOT( editCut() ) ); a->addTo( editBar ); a->addTo( edit ); a = new QAction( tr( "Copy" ), Resource::loadPixmap( "copy" ), QString::null, 0, this, 0 ); connect( a, SIGNAL( activated() ), this, SLOT( editCopy() ) ); a->addTo( editBar ); a->addTo( edit ); a = new QAction( tr( "Paste" ), Resource::loadPixmap( "paste" ), QString::null, 0, this, 0 ); connect( a, SIGNAL( activated() ), this, SLOT( editPaste() ) ); a->addTo( editBar ); a->addTo( edit ); #ifndef QT_NO_CLIPBOARD a = new QAction( tr( "Insert Time and Date" ), Resource::loadPixmap( "paste" ), QString::null, 0, this, 0 ); connect( a, SIGNAL( activated() ), this, SLOT( editPasteTimeDate() ) ); a->addTo( edit ); #endif a = new QAction( tr( "Goto Line..." ), Resource::loadPixmap( "find" ), QString::null, 0, this, 0 ); connect( a, SIGNAL( activated() ), this, SLOT( gotoLine() ) ); edit->insertSeparator(); a->addTo( edit ); a = new QAction( tr( "Find..." ), Resource::loadPixmap( "find" ), QString::null, 0, this, 0 ); connect( a, SIGNAL( activated() ), this, SLOT( editFind() ) ); a->addTo( bar ); a->addTo( edit ); zin = new QAction( tr("Zoom in"), QString::null, 0, this, 0 ); connect( zin, SIGNAL( activated() ), this, SLOT( zoomIn() ) ); zin->addTo( font ); zout = new QAction( tr("Zoom out"), QString::null, 0, this, 0 ); connect( zout, SIGNAL( activated() ), this, SLOT( zoomOut() ) ); zout->addTo( font ); font->insertSeparator(); font->insertItem(tr("Font"), this, SLOT(changeFont()) ); font->insertSeparator(); font->insertItem(tr("Advanced Features"), advancedMenu); QAction *wa = new QAction( tr("Wrap lines"), QString::null, 0, this, 0 ); connect( wa, SIGNAL( toggled(bool) ), this, SLOT( setWordWrap(bool) ) ); wa->setToggleAction(true); wa->addTo( advancedMenu); nStart = new QAction( tr("Start with new file"), QString::null, 0, this, 0 ); connect( nStart, SIGNAL( toggled(bool) ), this, SLOT( changeStartConfig(bool) ) ); nStart->setToggleAction(true); nStart->addTo( advancedMenu ); nStart->setEnabled(false); nAdvanced = new QAction( tr("Prompt on Exit"), QString::null, 0, this, 0 ); connect( nAdvanced, SIGNAL( toggled(bool) ), this, SLOT( doPrompt(bool) ) ); nAdvanced->setToggleAction(true); nAdvanced->addTo( advancedMenu ); desktopAction = new QAction( tr("Always open linked file"), QString::null, 0, this, 0 ); connect( desktopAction, SIGNAL( toggled(bool) ), this, SLOT( doDesktop(bool) ) ); desktopAction->setToggleAction(true); desktopAction->addTo( advancedMenu); filePermAction = new QAction( tr("File Permissions"), QString::null, 0, this, 0 ); connect( filePermAction, SIGNAL( toggled(bool) ), this, SLOT( doFilePerms(bool) ) ); filePermAction->setToggleAction(true); filePermAction->addTo( advancedMenu); searchBarAction = new QAction( tr("Search Bar Open"), QString::null, 0, this, 0 ); connect( searchBarAction, SIGNAL( toggled(bool) ), this, SLOT( setSearchBar(bool) ) ); searchBarAction->setToggleAction(true); searchBarAction->addTo( advancedMenu); nAutoSave = new QAction( tr("Auto Save 5 min."), QString::null, 0, this, 0 ); connect( nAutoSave, SIGNAL( toggled(bool) ), this, SLOT( doTimer(bool) ) ); nAutoSave->setToggleAction(true); nAutoSave->addTo( advancedMenu); //font->insertSeparator(); //font->insertItem(tr("About"), this, SLOT( doAbout()) ); mb->insertItem( tr( "File" ), file ); mb->insertItem( tr( "Edit" ), edit ); mb->insertItem( tr( "View" ), font ); searchBar = new QToolBar(this); addToolBar( searchBar, "Search", QMainWindow::Top, true ); searchBar->setHorizontalStretchable( true ); searchEdit = new QLineEdit( searchBar, "searchEdit" ); searchBar->setStretchableWidget( searchEdit ); - connect( searchEdit, SIGNAL( textChanged( const QString & ) ), + connect( searchEdit, SIGNAL( textChanged(const QString&) ), this, SLOT( search() ) ); a = new QAction( tr( "Find Next" ), Resource::loadPixmap( "next" ), QString::null, 0, this, 0 ); connect( a, SIGNAL( activated() ), this, SLOT( findNext() ) ); a->addTo( searchBar ); a->addTo( edit ); a = new QAction( tr( "Close Find" ), Resource::loadPixmap( "close" ), QString::null, 0, this, 0 ); connect( a, SIGNAL( activated() ), this, SLOT( findClose() ) ); a->addTo( searchBar ); edit->insertSeparator(); a = new QAction( tr( "Delete" ), Resource::loadPixmap( "close" ), QString::null, 0, this, 0 ); connect( a, SIGNAL( activated() ), this, SLOT( editDelete() ) ); a->addTo( edit ); searchBar->hide(); editor = new QpeEditor( this ); setCentralWidget( editor ); editor->setFrameStyle( QFrame::Panel | QFrame::Sunken ); connect( editor, SIGNAL( textChanged() ), this, SLOT( editorChanged() ) ); QPEApplication::setStylusOperation( editor, QPEApplication::RightOnHold); Config cfg("TextEdit"); cfg. setGroup ( "Font" ); QFont defaultFont = editor-> font ( ); QString family = cfg. readEntry ( "Family", defaultFont. family ( )); int size = cfg. readNumEntry ( "Size", defaultFont. pointSize ( )); int weight = cfg. readNumEntry ( "Weight", defaultFont. weight ( )); bool italic = cfg. readBoolEntry ( "Italic", defaultFont. italic ( )); defaultFont = QFont ( family, size, weight, italic ); editor-> setFont ( defaultFont ); // updateCaption(); cfg.setGroup ( "View" ); promptExit = cfg.readBoolEntry ( "PromptExit", false ); openDesktop = cfg.readBoolEntry ( "OpenDesktop", true ); filePerms = cfg.readBoolEntry ( "FilePermissions", false ); useSearchBar = cfg.readBoolEntry ( "SearchBar", false ); startWithNew = cfg.readBoolEntry ( "startNew", true); featureAutoSave = cfg.readBoolEntry( "autosave", false); if(useSearchBar) searchBarAction->setOn(true); if(promptExit) nAdvanced->setOn( true ); if(openDesktop) desktopAction->setOn( true ); if(filePerms) filePermAction->setOn( true ); if(startWithNew) nStart->setOn( true ); if(featureAutoSave) nAutoSave->setOn(true); // { // doTimer(true); // } bool wrap = cfg. readBoolEntry ( "Wrap", true ); wa-> setOn ( wrap ); setWordWrap ( wrap ); ///////////////// if( qApp->argc() > 1) { currentFileName=qApp->argv()[1]; QFileInfo fi(currentFileName); if(fi.baseName().left(1) == "") { openDotFile(currentFileName); } else { openFile(currentFileName); } } else { edited1=false; openDotFile(""); } viewSelection = cfg.readNumEntry( "FileView", 0 ); } TextEdit::~TextEdit() { qWarning("textedit d'tor"); delete editor; } void TextEdit::closeEvent(QCloseEvent *) { if( edited1 && promptExit) { switch( savePrompt() ) { case 1: { saveAs(); qApp->quit(); } break; case 2: { qApp->quit(); } break; case -1: break; }; } else qApp->quit(); } void TextEdit::cleanUp() { Config cfg ( "TextEdit" ); cfg. setGroup ( "Font" ); QFont f = editor->font(); cfg.writeEntry ( "Family", f. family ( )); cfg.writeEntry ( "Size", f. pointSize ( )); cfg.writeEntry ( "Weight", f. weight ( )); cfg.writeEntry ( "Italic", f. italic ( )); cfg.setGroup ( "View" ); cfg.writeEntry ( "Wrap", editor->wordWrap() == QMultiLineEdit::WidgetWidth ); cfg.writeEntry ( "FileView", viewSelection ); cfg.writeEntry ( "PromptExit", promptExit ); cfg.writeEntry ( "OpenDesktop", openDesktop ); cfg.writeEntry ( "FilePermissions", filePerms ); cfg.writeEntry ( "SearchBar", useSearchBar ); cfg.writeEntry ( "startNew", startWithNew ); } void TextEdit::accept() { if( edited1) saveAs(); qApp->quit(); } void TextEdit::zoomIn() { setFontSize(editor->font().pointSize()+1,false); } void TextEdit::zoomOut() { setFontSize(editor->font().pointSize()-1,true); } void TextEdit::setFontSize(int sz, bool round_down_not_up) { int s=10; for (int i=0; i<nfontsizes; i++) { if ( fontsize[i] == sz ) { s = sz; break; } else if ( round_down_not_up ) { if ( fontsize[i] < sz ) s = fontsize[i]; } else { if ( fontsize[i] > sz ) { s = fontsize[i]; break; } } } QFont f = editor->font(); f.setPointSize(s); editor->setFont(f); zin->setEnabled(s != fontsize[nfontsizes-1]); zout->setEnabled(s != fontsize[0]); } void TextEdit::setBold(bool y) { QFont f = editor->font(); f.setBold(y); editor->setFont(f); } void TextEdit::setItalic(bool y) { QFont f = editor->font(); f.setItalic(y); editor->setFont(f); } void TextEdit::setWordWrap(bool y) { bool state = editor->edited(); QString captionStr = caption(); bool b1 = edited1; bool b2 = edited; editor->setWordWrap(y ? QMultiLineEdit::WidgetWidth : QMultiLineEdit::NoWrap ); editor->setEdited( state ); edited1=b1; edited=b2; setCaption(captionStr); } void TextEdit::setSearchBar(bool b) { useSearchBar=b; Config cfg("TextEdit"); cfg.setGroup("View"); cfg.writeEntry ( "SearchBar", b ); searchBarAction->setOn(b); if(b) searchBar->show(); else searchBar->hide(); editor->setFocus(); } void TextEdit::fileNew() { // if( !bFromDocView ) { // saveAs(); // } newFile(DocLnk()); } void TextEdit::fileOpen() { Config cfg("TextEdit"); cfg. setGroup ( "View" ); QMap<QString, QStringList> map; map.insert(tr("All"), QStringList() ); QStringList text; text << "text/*"; map.insert(tr("Text"), text ); text << "*"; map.insert(tr("All"), text ); QString str = OFileDialog::getOpenFileName( 2, QString::null , QString::null, map); if( !str.isEmpty() && QFile(str).exists() && !QFileInfo(str).isDir() ) { openFile( str ); } else updateCaption(); } void TextEdit::doSearchBar() { if(!useSearchBar) searchBar->hide(); else searchBar->show(); } #if 0 void TextEdit::slotFind() { FindDialog frmFind( tr("Text Editor"), this ); - connect( &frmFind, SIGNAL(signalFindClicked(const QString &, bool, bool, int)), - editor, SLOT(slotDoFind( const QString&,bool,bool))); + connect( &frmFind, SIGNAL(signalFindClicked(const QString&,bool,bool,int)), + editor, SLOT(slotDoFind(const QString&,bool,bool))); //case sensitive, backwards, [category] connect( editor, SIGNAL(notFound()), &frmFind, SLOT(slotNotFound()) ); connect( editor, SIGNAL(searchWrapped()), &frmFind, SLOT(slotWrapAround()) ); frmFind.exec(); } #endif void TextEdit::fileRevert() { clear(); fileOpen(); } void TextEdit::editCut() { #ifndef QT_NO_CLIPBOARD editor->cut(); #endif } void TextEdit::editCopy() { #ifndef QT_NO_CLIPBOARD editor->copy(); #endif } void TextEdit::editPaste() { #ifndef QT_NO_CLIPBOARD editor->paste(); #endif } void TextEdit::editFind() { searchBar->show(); searchEdit->setFocus(); } void TextEdit::findNext() { editor->find( searchEdit->text(), false, false ); } void TextEdit::findClose() { searchBar->hide(); } void TextEdit::search() { editor->find( searchEdit->text(), false, false ); } void TextEdit::newFile( const DocLnk &f ) { DocLnk nf = f; nf.setType("text/plain"); clear(); setWState (WState_Reserved1 ); editor->setFocus(); doc = new DocLnk(nf); currentFileName = "Unnamed"; qDebug("newFile "+currentFileName); updateCaption( currentFileName); // editor->setEdited( false); } void TextEdit::openDotFile( const QString &f ) { if(!currentFileName.isEmpty()) { currentFileName=f; qDebug("openFile dotfile " + currentFileName); QString txt; QFile file(f); file.open(IO_ReadWrite); QTextStream t(&file); while ( !t.atEnd()) { txt+=t.readLine()+"\n"; } editor->setText(txt); editor->setEdited( false); edited1=false; edited=false; } updateCaption( currentFileName); } void TextEdit::openFile( const QString &f ) { qDebug("filename is "+ f); QString filer; QFileInfo fi( f); // bFromDocView = true; if(f.find(".desktop",0,true) != -1 && !openDesktop ) { switch ( QMessageBox::warning(this,tr("Text Editor"),tr("Text Editor has detected<BR>you selected a <B>.desktop</B>file.<BR>Open<B>.desktop</B> file or <B>linked</B> file?"),tr(".desktop File"),tr("Linked Document"),0,1,1) ) { case 0: //desktop filer = f; break; case 1: //linked DocLnk sf(f); filer = sf.file(); break; }; } else if(fi.baseName().left(1) == "") { qDebug("opening dotfile"); currentFileName=f; openDotFile(currentFileName); return; } /* * The problem is a file where Config(f).isValid() and it does not * end with .desktop will be treated as desktop file */ else if (f.find(".desktop",0,true) != -1 ) { DocLnk sf(f); filer = sf.file(); if(filer.right(1) == "/") filer = f; } else filer = f; DocLnk nf; nf.setType("text/plain"); nf.setFile(filer); currentFileName=filer; nf.setName(fi.baseName()); openFile(nf); qDebug("openFile string "+currentFileName); showEditTools(); // Show filename in caption QString name = filer; int sep = name.findRev( '/' ); if ( sep > 0 ) name = name.mid( sep+1 ); updateCaption( name ); } void TextEdit::openFile( const DocLnk &f ) { // clear(); // bFromDocView = true; FileManager fm; QString txt; currentFileName=f.file(); qDebug("openFile doclnk " + currentFileName); if ( !fm.loadFile( f, txt ) ) { // ####### could be a new file qDebug( "Cannot open file" ); } // fileNew(); if ( doc ) delete doc; doc = new DocLnk(f); editor->setText(txt); editor->setEdited( false); edited1=false; edited=false; doc->setName(currentFileName); updateCaption(); setTimer(); } void TextEdit::showEditTools() { menu->show(); editBar->show(); if(!useSearchBar) searchBar->hide(); else searchBar->show(); setWState (WState_Reserved1 ); } /*! unprompted save */ bool TextEdit::save() { qDebug("saveAsFile " + currentFileName); if(currentFileName.isEmpty()) { saveAs(); return false; } diff --git a/core/launcher/appicons.cpp b/core/launcher/appicons.cpp index c51ee5a..4d48b24 100644 --- a/core/launcher/appicons.cpp +++ b/core/launcher/appicons.cpp @@ -1,129 +1,131 @@ /********************************************************************** -** Copyright (C) 2000 Trolltech AS. All rights reserved. +** Copyright (C) 2000-2002 Trolltech AS. All rights reserved. ** -** This file is part of Qtopia Environment. +** This file is part of the Qtopia Environment. ** ** This file may be distributed and/or modified under the terms of the ** GNU General Public License version 2 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. ** ** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE ** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. ** ** See http://www.trolltech.com/gpl/ for GPL licensing information. ** ** Contact info@trolltech.com if any conditions of this licensing are ** not clear to you. ** **********************************************************************/ #include "appicons.h" -#include <qpe/qcopenvelope_qws.h> +#ifdef QWS +#include <qtopia/qcopenvelope_qws.h> +#endif #include <qtooltip.h> #include <qpixmap.h> AppIcons::AppIcons( QWidget *parent ) : QHBox(parent) { buttons.setAutoDelete(TRUE); #ifndef QT_NO_COP QCopChannel* channel = new QCopChannel("Qt/Tray", this); - connect(channel, SIGNAL(received(const QCString&, const QByteArray&)), - this, SLOT(receive(const QCString&, const QByteArray&))); + connect(channel, SIGNAL(received(const QCString&,const QByteArray&)), + this, SLOT(receive(const QCString&,const QByteArray&))); #endif } void AppIcons::setIcon(int id, const QPixmap& pm) { button(id)->setPixmap(pm); } class FlatButton : public QLabel { Q_OBJECT public: FlatButton(QWidget* parent) : QLabel(parent) { } void mouseDoubleClickEvent(QMouseEvent* e) { emit clicked(e->pos(),e->button(),TRUE); } void mouseReleaseEvent(QMouseEvent* e) { if ( rect().contains(e->pos()) ) emit clicked(e->pos(),e->button(),FALSE); } signals: void clicked(const QPoint&, int, bool); }; QLabel* AppIcons::button(int id) { QLabel* f = buttons.find(id); if ( !f ) { buttons.insert(id,f=new FlatButton(this)); - connect(f,SIGNAL(clicked(const QPoint&, int, bool)),this,SLOT(clicked(const QPoint&, int, bool))); + connect(f,SIGNAL(clicked(const QPoint&,int,bool)),this,SLOT(clicked(const QPoint&,int,bool))); f->show(); } return f; } int AppIcons::findId(QLabel* b) { QIntDictIterator<QLabel> it(buttons); for ( ; ; ++it ) if ( it.current() == b ) return it.currentKey(); } void AppIcons::clicked(const QPoint& relpos, int button, bool dbl) { #ifndef QT_NO_COP QLabel* s = (QLabel*)sender(); if ( button == RightButton ) { QCopEnvelope("Qt/Tray","popup(int,QPoint)") << findId(s) << s->mapToGlobal(QPoint(0,0)); } else { QCopEnvelope("Qt/Tray", dbl ? "doubleClicked(int,QPoint)" : "clicked(int,QPoint)") << findId(s) << relpos; } #endif } void AppIcons::setToolTip(int id, const QString& tip) { QToolTip::add(button(id),tip); } void AppIcons::remove(int id) { buttons.remove(id); } void AppIcons::receive( const QCString &msg, const QByteArray &data ) { QDataStream stream( data, IO_ReadOnly ); if ( msg == "remove(int)" ) { int id; stream >> id; remove(id); } else if ( msg == "setIcon(int,QPixmap)" ) { int id; QPixmap pm; stream >> id >> pm; setIcon(id,pm); } else if ( msg == "setToolTip(int,QString)" ) { int id; QString s; stream >> id >> s; setToolTip(id,s); } } #include "appicons.moc" diff --git a/core/launcher/applauncher.cpp b/core/launcher/applauncher.cpp index 7d3c032..08a3cb4 100644 --- a/core/launcher/applauncher.cpp +++ b/core/launcher/applauncher.cpp @@ -1,286 +1,286 @@ /********************************************************************** ** Copyright (C) 2000-2002 Trolltech AS. All rights reserved. ** ** This file is part of the Qtopia Environment. ** ** This file may be distributed and/or modified under the terms of the ** GNU General Public License version 2 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. ** ** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE ** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. ** ** See http://www.trolltech.com/gpl/ for GPL licensing information. ** ** Contact info@trolltech.com if any conditions of this licensing are ** not clear to you. ** **********************************************************************/ #ifndef QTOPIA_INTERNAL_PRELOADACCESS #define QTOPIA_INTERNAL_PRELOADACCESS #endif #ifndef QTOPIA_INTERNAL_FILEOPERATIONS #define QTOPIA_INTERNAL_FILEOPERATIONS #endif #ifndef QTOPIA_PROGRAM_MONITOR #define QTOPIA_PROGRAM_MONITOR #endif #include <opie2/oglobal.h> #ifndef Q_OS_WIN32 #include <sys/stat.h> #include <sys/wait.h> #include <sys/file.h> #include <unistd.h> #include <sys/time.h> #include <sys/resource.h> #include <errno.h> #else #include <process.h> #include <windows.h> #include <winbase.h> #endif #include <signal.h> #include <sys/types.h> #include <stdlib.h> #include <qtimer.h> #include <qwindowsystem_qws.h> #include <qmessagebox.h> #include <qfileinfo.h> #include <qtopia/qcopenvelope_qws.h> #include <qtopia/qpeapplication.h> #include "applauncher.h" #include "documentlist.h" const int AppLauncher::RAISE_TIMEOUT_MS = 5000; //--------------------------------------------------------------------------- static AppLauncher* appLauncherPtr; const int appStopEventID = 1290; class AppStoppedEvent : public QCustomEvent { public: AppStoppedEvent(int pid, int status) : QCustomEvent( appStopEventID ), mPid(pid), mStatus(status) { } int pid() { return mPid; } int status() { return mStatus; } private: int mPid, mStatus; }; AppLauncher::AppLauncher(QObject *parent, const char *name) : QObject(parent, name), qlPid(0), qlReady(FALSE), appKillerBox(0) { connect(qwsServer, SIGNAL(newChannel(const QString&)), this, SLOT(newQcopChannel(const QString&))); connect(qwsServer, SIGNAL(removedChannel(const QString&)), this, SLOT(removedQcopChannel(const QString&))); QCopChannel* channel = new QCopChannel( "QPE/System", this ); - connect( channel, SIGNAL(received(const QCString&, const QByteArray&)), - this, SLOT(received(const QCString&, const QByteArray&)) ); + connect( channel, SIGNAL(received(const QCString&,const QByteArray&)), + this, SLOT(received(const QCString&,const QByteArray&)) ); channel = new QCopChannel( "QPE/Server", this ); - connect( channel, SIGNAL(received(const QCString&, const QByteArray&)), - this, SLOT(received(const QCString&, const QByteArray&)) ); + connect( channel, SIGNAL(received(const QCString&,const QByteArray&)), + this, SLOT(received(const QCString&,const QByteArray&)) ); #ifndef Q_OS_WIN32 signal(SIGCHLD, signalHandler); #else runningAppsProc.setAutoDelete( TRUE ); #endif QString tmp = qApp->argv()[0]; int pos = tmp.findRev('/'); if ( pos > -1 ) tmp = tmp.mid(++pos); runningApps[::getpid()] = tmp; appLauncherPtr = this; QTimer::singleShot( 1000, this, SLOT(createQuickLauncher()) ); } AppLauncher::~AppLauncher() { appLauncherPtr = 0; #ifndef Q_OS_WIN32 signal(SIGCHLD, SIG_DFL); #endif if ( qlPid ) { int status; ::kill( qlPid, SIGTERM ); waitpid( qlPid, &status, 0 ); } } /* We use the QCopChannel of the app as an indicator of when it has been launched so that we can disable the busy indicators */ void AppLauncher::newQcopChannel(const QString& channelName) { // qDebug("channel %s added", channelName.data() ); QString prefix("QPE/Application/"); if (channelName.startsWith(prefix)) { { QCopEnvelope e("QPE/System", "newChannel(QString)"); e << channelName; } QString appName = channelName.mid(prefix.length()); if ( appName != "quicklauncher" ) { emit connected( appName ); QCopEnvelope e("QPE/System", "notBusy(QString)"); e << appName; } } else if (channelName.startsWith("QPE/QuickLauncher-")) { qDebug("Registered %s", channelName.latin1()); int pid = channelName.mid(18).toInt(); if (pid == qlPid) qlReady = TRUE; } } void AppLauncher::removedQcopChannel(const QString& channelName) { if (channelName.startsWith("QPE/Application/")) { QCopEnvelope e("QPE/System", "removedChannel(QString)"); e << channelName; } } void AppLauncher::received(const QCString& msg, const QByteArray& data) { QDataStream stream( data, IO_ReadOnly ); if ( msg == "execute(QString)" ) { QString t; stream >> t; if ( !executeBuiltin( t, QString::null ) ) execute(t, QString::null); } else if ( msg == "execute(QString,QString)" ) { QString t,d; stream >> t >> d; if ( !executeBuiltin( t, d ) ) execute( t, d ); } else if ( msg == "processQCop(QString)" ) { // from QPE/Server QString t; stream >> t; if ( !executeBuiltin( t, QString::null ) ) execute( t, QString::null, TRUE); } else if ( msg == "raise(QString)" ) { QString appName; stream >> appName; if ( !executeBuiltin( appName, QString::null ) ) { if ( !waitingHeartbeat.contains( appName ) && appKillerName != appName ) { //qDebug( "Raising: %s", appName.latin1() ); QCString channel = "QPE/Application/"; channel += appName.latin1(); // Need to lock it to avoid race conditions with QPEApplication::processQCopFile QFile f("/tmp/qcop-msg-" + appName); if ( f.open(IO_WriteOnly | IO_Append) ) { #ifndef Q_OS_WIN32 flock(f.handle(), LOCK_EX); #endif QDataStream ds(&f); QByteArray b; QDataStream bstream(b, IO_WriteOnly); ds << channel << QCString("raise()") << b; f.flush(); #ifndef Q_OS_WIN32 flock(f.handle(), LOCK_UN); #endif f.close(); } bool alreadyRunning = isRunning( appName ); if ( execute(appName, QString::null) ) { int id = startTimer(RAISE_TIMEOUT_MS + alreadyRunning?2000:0); waitingHeartbeat.insert( appName, id ); } } } } else if ( msg == "sendRunningApps()" ) { QStringList apps; QMap<int,QString>::Iterator it; for( it = runningApps.begin(); it != runningApps.end(); ++it ) apps.append( *it ); QCopEnvelope e( "QPE/Desktop", "runningApps(QStringList)" ); e << apps; } else if ( msg == "appRaised(QString)" ) { QString appName; stream >> appName; qDebug("Got a heartbeat from %s", appName.latin1()); QMap<QString,int>::Iterator it = waitingHeartbeat.find(appName); if ( it != waitingHeartbeat.end() ) { killTimer( *it ); waitingHeartbeat.remove(it); } // Check to make sure we're not waiting on user input... if ( appKillerBox && appName == appKillerName ) { // If we are, we kill the dialog box, and the code waiting on the result // will clean us up (basically the user said "no"). delete appKillerBox; appKillerBox = 0; appKillerName = QString::null; } } } void AppLauncher::signalHandler(int) { #ifndef Q_OS_WIN32 int status; pid_t pid = waitpid(-1, &status, WNOHANG); /* if (pid == 0 || &status == 0 ) { qDebug("hmm, could not get return value from signal"); } */ QApplication::postEvent(appLauncherPtr, new AppStoppedEvent(pid, status) ); #else qDebug("Unhandled signal see by AppLauncher::signalHandler(int)"); #endif } bool AppLauncher::event(QEvent *e) { if ( e->type() == appStopEventID ) { AppStoppedEvent *ae = (AppStoppedEvent *) e; sigStopped(ae->pid(), ae->status() ); return TRUE; } return QObject::event(e); } void AppLauncher::timerEvent( QTimerEvent *e ) { int id = e->timerId(); QMap<QString,int>::Iterator it; for ( it = waitingHeartbeat.begin(); it != waitingHeartbeat.end(); ++it ) { if ( *it == id ) { if ( appKillerBox ) // we're already dealing with one return; appKillerName = it.key(); killTimer( id ); waitingHeartbeat.remove( it ); // qDebug("Checking in on %s", appKillerName.latin1()); // We store this incase the application responds while we're // waiting for user input so we know not to delete ourselves. appKillerBox = new QMessageBox(tr("Application Problem"), tr("<p>%1 is not responding.</p>").arg(appKillerName) + tr("<p>Would you like to force the application to exit?</p>"), QMessageBox::Warning, QMessageBox::Yes, QMessageBox::No | QMessageBox::Default, QMessageBox::NoButton); if (appKillerBox->exec() == QMessageBox::Yes) { // qDebug("Killing the app!!! Bwuhahahaha!"); diff --git a/core/launcher/firstuse.cpp b/core/launcher/firstuse.cpp index 50ae6c2..4316648 100644 --- a/core/launcher/firstuse.cpp +++ b/core/launcher/firstuse.cpp @@ -1,353 +1,353 @@ /********************************************************************** ** Copyright (C) 2000-2002 Trolltech AS. All rights reserved. ** ** This file is part of the Qtopia Environment. ** ** This file may be distributed and/or modified under the terms of the ** GNU General Public License version 2 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. ** ** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE ** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. ** ** See http://www.trolltech.com/gpl/ for GPL licensing information. ** ** Contact info@trolltech.com if any conditions of this licensing are ** not clear to you. ** **********************************************************************/ // I need access to some things you don't normally get access to. #ifndef _MSC_VER //### revise to allow removal of translators under MSVC #define private public #define protected public #endif #include "firstuse.h" #include "inputmethods.h" #include "applauncher.h" #include "serverapp.h" //#include <qtopia/custom.h> #include "calibrate.h" #include "documentlist.h" #include <qtopia/resource.h> #include <qtopia/qcopenvelope_qws.h> #include <qtopia/config.h> #include <qtopia/fontmanager.h> #include <qfile.h> #include <qpainter.h> #include <qsimplerichtext.h> #include <qpushbutton.h> #include <qlabel.h> #include <qtimer.h> #if defined( Q_WS_QWS ) #include <qwsdisplay_qws.h> #include <qgfx_qws.h> #endif #include <stdlib.h> #include <sys/types.h> #if defined(Q_OS_LINUX) || defined(_OS_LINUX_) #include <unistd.h> #endif struct { bool enabled; const char *app; const char *start; const char *stop; const char *desc; } settingsTable [] = { { FALSE, "language", "raise()", "accept()", // No tr QT_TR_NOOP("Language") }, { FALSE, "doctab", "raise()", "accept()", // No tr QT_TR_NOOP("DocTab") }, #ifndef Q_OS_WIN32 { FALSE, "systemtime", "raise()", "accept()", // No tr QT_TR_NOOP("Time and Date") }, #endif { FALSE, "addressbook", "editPersonalAndClose()", "accept()", // No tr QT_TR_NOOP("Personal Information") }, { FALSE, 0, 0, 0, 0 } }; FirstUse::FirstUse(QWidget* parent, const char * name, WFlags wf) : QDialog( parent, name, TRUE, wf), transApp(0), transLib(0), needCalibrate(FALSE), currApp(-1), waitForExit(-1), waitingForLaunch(FALSE), needRestart(FALSE) { ServerApplication::allowRestart = FALSE; // we force our height beyound the maximum (which we set anyway) QRect desk = qApp->desktop()->geometry(); setGeometry( 0, 0, desk.width(), desk.height() ); connect(qwsServer, SIGNAL(newChannel(const QString&)), this, SLOT(newQcopChannel(const QString&))); // Create a DocumentList so appLauncher has appLnkSet to search docList = new DocumentList( 0, FALSE ); appLauncher = new AppLauncher( this ); - connect( appLauncher, SIGNAL(terminated(int, const QString&)), - this, SLOT(terminated(int, const QString&)) ); + connect( appLauncher, SIGNAL(terminated(int,const QString&)), + this, SLOT(terminated(int,const QString&)) ); // more hackery // I will be run as either the main server or as part of the main server QWSServer::setScreenSaverIntervals(0); loadPixmaps(); //check if there is a language program #ifndef Q_OS_WIN32 QString exeSuffix; #else QString exeSuffix(".exe"); #endif for ( int i = 0; settingsTable[i].app; i++ ) { QString file = QPEApplication::qpeDir() + "bin/"; file += settingsTable[i].app; file += exeSuffix; if ( QFile::exists(file) ) settingsTable[i].enabled = TRUE; } setFocusPolicy(NoFocus); taskBar = new QWidget(0, 0, WStyle_Tool | WStyle_Customize | WStyle_StaysOnTop | WGroupLeader); inputMethods = new InputMethods(taskBar); connect(inputMethods, SIGNAL(inputToggled(bool)), this, SLOT(calcMaxWindowRect())); back = new QPushButton(tr("<< Back"), taskBar); back->setFocusPolicy(NoFocus); connect(back, SIGNAL(clicked()), this, SLOT(previousDialog()) ); next = new QPushButton(tr("Next >>"), taskBar); next->setFocusPolicy(NoFocus); connect(next, SIGNAL(clicked()), this, SLOT(nextDialog()) ); // need to set the geom to lower corner QSize sz = inputMethods->sizeHint(); int buttonWidth = (width() - sz.width()) / 2; int x = 0; controlHeight = back->sizeHint().height(); inputMethods->setGeometry(0,0, sz.width(), controlHeight ); x += sz.width(); back->setGeometry(x, 0, buttonWidth, controlHeight); x += buttonWidth; next->setGeometry(x, 0, buttonWidth, controlHeight); taskBar->setGeometry( 0, height() - controlHeight, desk.width(), controlHeight); taskBar->hide(); #if defined(Q_WS_QWS) && !defined(QT_NO_COP) qDebug("Setting up QCop to QPE/System"); QCopChannel* sysChannel = new QCopChannel( "QPE/System", this ); - connect(sysChannel, SIGNAL(received(const QCString &, const QByteArray &)), - this, SLOT(message(const QCString &, const QByteArray &)) ); + connect(sysChannel, SIGNAL(received(const QCString&,const QByteArray&)), + this, SLOT(message(const QCString&,const QByteArray&)) ); #endif calcMaxWindowRect(); m_calHandler = ( QWSServer::mouseHandler() && QWSServer::mouseHandler()->inherits("QCalibratedMouseHandler") ) ? true : false; if ( m_calHandler) { if ( !QFile::exists("/etc/pointercal") ) { needCalibrate = TRUE; grabMouse(); } } Config config("locale"); config.setGroup( "Language"); lang = config.readEntry( "Language", "en"); defaultFont = font(); //###language/font hack; should look it up somewhere #ifdef Q_WS_QWS if ( lang == "ja" || lang == "zh_CN" || lang == "zh_TW" || lang == "ko" ) { QFont fn = FontManager::unicodeFont( FontManager::Proportional ); qApp->setFont( fn, TRUE ); } #endif } FirstUse::~FirstUse() { delete appLauncher; delete docList; delete taskBar; ServerApplication::allowRestart = TRUE; } void FirstUse::calcMaxWindowRect() { #ifdef Q_WS_QWS QRect wr; int displayWidth = qApp->desktop()->width(); QRect ir = inputMethods->inputRect(); if ( ir.isValid() ) { wr.setCoords( 0, 0, displayWidth-1, ir.top()-1 ); } else { wr.setCoords( 0, 0, displayWidth-1, qApp->desktop()->height() - controlHeight-1); } #if QT_VERSION < 0x030000 QWSServer::setMaxWindowRect( qt_screen->mapToDevice(wr, QSize(qt_screen->width(),qt_screen->height())) ); #else QWSServer::setMaxWindowRect( wr ); #endif #endif } /* cancel current dialog, and bring up next */ void FirstUse::nextDialog() { int prevApp = currApp; do { currApp++; qDebug( "currApp = %d", currApp ); if ( settingsTable[currApp].app == 0 ) { if ( prevApp >= 0 && appLauncher->isRunning(settingsTable[prevApp].app) ) { // The last application is still running. // Tell it to stop, and when its done we'll come back // to nextDialog and exit. qDebug( "Waiting for %s to exit", settingsTable[prevApp].app ); QCopEnvelope e(QCString("QPE/Application/") + settingsTable[prevApp].app, settingsTable[prevApp].stop ); currApp = prevApp; } else { qDebug( "Done!" ); Config config( "qpe" ); config.setGroup( "Startup" ); config.writeEntry( "FirstUse", FALSE ); QPixmap pix = Resource::loadPixmap("bigwait"); QLabel *lblWait = new QLabel(0, "wait hack!", // No tr QWidget::WStyle_Customize | QWidget::WDestructiveClose | QWidget::WStyle_NoBorder | QWidget::WStyle_Tool | QWidget::WStyle_StaysOnTop); lblWait->setPixmap( pix ); lblWait->setAlignment( QWidget::AlignCenter ); lblWait->setGeometry( qApp->desktop()->geometry() ); lblWait->show(); qApp->processEvents(); QTimer::singleShot( 1000, lblWait, SLOT(close()) ); repaint(); close(); ServerApplication::allowRestart = TRUE; } return; } } while ( !settingsTable[currApp].enabled ); if ( prevApp >= 0 && appLauncher->isRunning(settingsTable[prevApp].app) ) { qDebug( "Shutdown: %s", settingsTable[prevApp].app ); QCopEnvelope e(QCString("QPE/Application/") + settingsTable[prevApp].app, settingsTable[prevApp].stop ); waitForExit = prevApp; } else { qDebug( "Startup: %s", settingsTable[currApp].app ); QCopEnvelope e(QCString("QPE/Application/") + settingsTable[currApp].app, settingsTable[currApp].start ); waitingForLaunch = TRUE; } updateButtons(); } /* accept current dialog and bring up previous */ void FirstUse::previousDialog() { int prevApp = currApp; do { currApp--; if ( currApp < 0 ) { currApp = prevApp; return; } } while ( !settingsTable[currApp].enabled ); if ( prevApp >= 0 ) { qDebug( "Shutdown: %s", settingsTable[prevApp].app ); QCopEnvelope e(QCString("QPE/Application/") + settingsTable[prevApp].app, settingsTable[prevApp].stop ); /* if (settingsTable[prevApp].app == QString("systemtime")) QCopEnvelope e("QPE/Application/citytime", "close()"); */ waitForExit = prevApp; } else { qDebug( "Startup: %s", settingsTable[currApp].app ); QCopEnvelope e(QCString("QPE/Application/") + settingsTable[currApp].app, settingsTable[currApp].start ); waitingForLaunch = TRUE; } updateButtons(); } void FirstUse::message(const QCString &msg, const QByteArray &data) { QDataStream stream( data, IO_ReadOnly ); if ( msg == "timeChange(QString)" ) { QString t; stream >> t; if ( t.isNull() ) unsetenv("TZ"); else setenv( "TZ", t.latin1(), 1 ); } } void FirstUse::terminated( int, const QString &app ) { qDebug( "--- terminated: %s", app.latin1() ); if ( waitForExit != -1 && settingsTable[waitForExit].app == app ) { qDebug( "Startup: %s", settingsTable[currApp].app ); if ( settingsTable[waitForExit].app == "language" ) { // No tr Config config("locale"); config.setGroup( "Language"); QString l = config.readEntry( "Language", "en"); if ( l != lang ) { reloadLanguages(); needRestart = TRUE; lang = l; } } QCopEnvelope e(QCString("QPE/Application/") + settingsTable[currApp].app, settingsTable[currApp].start ); waitingForLaunch = TRUE; updateButtons(); repaint(); waitForExit = -1; } else if ( settingsTable[currApp].app == app ) { nextDialog(); } else { back->setEnabled(TRUE); next->setEnabled(TRUE); } } void FirstUse::newQcopChannel(const QString& channelName) { qDebug("channel %s added", channelName.data() ); QString prefix("QPE/Application/"); if (channelName.startsWith(prefix)) { QString appName = channelName.mid(prefix.length()); diff --git a/core/launcher/inputmethods.cpp b/core/launcher/inputmethods.cpp index 683f1e2..19e799a 100644 --- a/core/launcher/inputmethods.cpp +++ b/core/launcher/inputmethods.cpp @@ -1,341 +1,341 @@ /********************************************************************** ** Copyright (C) 2000-2002 Trolltech AS. All rights reserved. ** ** This file is part of the Qtopia Environment. ** ** This file may be distributed and/or modified under the terms of the ** GNU General Public License version 2 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. ** ** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE ** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. ** ** See http://www.trolltech.com/gpl/ for GPL licensing information. ** ** Contact info@trolltech.com if any conditions of this licensing are ** not clear to you. ** **********************************************************************/ #define QTOPIA_INTERNAL_LANGLIST #include "inputmethods.h" #include <qtopia/config.h> #include <qtopia/qpeapplication.h> #include <qpopupmenu.h> #include <qtoolbutton.h> #include <qwidgetstack.h> #include <qlayout.h> #include <qdir.h> #include <stdlib.h> #include <qtl.h> #ifdef Q_WS_QWS #include <qwindowsystem_qws.h> #include <qwsevent_qws.h> #include <qcopchannel_qws.h> #endif /* ### SingleFloppy if someone is interested? */ #if 0 #ifdef QT_NO_COMPONENT #include "../plugins/inputmethods/handwriting/handwritingimpl.h" #include "../plugins/inputmethods/keyboard/keyboardimpl.h" #include "../3rdparty/plugins/inputmethods/pickboard/pickboardimpl.h" #endif #endif /* XPM */ static const char * tri_xpm[]={ "9 9 2 1", "a c #000000", ". c None", ".........", ".........", ".........", "....a....", "...aaa...", "..aaaaa..", ".aaaaaaa.", ".........", "........."}; int InputMethod::operator <(const InputMethod& o) const { return name() < o.name(); } int InputMethod::operator >(const InputMethod& o) const { return name() > o.name(); } int InputMethod::operator <=(const InputMethod& o) const { return name() <= o.name(); } /* Slightly hacky: We use WStyle_Tool as a flag to say "this widget belongs to the IM system, so clicking it should not cause a reset". */ class IMToolButton : public QToolButton { public: IMToolButton::IMToolButton( QWidget *parent ) : QToolButton( parent ) { setWFlags( WStyle_Tool ); } }; InputMethods::InputMethods( QWidget *parent ) : QWidget( parent, "InputMethods", WStyle_Tool | WStyle_Customize ), mkeyboard(0), imethod(0) { Config cfg( "Launcher" ); cfg.setGroup( "InputMethods" ); inputWidgetStyle = QWidget::WStyle_Customize | QWidget::WStyle_StaysOnTop | QWidget::WGroupLeader | QWidget::WStyle_Tool; inputWidgetStyle |= cfg.readBoolEntry( "Float", false ) ? QWidget::WStyle_DialogBorder : 0; inputWidgetWidth = cfg.readNumEntry( "Width", 100 ); setBackgroundMode( PaletteBackground ); QHBoxLayout *hbox = new QHBoxLayout( this ); kbdButton = new IMToolButton( this); kbdButton->setFocusPolicy(NoFocus); kbdButton->setToggleButton( TRUE ); if (parent->sizeHint().height() > 0) kbdButton->setFixedHeight( parent->sizeHint().height() ); kbdButton->setFixedWidth( 32 ); kbdButton->setAutoRaise( TRUE ); kbdButton->setUsesBigPixmap( TRUE ); hbox->addWidget( kbdButton ); connect( kbdButton, SIGNAL(toggled(bool)), this, SLOT(showKbd(bool)) ); kbdChoice = new IMToolButton( this ); kbdChoice->setFocusPolicy(NoFocus); kbdChoice->setPixmap( QPixmap( (const char **)tri_xpm ) ); if (parent->sizeHint().height() > 0) kbdChoice->setFixedHeight( parent->sizeHint().height() ); kbdChoice->setFixedWidth( 13 ); kbdChoice->setAutoRaise( TRUE ); hbox->addWidget( kbdChoice ); connect( kbdChoice, SIGNAL(clicked()), this, SLOT(chooseKbd()) ); connect( (QPEApplication*)qApp, SIGNAL(clientMoused()), this, SLOT(resetStates()) ); imButton = new QWidgetStack( this ); // later a widget stack imButton->setFocusPolicy(NoFocus); if (parent->sizeHint().height() > 0) imButton->setFixedHeight( parent->sizeHint().height() ); hbox->addWidget(imButton); imChoice = new QToolButton( this ); imChoice->setFocusPolicy(NoFocus); imChoice->setPixmap( QPixmap( (const char **)tri_xpm ) ); if (parent->sizeHint().height() > 0) imChoice->setFixedHeight( parent->sizeHint().height() ); imChoice->setFixedWidth( 13 ); imChoice->setAutoRaise( TRUE ); hbox->addWidget( imChoice ); connect( imChoice, SIGNAL(clicked()), this, SLOT(chooseIm()) ); loadInputMethods(); QCopChannel *channel = new QCopChannel( "QPE/IME", this ); - connect( channel, SIGNAL(received(const QCString&, const QByteArray&)), - this, SLOT(qcopReceive(const QCString&, const QByteArray&)) ); + connect( channel, SIGNAL(received(const QCString&,const QByteArray&)), + this, SLOT(qcopReceive(const QCString&,const QByteArray&)) ); } InputMethods::~InputMethods() { Config cfg("qpe"); cfg.setGroup("InputMethod"); if (imethod) cfg.writeEntry("im", imethod->name() ); if (mkeyboard) cfg.writeEntry("current", mkeyboard->name() ); unloadInputMethods(); } void InputMethods::hideInputMethod() { kbdButton->setOn( FALSE ); } void InputMethods::showInputMethod() { kbdButton->setOn( TRUE ); } void InputMethods::showInputMethod(const QString& name) { int i = 0; QValueList<InputMethod>::Iterator it; InputMethod *im = 0; for ( it = inputMethodList.begin(); it != inputMethodList.end(); ++it, i++ ) { QString lname = (*it).libName.mid((*it).libName.findRev('/') + 1); if ( (*it).name() == name || lname == name ) { im = &(*it); break; } } if ( im ) chooseKeyboard(im); } void InputMethods::resetStates() { if ( mkeyboard && !mkeyboard->newIM ) mkeyboard->interface->resetState(); } QRect InputMethods::inputRect() const { if ( !mkeyboard || !mkeyboard->widget || !mkeyboard->widget->isVisible() ) return QRect(); else return mkeyboard->widget->geometry(); } void InputMethods::unloadInputMethods() { unloadMethod( inputMethodList ); unloadMethod( inputModifierList ); inputMethodList.clear(); inputModifierList.clear(); } void InputMethods::unloadMethod( QValueList<InputMethod>& list ) { QValueList<InputMethod>::Iterator it; for (it = list.begin(); it != list.end(); ++it ) (*it).releaseInterface(); } QStringList InputMethods::plugins()const { QString path = QPEApplication::qpeDir() + "/plugins/inputmethods"; #ifdef Q_OS_MACX QDir dir( path, "lib*.dylib" ); #else QDir dir( path, "lib*.so" ); #endif /* Q_OS_MACX */ return dir.entryList(); } void InputMethods::installTranslator( const QString& type ) { QStringList langs = Global::languageList(); QStringList::ConstIterator lit; for ( lit= langs.begin(); lit!=langs.end(); ++lit) { QString lang = *lit; QTranslator * trans = new QTranslator(qApp); QString tfn = QPEApplication::qpeDir()+"/i18n/"+lang+"/"+type+".qm"; if ( trans->load( tfn )) qApp->installTranslator( trans ); else delete trans; } } void InputMethods::setPreferedHandlers() { Config cfg("qpe"); cfg.setGroup("InputMethod"); QString current = cfg.readEntry("current"); QString im = cfg.readEntry("im"); QValueList<InputMethod>::Iterator it; if (!inputModifierList.isEmpty() && !im.isEmpty() ) { for (it = inputModifierList.begin(); it != inputModifierList.end(); ++it ) if ( (*it).name() == im ) { imethod = &(*it); break; } } if (!inputMethodList.isEmpty() && !current.isEmpty() ) { for (it = inputMethodList.begin(); it != inputMethodList.end(); ++it ) if ( (*it).name() == current ) { qWarning("preferred keyboard is %s", current.latin1() ); mkeyboard = &(*it); kbdButton->setPixmap( *mkeyboard->icon() ); break; } } } void InputMethods::loadInputMethods() { #ifndef QT_NO_COMPONENT hideInputMethod(); mkeyboard = 0; unloadInputMethods(); QString path = QPEApplication::qpeDir() + "/plugins/inputmethods"; QStringList list = plugins(); QStringList::Iterator it; for ( it = list.begin(); it != list.end(); ++it ) { InputMethodInterface *iface = 0; ExtInputMethodInterface *eface = 0; QLibrary *lib = new QLibrary( path + "/" + *it ); if ( lib->queryInterface( IID_InputMethod, (QUnknownInterface**)&iface ) == QS_OK ) { InputMethod input; input.newIM = FALSE; input.library = lib; input.libName = *it; input.interface = iface; input.widget = input.interface->inputMethod( 0, inputWidgetStyle ); input.interface->onKeyPress( this, SLOT(sendKey(ushort,ushort,ushort,bool,bool)) ); inputMethodList.append( input ); } else if ( lib->queryInterface( IID_ExtInputMethod, (QUnknownInterface**)&eface ) == QS_OK ) { InputMethod input; input.newIM = TRUE; input.library = lib; input.libName = *it; input.extInterface = eface; input.widget = input.extInterface->keyboardWidget( 0, inputWidgetStyle ); // may be either a simple, or advanced. if (input.widget) { //qDebug("its a keyboard"); inputMethodList.append( input ); } else { //qDebug("its a real im"); input.widget = input.extInterface->statusWidget( 0, 0 ); if (input.widget) { //qDebug("blah"); inputModifierList.append( input ); imButton->addWidget(input.widget, inputModifierList.count()); } } }else{ delete lib; lib = 0l; } installTranslator( (*it).left( (*it).find(".") ) ); } qHeapSort( inputMethodList ); #endif /* killed BUILT in cause they would not compile */ QWSServer::setCurrentInputMethod( 0 ); /* set the prefered IM + handler */ setPreferedHandlers(); if ( !inputModifierList.isEmpty() ) { if (!imethod) imethod = &inputModifierList[0]; imButton->raiseWidget(imethod->widget); QWSServer::setCurrentInputMethod( imethod->extInterface->inputMethod() ); } else { imethod = 0; } // we need to update keyboards afterwards, as some of them may not be compatible with diff --git a/core/launcher/launcher.cpp b/core/launcher/launcher.cpp index 54efb0b..5d0c778 100644 --- a/core/launcher/launcher.cpp +++ b/core/launcher/launcher.cpp @@ -1,673 +1,673 @@ /********************************************************************** ** Copyright (C) 2000-2002 Trolltech AS. All rights reserved. ** ** This file is part of the Qtopia Environment. ** ** This file may be distributed and/or modified under the terms of the ** GNU General Public License version 2 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. ** ** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE ** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. ** ** See http://www.trolltech.com/gpl/ for GPL licensing information. ** ** Contact info@trolltech.com if any conditions of this licensing are ** not clear to you. ** **********************************************************************/ #include <qtopia/global.h> #ifdef Q_WS_QWS #include <qtopia/qcopenvelope_qws.h> #endif #include <qtopia/resource.h> #include <qtopia/applnk.h> #include <qtopia/config.h> #include <qtopia/qpeapplication.h> #include <qtopia/mimetype.h> #include <qtopia/private/categories.h> //#include <qtopia/custom.h> #include <qdir.h> #ifdef Q_WS_QWS #include <qwindowsystem_qws.h> #endif #include <qtimer.h> #include <qcombobox.h> #include <qvbox.h> #include <qlayout.h> #include <qstyle.h> #include <qpushbutton.h> #include <qtabbar.h> #include <qwidgetstack.h> #include <qregexp.h> #include <qmessagebox.h> #include <qframe.h> #include <qpainter.h> #include <qlabel.h> #include <qtextstream.h> #include <qpopupmenu.h> #include "startmenu.h" #include "taskbar.h" #include "serverinterface.h" #include "launcherview.h" #include "launcher.h" #include "server.h" #define QTOPIA_INTERNAL_FSLP #include <qtopia/lnkproperties.h> #include <stdlib.h> #include <assert.h> #if defined(_OS_LINUX_) || defined(Q_OS_LINUX) #include <unistd.h> #include <stdio.h> #include <sys/vfs.h> #include <mntent.h> #endif #ifdef Q_WS_QWS #include <qkeyboard_qws.h> #include <qpe/lnkproperties.h> #endif static bool isVisibleWindow( int ); //=========================================================================== LauncherTabWidget::LauncherTabWidget( Launcher* parent ) : QVBox( parent ), docview( 0 ) { docLoadingWidgetEnabled = false; docLoadingWidget = 0; docLoadingWidgetProgress = 0; launcher = parent; categoryBar = new LauncherTabBar( this ); QPalette pal = categoryBar->palette(); pal.setColor( QColorGroup::Light, pal.color(QPalette::Active,QColorGroup::Shadow) ); pal.setColor( QColorGroup::Background, pal.active().background().light(110) ); categoryBar->setPalette( pal ); stack = new QWidgetStack(this); connect( categoryBar, SIGNAL(selected(int)), this, SLOT(raiseTabWidget()) ); categoryBar->show(); stack->show(); #if defined(Q_WS_QWS) && !defined(QT_NO_COP) QCopChannel *channel = new QCopChannel( "QPE/Launcher", this ); - connect( channel, SIGNAL(received(const QCString&, const QByteArray&)), - this, SLOT(launcherMessage(const QCString&, const QByteArray&)) ); - connect( qApp, SIGNAL(appMessage(const QCString&, const QByteArray&)), - this, SLOT(appMessage(const QCString&, const QByteArray&))); + connect( channel, SIGNAL(received(const QCString&,const QByteArray&)), + this, SLOT(launcherMessage(const QCString&,const QByteArray&)) ); + connect( qApp, SIGNAL(appMessage(const QCString&,const QByteArray&)), + this, SLOT(appMessage(const QCString&,const QByteArray&))); #endif createDocLoadingWidget(); } void LauncherTabWidget::createDocLoadingWidget() { // Construct the 'doc loading widget' shown when finding documents // ### LauncherView class needs changing to be more generic so // this widget can change its background similar to the iconviews // so the background for this matches docLoadingWidget = new LauncherView( stack ); docLoadingWidget->hideIcons(); QVBox *docLoadingVBox = new QVBox( docLoadingWidget ); docLoadingVBox->setSpacing( 20 ); docLoadingVBox->setMargin( 10 ); QWidget *space1 = new QWidget( docLoadingVBox ); docLoadingVBox->setStretchFactor( space1, 1 ); QLabel *waitPixmap = new QLabel( docLoadingVBox ); waitPixmap->setSizePolicy( QSizePolicy( (QSizePolicy::SizeType)5, (QSizePolicy::SizeType)5, waitPixmap->sizePolicy().hasHeightForWidth() ) ); waitPixmap->setPixmap( Resource::loadPixmap( "bigwait" ) ); waitPixmap->setAlignment( int( QLabel::AlignCenter ) ); Config cfg( "Launcher" ); cfg.setGroup( "DocTab" ); bool docTabEnabled = cfg.readBoolEntry( "Enable", true ); QLabel *textLabel = new QLabel( docLoadingVBox ); textLabel->setAlignment( int( QLabel::AlignCenter ) ); docLoadingWidgetProgress = new QProgressBar( docLoadingVBox ); docLoadingWidgetProgress->setProgress( 0 ); docLoadingWidgetProgress->setCenterIndicator( TRUE ); docLoadingWidgetProgress->setBackgroundMode( NoBackground ); // No flicker setProgressStyle(); if ( docTabEnabled ) { textLabel->setText( tr( "<b>Finding Documents...</b>" ) ); } else { textLabel->setText( tr( "<b>The Documents Tab<p>has been disabled.<p>" "Use Settings->Launcher->DocTab<p>to reenable it.</b></center>" ) ); docLoadingWidgetProgress->hide(); docLoadingWidgetEnabled = true; } QWidget *space2 = new QWidget( docLoadingVBox ); docLoadingVBox->setStretchFactor( space2, 1 ); cfg.setGroup( "Tab Documents" ); // No tr setTabViewAppearance( docLoadingWidget, cfg ); stack->addWidget( docLoadingWidget, 0 ); } void LauncherTabWidget::initLayout() { layout()->activate(); docView()->setFocus(); categoryBar->showTab("Documents"); } void LauncherTabWidget::appMessage(const QCString& message, const QByteArray&) { if ( message == "nextView()" ) categoryBar->nextTab(); } void LauncherTabWidget::raiseTabWidget() { if ( categoryBar->currentView() == docView() && docLoadingWidgetEnabled ) { stack->raiseWidget( docLoadingWidget ); docLoadingWidget->updateGeometry(); } else { stack->raiseWidget( categoryBar->currentView() ); } } void LauncherTabWidget::tabProperties() { LauncherView *view = categoryBar->currentView(); QPopupMenu *m = new QPopupMenu( this ); m->insertItem( tr("Icon View"), LauncherView::Icon ); m->insertItem( tr("List View"), LauncherView::List ); m->setItemChecked( (int)view->viewMode(), TRUE ); int rv = m->exec( QCursor::pos() ); if ( rv >= 0 && rv != view->viewMode() ) { view->setViewMode( (LauncherView::ViewMode)rv ); } delete m; } void LauncherTabWidget::deleteView( const QString& id ) { LauncherTab *t = categoryBar->launcherTab(id); if ( t ) { stack->removeWidget( t->view ); delete t->view; categoryBar->removeTab( t ); } } LauncherView* LauncherTabWidget::newView( const QString& id, const QPixmap& pm, const QString& label ) { LauncherView* view = new LauncherView( stack ); connect( view, SIGNAL(clicked(const AppLnk*)), this, SIGNAL(clicked(const AppLnk*))); connect( view, SIGNAL(rightPressed(AppLnk*)), this, SIGNAL(rightPressed(AppLnk*))); int n = categoryBar->count(); stack->addWidget( view, n ); LauncherTab *tab = new LauncherTab( id, view, pm, label ); categoryBar->insertTab( tab, n-1 ); if ( id == "Documents" ) docview = view; qDebug("inserting %s at %d", id.latin1(), n-1 ); Config cfg("Launcher"); setTabAppearance( tab, cfg ); cfg.setGroup( "GUI" ); view->setBusyIndicatorType( cfg.readEntry( "BusyType", QString::null ) ); return view; } LauncherView *LauncherTabWidget::view( const QString &id ) { LauncherTab *t = categoryBar->launcherTab(id); if ( !t ) return 0; return t->view; } LauncherView *LauncherTabWidget::docView() { return docview; } void LauncherTabWidget::setLoadingWidgetEnabled( bool v ) { if ( v != docLoadingWidgetEnabled && docLoadingWidget ) { docLoadingWidgetEnabled = v; raiseTabWidget(); } } void LauncherTabWidget::setLoadingProgress( int percent ) { docLoadingWidgetProgress->setProgress( (percent / 4) * 4 ); } // ### this function could more to LauncherView void LauncherTabWidget::setTabViewAppearance( LauncherView *v, Config &cfg ) { // View QString view = cfg.readEntry( "View", "Icon" ); if ( view == "List" ) // No tr v->setViewMode( LauncherView::List ); QString bgType = cfg.readEntry( "BackgroundType", "Image" ); if ( bgType == "Image" ) { // No tr QString pm = cfg.readEntry( "BackgroundImage", "launcher/opie-background" ); v->setBackgroundType( LauncherView::Image, pm ); } else if ( bgType == "SolidColor" ) { QString c = cfg.readEntry( "BackgroundColor" ); v->setBackgroundType( LauncherView::SolidColor, c ); } else { v->setBackgroundType( LauncherView::Ruled, QString::null ); } QString textCol = cfg.readEntry( "TextColor" ); if ( textCol.isEmpty() ) v->setTextColor( QColor() ); else v->setTextColor( QColor(textCol) ); // bool customFont = cfg.readBoolEntry( "CustomFont", FALSE ); QStringList font = cfg.readListEntry( "Font", ',' ); if ( font.count() == 4 ) v->setViewFont( QFont(font[0], font[1].toInt(), font[2].toInt(), font[3].toInt()!=0) ); // ### FIXME TabColor TabTextColor } // ### Could move to LauncherTab void LauncherTabWidget::setTabAppearance( LauncherTab *tab, Config &cfg ) { cfg.setGroup( QString( "Tab %1" ).arg(tab->type) ); // No tr setTabViewAppearance( tab->view, cfg ); // Tabs QString tabCol = cfg.readEntry( "TabColor" ); if ( tabCol.isEmpty() ) tab->bgColor = QColor(); else tab->bgColor = QColor(tabCol); QString tabTextCol = cfg.readEntry( "TabTextColor" ); if ( tabTextCol.isEmpty() ) tab->fgColor = QColor(); else tab->fgColor = QColor(tabTextCol); } void LauncherTabWidget::paletteChange( const QPalette &p ) { QVBox::paletteChange( p ); QPalette pal = palette(); pal.setColor( QColorGroup::Light, pal.color(QPalette::Active,QColorGroup::Shadow) ); pal.setColor( QColorGroup::Background, pal.active().background().light(110) ); categoryBar->setPalette( pal ); categoryBar->update(); } void LauncherTabWidget::styleChange( QStyle & ) { QTimer::singleShot( 0, this, SLOT(setProgressStyle()) ); } void LauncherTabWidget::setProgressStyle() { if (docLoadingWidgetProgress) { docLoadingWidgetProgress->setFrameShape( QProgressBar::Box ); docLoadingWidgetProgress->setFrameShadow( QProgressBar::Plain ); docLoadingWidgetProgress->setMargin( 1 ); docLoadingWidgetProgress->setLineWidth( 1 ); } } void LauncherTabWidget::setBusy(bool on) { if ( on ) currentView()->setBusy(TRUE); else { for ( int i = 0; i < categoryBar->count(); i++ ) { LauncherView *view = ((LauncherTab *)categoryBar->tab(i))->view; view->setBusy( FALSE ); } } } void LauncherTabWidget::setBusyIndicatorType( const QString& str ) { for (int i = 0; i < categoryBar->count(); i++ ) { LauncherView* view = static_cast<LauncherTab*>( categoryBar->tab(i) )->view; view->setBusyIndicatorType( str ); } } LauncherView *LauncherTabWidget::currentView(void) { return (LauncherView*)stack->visibleWidget(); } void LauncherTabWidget::launcherMessage( const QCString &msg, const QByteArray &data) { QDataStream stream( data, IO_ReadOnly ); if ( msg == "setTabView(QString,int)" ) { QString id; stream >> id; int mode; stream >> mode; if ( view(id) ) view(id)->setViewMode( (LauncherView::ViewMode)mode ); } else if ( msg == "setTabBackground(QString,int,QString)" ) { QString id; stream >> id; int mode; stream >> mode; QString pixmapOrColor; stream >> pixmapOrColor; if ( view(id) ) view(id)->setBackgroundType( (LauncherView::BackgroundType)mode, pixmapOrColor ); if ( id == "Documents" ) docLoadingWidget->setBackgroundType( (LauncherView::BackgroundType)mode, pixmapOrColor ); } else if ( msg == "setTextColor(QString,QString)" ) { QString id; stream >> id; QString color; stream >> color; if ( view(id) ) view(id)->setTextColor( QColor(color) ); if ( id == "Documents" ) docLoadingWidget->setTextColor( QColor(color) ); } else if ( msg == "setFont(QString,QString,int,int,int)" ) { QString id; stream >> id; QString fam; stream >> fam; int size; stream >> size; int weight; stream >> weight; int italic; stream >> italic; if ( view(id) ) { if ( !fam.isEmpty() ) { view(id)->setViewFont( QFont(fam, size, weight, italic!=0) ); qDebug( "setFont: %s, %d, %d, %d", fam.latin1(), size, weight, italic ); } else { view(id)->clearViewFont(); } } }else if ( msg == "setBusyIndicatorType(QString)" ) { QString type; stream >> type; setBusyIndicatorType( type ); }else if ( msg == "home()" ) { if ( isVisibleWindow( static_cast<QWidget*>(parent())->winId() ) ) { if (categoryBar) categoryBar->nextTab(); }else static_cast<QWidget*>(parent())->raise(); } } //--------------------------------------------------------------------------- Launcher::Launcher() : QMainWindow( 0, "PDA User Interface", QWidget::WStyle_Customize | QWidget::WGroupLeader ) { tabs = 0; tb = 0; Config cfg( "Launcher" ); cfg.setGroup( "DocTab" ); docTabEnabled = cfg.readBoolEntry( "Enable", true ); } void Launcher::createGUI() { setCaption( tr("Launcher") ); // we have a pretty good idea how big we'll be setGeometry( 0, 0, qApp->desktop()->width(), qApp->desktop()->height() ); tb = new TaskBar; tabs = new LauncherTabWidget( this ); setCentralWidget( tabs ); ServerInterface::dockWidget( tb, ServerInterface::Bottom ); tb->show(); qApp->installEventFilter( this ); connect( qApp, SIGNAL(symbol()), this, SLOT(toggleSymbolInput()) ); connect( qApp, SIGNAL(numLockStateToggle()), this, SLOT(toggleNumLockState()) ); connect( qApp, SIGNAL(capsLockStateToggle()), this, SLOT(toggleCapsLockState()) ); connect( tb, SIGNAL(tabSelected(const QString&)), this, SLOT(showTab(const QString&)) ); connect( tabs, SIGNAL(selected(const QString&)), this, SLOT(viewSelected(const QString&)) ); connect( tabs, SIGNAL(clicked(const AppLnk*)), this, SLOT(select(const AppLnk*))); connect( tabs, SIGNAL(rightPressed(AppLnk*)), this, SLOT(properties(AppLnk*))); #if defined(Q_WS_QWS) && !defined(QT_NO_COP) QCopChannel* sysChannel = new QCopChannel( "QPE/System", this ); - connect( sysChannel, SIGNAL(received(const QCString &, const QByteArray &)), - this, SLOT(systemMessage( const QCString &, const QByteArray &)) ); + connect( sysChannel, SIGNAL(received(const QCString&,const QByteArray&)), + this, SLOT(systemMessage(const QCString&,const QByteArray&)) ); #endif // all documents QImage img( Resource::loadImage( "DocsIcon" ) ); QPixmap pm; pm = img.smoothScale( AppLnk::smallIconSize(), AppLnk::smallIconSize() ); // It could add this itself if it handles docs tabs->newView("Documents", pm, tr("Documents") )->setToolsEnabled( TRUE ); QTimer::singleShot( 0, tabs, SLOT( initLayout() ) ); qApp->setMainWidget( this ); QTimer::singleShot( 500, this, SLOT( makeVisible() ) ); } Launcher::~Launcher() { if ( tb ) destroyGUI(); } bool Launcher::requiresDocuments() const { Config cfg( "Launcher" ); cfg.setGroup( "DocTab" ); return cfg.readBoolEntry( "Enable", true ); } void Launcher::makeVisible() { showMaximized(); } void Launcher::destroyGUI() { delete tb; tb = 0; delete tabs; tabs =0; } bool Launcher::eventFilter( QObject*, QEvent *ev ) { #ifdef QT_QWS_CUSTOM if ( ev->type() == QEvent::KeyPress ) { QKeyEvent *ke = (QKeyEvent *)ev; if ( ke->key() == Qt::Key_F11 ) { // menu key QWidget *active = qApp->activeWindow(); if ( active && active->isPopup() ) active->close(); else { Global::terminateBuiltin("calibrate"); // No tr tb->launchStartMenu(); } return TRUE; } } #else Q_UNUSED(ev); #endif return FALSE; } void Launcher::toggleSymbolInput() { tb->toggleSymbolInput(); } void Launcher::toggleNumLockState() { tb->toggleNumLockState(); } void Launcher::toggleCapsLockState() { tb->toggleCapsLockState(); } static bool isVisibleWindow(int wid) { #ifdef Q_WS_QWS const QList<QWSWindow> &list = qwsServer->clientWindows(); QWSWindow* w; for (QListIterator<QWSWindow> it(list); (w=it.current()); ++it) { if ( w->winId() == wid ) return !w->isFullyObscured(); } #endif return FALSE; } void Launcher::viewSelected(const QString& s) { setCaption( s + tr(" - Launcher") ); } void Launcher::showTab(const QString& id) { tabs->categoryBar->showTab(id); raise(); } void Launcher::select( const AppLnk *appLnk ) { if ( appLnk->type() == "Folder" ) { // No tr // Not supported: flat is simpler for the user } else { if ( appLnk->exec().isNull() ) { int i = QMessageBox::information(this,tr("No application"), tr("<p>No application is defined for this document." "<p>Type is %1.").arg(appLnk->type()), tr("OK"), tr("View as text"), 0, 0, 1); /* ### Fixme */ if ( i == 1 ) Global::execute("textedit",appLnk->file()); return; } tabs->setBusy(TRUE); emit executing( appLnk ); appLnk->execute(); } } void Launcher::properties( AppLnk *appLnk ) { if ( appLnk->type() == "Folder" ) { // No tr // Not supported: flat is simpler for the user } else { /* ### libqtopia FIXME also moving docLnks... */ LnkProperties prop(appLnk,0 ); QPEApplication::execDialog( &prop ); } } void Launcher::storageChanged( const QList<FileSystem> &fs ) { // ### update combo boxes if we had a combo box for the storage type } void Launcher::systemMessage( const QCString &msg, const QByteArray &data) { QDataStream stream( data, IO_ReadOnly ); if ( msg == "busy()" ) { tb->startWait(); } else if ( msg == "notBusy(QString)" ) { QString app; stream >> app; tabs->setBusy(FALSE); tb->stopWait(app); } else if (msg == "applyStyle()") { tabs->currentView()->relayout(); } } // These are the update functions from the server void Launcher::typeAdded( const QString& type, const QString& name, const QPixmap& pixmap, const QPixmap& ) { tabs->newView( type, pixmap, name ); ids.append( type ); /* this will be called in applicationScanningProgress with value 100! */ // tb->refreshStartMenu(); static bool first = TRUE; if ( first ) { first = FALSE; tabs->categoryBar->showTab(type); } tabs->view( type )->setUpdatesEnabled( FALSE ); tabs->view( type )->setSortEnabled( FALSE ); } void Launcher::typeRemoved( const QString& type ) { tabs->view( type )->removeAllItems(); tabs->deleteView( type ); ids.remove( type ); /* this will be called in applicationScanningProgress with value 100! */ // tb->refreshStartMenu(); } void Launcher::applicationAdded( const QString& type, const AppLnk& app ) { if ( app.type() == "Separator" ) // No tr return; LauncherView *view = tabs->view( type ); if ( view ) view->addItem( new AppLnk( app ), FALSE ); diff --git a/core/launcher/launcherview.cpp b/core/launcher/launcherview.cpp index 513b1bd..6c7d487 100644 --- a/core/launcher/launcherview.cpp +++ b/core/launcher/launcherview.cpp @@ -426,392 +426,392 @@ void LauncherItem::paintAnimatedIcon( QPainter *p ) x1 = x() + (width() - w) / 2 - liv->contentsX(); y1 = y() - liv->contentsY(); } else { x1 = x() - liv->contentsX(); y1 = y() + (height() - h) / 2 - liv->contentsY(); } y1 -= 2; p2.translate(-x1,-y1); liv->drawBackground( &p2, QRect(x1,y1,w,h+4) ); int bounceY = 2; #ifdef BOUNCE_BUSY_ICON if ( busyType == BIT_Animated ) { bounceY = 4 - ((iteration+2)%8); bounceY = bounceY < 0 ? -bounceY : bounceY; } #endif p2.drawPixmap( x1, y1 + bounceY, *pixmap() ); #ifdef USE_ANIMATED_BUSY_ICON_OVERLAY p2.drawPixmap( x1, y1 + bounceY, liv->busyPixmap(), w * pic, 0, w, h ); #endif p->drawPixmap( x1, y1, dblBuf ); } void LauncherItem::animateIcon() { LauncherIconView* liv = (LauncherIconView*)iconView(); if ( liv->busyItem() != this || !app ) return; // Highlight the icon if ( iteration == 0 ) { QPixmap src = isBigIcon ? app->bigPixmap() : app->pixmap(); QImage img = src.convertToImage(); QRgb *rgb; int count; if ( img.depth() == 32 ) { rgb = (QRgb*)img.bits(); count = img.bytesPerLine()/sizeof(QRgb)*img.height(); } else { rgb = img.colorTable(); count = img.numColors(); } for ( int r = 0; r < count; r++, rgb++ ) { #if defined(BRIGHTEN_BUSY_ICON) QColor c(*rgb); int h, s, v; c.hsv(&h,&s,&v); c.setHsv(h,QMAX(s-24,0),QMIN(v+48,255)); *rgb = qRgba(c.red(),c.green(),c.blue(),qAlpha(*rgb)); #elif defined(ALPHA_FADE_BUSY_ICON) *rgb = qRgba(qRed(*rgb),qGreen(*rgb),qBlue(*rgb),qAlpha(*rgb)/2); #endif } src.convertFromImage( img ); setPixmap( src ); } iteration++; // Paint animation overlay QPainter p( liv->viewport() ); paintAnimatedIcon( &p ); } void LauncherItem::resetIcon() { iteration = 0; setPixmap( isBigIcon ? app->bigPixmap() : app->pixmap() ); } //=========================================================================== QStringList LauncherIconView::mimeTypes() const { QStringList r; QDictIterator<void> it(mimes); while (it.current()) { r.append(it.currentKey()); ++it; } r.sort(); return r; } void LauncherIconView::addItem(AppLnk* app, bool resort) { addCatsAndMimes(app); if ( (tf.isEmpty() || tf.match(app->type()) >= 0) && (cf == 0 || app->categories().contains(cf) || cf == -1 && app->categories().count() == 0 ) ) (void) new LauncherItem( this, app, bigIcns ); else hidden.append(app); if ( resort ) sort(); } void LauncherIconView::updateCategoriesAndMimeTypes() { mimes.clear(); cats.clear(); LauncherItem* item = (LauncherItem*)firstItem(); while (item) { addCatsAndMimes(item->appLnk()); item = (LauncherItem*)item->nextItem(); } QListIterator<AppLnk> it(hidden); AppLnk* l; while ((l=it.current())) { addCatsAndMimes(l); ++it; } } void LauncherIconView::hideOrShowItems(bool resort) { viewport()->setUpdatesEnabled( FALSE ); hidden.setAutoDelete(FALSE); QList<AppLnk> links=hidden; hidden.clear(); hidden.setAutoDelete(TRUE); LauncherItem* item = (LauncherItem*)firstItem(); while (item) { links.append(item->takeAppLnk()); item = (LauncherItem*)item->nextItem(); } clear(); QListIterator<AppLnk> it(links); AppLnk* l; while ((l=it.current())) { addItem(l,FALSE); ++it; } if ( resort && !autoArrange() ) sort(); viewport()->setUpdatesEnabled( TRUE ); } bool LauncherIconView::removeLink(const QString& linkfile) { LauncherItem* item = (LauncherItem*)firstItem(); AppLnk* l; bool did = FALSE; DocLnk dl(linkfile); while (item) { l = item->appLnk(); LauncherItem *nextItem = (LauncherItem *)item->nextItem(); if ( l->linkFileKnown() && l->linkFile() == linkfile || l->fileKnown() && ( l->file() == linkfile || dl.isValid() && dl.file() == l->file() ) ) { delete item; did = TRUE; } item = nextItem; } QListIterator<AppLnk> it(hidden); while ((l=it.current())) { ++it; if ( l->linkFileKnown() && l->linkFile() == linkfile || l->file() == linkfile || dl.isValid() && dl.file() == l->file() ) { hidden.removeRef(l); did = TRUE; } } return did; } //=========================================================================== LauncherView::LauncherView( QWidget* parent, const char* name, WFlags fl ) : QVBox( parent, name, fl ) { catmb = 0; icons = new LauncherIconView( this ); setFocusProxy(icons); QPEApplication::setStylusOperation( icons->viewport(), QPEApplication::RightOnHold ); icons->setItemsMovable( FALSE ); icons->setAutoArrange( TRUE ); icons->setSorting( TRUE ); icons->setFrameStyle( QFrame::NoFrame ); icons->setMargin( 0 ); icons->setSelectionMode( QIconView::NoSelection ); icons->setBackgroundMode( PaletteBase ); icons->setResizeMode( QIconView::Fixed ); vmode = (ViewMode)-1; setViewMode( Icon ); - connect( icons, SIGNAL(mouseButtonClicked(int, QIconViewItem *, const QPoint&)), - SLOT(itemClicked(int, QIconViewItem *)) ); + connect( icons, SIGNAL(mouseButtonClicked(int,QIconViewItem*,const QPoint&)), + SLOT(itemClicked(int,QIconViewItem*)) ); connect( icons, SIGNAL(selectionChanged()), SLOT(selectionChanged()) ); - connect( icons, SIGNAL(returnPressed(QIconViewItem *)), - SLOT(returnPressed(QIconViewItem *)) ); - connect( icons, SIGNAL(mouseButtonPressed(int, QIconViewItem *, const QPoint&)), - SLOT(itemPressed(int, QIconViewItem *)) ); + connect( icons, SIGNAL(returnPressed(QIconViewItem*)), + SLOT(returnPressed(QIconViewItem*)) ); + connect( icons, SIGNAL(mouseButtonPressed(int,QIconViewItem*,const QPoint&)), + SLOT(itemPressed(int,QIconViewItem*)) ); tools = 0; setBackgroundType( Ruled, QString::null ); } LauncherView::~LauncherView() { if ( bgCache && bgCache->contains( bgName ) ) (*bgCache)[bgName]->ref--; } void LauncherView::hideIcons() { icons->hide(); } void LauncherView::setToolsEnabled(bool y) { if ( !y != !tools ) { if ( y ) { tools = new QHBox(this); // Type filter typemb = new QComboBox(tools); QSizePolicy p = typemb->sizePolicy(); p.setHorData(QSizePolicy::Expanding); typemb->setSizePolicy(p); // Category filter updateTools(); tools->show(); // Always show vscrollbar icons->setVScrollBarMode( QScrollView::AlwaysOn ); } else { delete tools; tools = 0; } } } void LauncherView::updateTools() { disconnect( typemb, SIGNAL(activated(int)), this, SLOT(showType(int)) ); if ( catmb ) disconnect( catmb, SIGNAL(signalSelected(int)), this, SLOT(showCategory(int)) ); // ### I want to remove this icons->updateCategoriesAndMimeTypes(); QString prev; // Type filter QStringList types; typelist = icons->mimeTypes(); for (QStringList::ConstIterator it = typelist.begin(); it!=typelist.end(); ++it) { QString t = *it; if ( t.left(12) == "application/" ) { MimeType mt(t); const AppLnk* app = mt.application(); if ( app ) t = app->name(); else t = t.mid(12); } else { t[0] = t[0].upper(); } types += t; } types << tr("All types"); prev = typemb->currentText(); typemb->clear(); typemb->insertStringList(types); for (int i=0; i<typemb->count(); i++) { if ( typemb->text(i) == prev ) { typemb->setCurrentItem(i); break; } } if ( prev.isNull() ) typemb->setCurrentItem(typemb->count()-1); int pcat = catmb ? catmb->currentCategory() : -2; if ( !catmb ) catmb = new CategorySelect(tools); Categories cats( 0 ); cats.load( categoryFileName() ); QArray<int> vl( 0 ); catmb->setCategories( vl, "Document View", // No tr tr("Document View") ); catmb->setRemoveCategoryEdit( TRUE ); catmb->setAllCategories( TRUE ); catmb->setCurrentCategory(pcat); // if type has changed we need to redisplay if ( typemb->currentText() != prev ) showType( typemb->currentItem() ); connect(typemb, SIGNAL(activated(int)), this, SLOT(showType(int))); connect(catmb, SIGNAL(signalSelected(int)), this, SLOT(showCategory(int))); } void LauncherView::sortBy(int s) { icons->setSortMethod((LauncherIconView::SortMethod)s); } void LauncherView::showType(int t) { if ( t >= (int)typelist.count() ) { icons->setTypeFilter("",TRUE); } else { QString ty = typelist[t]; if ( !ty.contains('/') ) ty += "/*"; icons->setTypeFilter(ty,TRUE); } } void LauncherView::showCategory( int c ) { icons->setCategoryFilter( c, TRUE ); } void LauncherView::setViewMode( ViewMode m ) { if ( vmode != m ) { bool bigIcons = m == Icon; icons->viewport()->setUpdatesEnabled( FALSE ); icons->setBigIcons( bigIcons ); switch ( m ) { case List: icons->setItemTextPos( QIconView::Right ); break; case Icon: icons->setItemTextPos( QIconView::Bottom ); break; } icons->hideOrShowItems( FALSE ); icons->viewport()->setUpdatesEnabled( TRUE ); vmode = m; } } // // User images may require scaling. // QImage LauncherView::loadBackgroundImage(QString &bgName) { QImageIO imgio; QSize ds = qApp->desktop()->size(); // should be launcher, not desktop bool further_scaling = TRUE; imgio.setFileName( bgName ); imgio.setParameters("GetHeaderInformation"); if (imgio.read() == FALSE) { return imgio.image(); } if (imgio.image().width() < ds.width() && imgio.image().height() < ds.height()) { further_scaling = FALSE; } if (!imgio.image().bits()) { // // Scale and load. Note we don't scale up. // QString param( "Scale( %1, %2, ScaleMin )" ); // No tr imgio.setParameters(further_scaling ? param.arg(ds.width()).arg(ds.height()).latin1() : ""); imgio.read(); } else { if (further_scaling) { int t1 = imgio.image().width() * ds.height(); int t2 = imgio.image().height() * ds.width(); int dsth = ds.height(); int dstw = ds.width(); if (t1 > t2) { dsth = t2 / imgio.image().width(); } else { dstw = t1 / imgio.image().height(); } // // Loader didn't scale for us. Do it manually. // return imgio.image().smoothScale(dstw, dsth); diff --git a/core/launcher/packageslave.cpp b/core/launcher/packageslave.cpp index 321b5dd..7e61b0e 100644 --- a/core/launcher/packageslave.cpp +++ b/core/launcher/packageslave.cpp @@ -1,248 +1,248 @@ /********************************************************************** ** Copyright (C) 2000-2002 Trolltech AS. All rights reserved. ** ** This file is part of the Qtopia Environment. ** ** This file may be distributed and/or modified under the terms of the ** GNU General Public License version 2 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. ** ** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE ** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. ** ** See http://www.trolltech.com/gpl/ for GPL licensing information. ** ** Contact info@trolltech.com if any conditions of this licensing are ** not clear to you. ** **********************************************************************/ #include "packageslave.h" #include <qtopia/qprocess.h> #ifdef Q_WS_QWS #include <qtopia/qcopenvelope_qws.h> #endif #ifdef Q_WS_QWS #include <qcopchannel_qws.h> #endif #include <qtextstream.h> #include <stdlib.h> #include <sys/stat.h> // mkdir() #if defined(_OS_LINUX_) || defined(Q_OS_LINUX) #include <unistd.h> #include <sys/vfs.h> #include <mntent.h> #elif defined(Q_OS_WIN32) #include <windows.h> #include <winbase.h> #elif defined(Q_OS_MACX) #include <unistd.h> #endif PackageHandler::PackageHandler( QObject *parent, char* name ) : QObject( parent, name ), packageChannel( 0 ), currentProcess( 0 ), mNoSpaceLeft( FALSE ) { // setup qcop channel #ifndef QT_NO_COP packageChannel = new QCopChannel( "QPE/Package", this ); - connect( packageChannel, SIGNAL( received(const QCString &, const QByteArray &) ), - this, SLOT( qcopMessage( const QCString &, const QByteArray &) ) ); + connect( packageChannel, SIGNAL( received(const QCString&,const QByteArray&) ), + this, SLOT( qcopMessage(const QCString&,const QByteArray&) ) ); #endif } void PackageHandler::qcopMessage( const QCString &msg, const QByteArray &data ) { QDataStream stream( data, IO_ReadOnly ); if ( msg == "installPackage(QString)" ) { QString file; stream >> file; installPackage( file ); } else if ( msg == "removePackage(QString)" ) { QString file; stream >> file; removePackage( file ); } else if ( msg == "addPackageFiles(QString,QString)" ) { QString location, listfile; stream >> location >> listfile; addPackageFiles( location, listfile); } else if ( msg == "addPackages(QString)" ) { QString location; stream >> location; addPackages( location ); } else if ( msg == "cleanupPackageFiles(QString)" ) { QString listfile; stream >> listfile; cleanupPackageFiles( listfile ); } else if ( msg == "cleanupPackages(QString)" ) { QString location; stream >> location; cleanupPackages( location ); } else if ( msg == "prepareInstall(QString,QString)" ) { QString size, path; stream >> size; stream >> path; prepareInstall( size, path ); } } void PackageHandler::installPackage( const QString &package ) { if ( mNoSpaceLeft ) { mNoSpaceLeft = FALSE; // Don't emit that for now, I still couldn't test it (Wener) //sendReply( "installFailed(QString)", package ); //return; } currentProcess = new QProcess( QStringList() << "ipkg" << "install" << package ); // No tr connect( currentProcess, SIGNAL( processExited() ), SLOT( iProcessExited() ) ); connect( currentProcess, SIGNAL( readyReadStdout() ), SLOT( readyReadStdout() ) ); connect( currentProcess, SIGNAL( readyReadStderr() ), SLOT( readyReadStderr() ) ); currentPackage = package; currentProcessError=""; sendReply( "installStarted(QString)", package ); currentProcess->start(); } void PackageHandler::removePackage( const QString &package ) { currentProcess = new QProcess( QStringList() << "ipkg" << "remove" << package ); // No tr connect( currentProcess, SIGNAL( processExited() ), SLOT( rmProcessExited() ) ); connect( currentProcess, SIGNAL( readyReadStdout() ), SLOT( readyReadStdout() ) ); connect( currentProcess, SIGNAL( readyReadStderr() ), SLOT( readyReadStderr() ) ); currentPackage = package; currentProcessError=""; sendReply( "removeStarted(QString)", package ); currentProcess->start(); } void PackageHandler::sendReply( const QCString& msg, const QString& arg ) { #ifndef QT_NO_COP QCopEnvelope e( "QPE/Desktop", msg ); e << arg; #endif } void PackageHandler::addPackageFiles( const QString &location, const QString &listfile ) { QFile f(listfile); #ifndef Q_OS_WIN32 //make a copy so we can remove the symlinks later mkdir( ("/usr/lib/ipkg/info/"+location).ascii(), 0777 ); system(("cp " + f.name() + " /usr/lib/ipkg/info/"+location).ascii()); #else QDir d; //#### revise qDebug("Copy file at %s: %s", __FILE__, __LINE__ ); d.mkdir(("/usr/lib/ipkg/info/" + location).ascii()); system(("copy " + f.name() + " /usr/lib/ipkg/info/"+location).ascii()); #endif if ( f.open(IO_ReadOnly) ) { QTextStream ts(&f); QString s; while ( !ts.eof() ) { // until end of file... s = ts.readLine(); // line of text excluding '\n' // for s, do link/mkdir. if ( s.right(1) == "/" ) { qDebug("do mkdir for %s", s.ascii()); #ifndef Q_OS_WIN32 mkdir( s.ascii(), 0777 ); //possible optimization: symlink directories //that don't exist already. -- Risky. #else d.mkdir( s.ascii()); #endif } else { #ifndef Q_OS_WIN32 qDebug("do symlink for %s", s.ascii()); symlink( (location + s).ascii(), s.ascii() ); #else qDebug("Copy file instead of a symlink for WIN32"); if (!CopyFile((TCHAR*)qt_winTchar((location + s), TRUE), (TCHAR*)qt_winTchar(s, TRUE), FALSE)) qWarning("Unable to create symlinkfor %s", (location + s).ascii()); #endif } } f.close(); } } void PackageHandler::addPackages( const QString &location ) { // get list of *.list in location/usr/lib/ipkg/info/*.list QDir dir(location + "/usr/lib/ipkg/info", "*.list", // No tr QDir::Name, QDir::Files); if ( !dir.exists() ) return; QStringList packages = dir.entryList(); for ( QStringList::Iterator it = packages.begin(); it != packages.end(); ++it ) { addPackageFiles( location, *it ); } } void PackageHandler::cleanupPackageFiles( const QString &listfile ) { QFile f(listfile); if ( f.open(IO_ReadOnly) ) { QTextStream ts(&f); QString s; while ( !ts.eof() ) { // until end of file... s = ts.readLine(); // line of text excluding '\n' // for s, do link/mkdir. if ( s.right(1) == "/" ) { //should rmdir if empty, after all files have been removed } else { #ifndef Q_OS_WIN32 qDebug("remove symlink for %s", s.ascii()); //check if it is a symlink first (don't remove /etc/passwd...) char buf[10]; //we don't care about the contents if ( ::readlink( s.ascii(),buf, 10 >= 0 ) ) ::unlink( s.ascii() ); #else // ### revise qWarning("Unable to remove symlink %s:%s", __FILE__, __LINE__); #endif } } f.close(); //remove the list file ::unlink( listfile.ascii() ); } } void PackageHandler::cleanupPackages( const QString &location ) { // get list of *.list in location/usr/lib/ipkg/info/*.list QDir dir( "/usr/lib/ipkg/info/"+location, "*.list", // No tr QDir::Name, QDir::Files); if ( !dir.exists() ) return; QStringList packages = dir.entryList(); for ( QStringList::Iterator it = packages.begin(); it != packages.end(); ++it ) { cleanupPackageFiles( *it ); diff --git a/core/launcher/qcopbridge.cpp b/core/launcher/qcopbridge.cpp index 24f471d..53efba4 100644 --- a/core/launcher/qcopbridge.cpp +++ b/core/launcher/qcopbridge.cpp @@ -1,298 +1,298 @@ /********************************************************************** ** Copyright (C) 2000-2002 Trolltech AS. All rights reserved. ** ** This file is part of the Qtopia Environment. ** ** This file may be distributed and/or modified under the terms of the ** GNU General Public License version 2 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. ** ** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE ** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. ** ** See http://www.trolltech.com/gpl/ for GPL licensing information. ** ** Contact info@trolltech.com if any conditions of this licensing are ** not clear to you. ** **********************************************************************/ #include "qcopbridge.h" #include "transferserver.h" #include <opie2/oglobal.h> #ifdef Q_WS_QWS #include <qtopia/qcopenvelope_qws.h> #endif #include <qtopia/qpeapplication.h> #include <qtopia/version.h> #include <qtextstream.h> #include <qtimer.h> #ifdef Q_WS_QWS #include <qcopchannel_qws.h> #endif #ifndef _XOPEN_SOURCE #define _XOPEN_SOURCE #endif #ifndef Q_OS_WIN32 #include <pwd.h> #include <unistd.h> #include <sys/types.h> #endif #if defined(_OS_LINUX_) #include <shadow.h> #endif //#define INSECURE const int block_size = 51200; QCopBridge::QCopBridge( Q_UINT16 port, QObject *parent, const char* name ) : QServerSocket( port, 1, parent, name ), desktopChannel( 0 ), cardChannel( 0 ) { if ( !ok() ) qWarning( "Failed to bind to port %d", port ); else { #ifndef QT_NO_COP desktopChannel = new QCopChannel( "QPE/Desktop", this ); - connect( desktopChannel, SIGNAL(received(const QCString &, const QByteArray &)), - this, SLOT(desktopMessage( const QCString &, const QByteArray &)) ); + connect( desktopChannel, SIGNAL(received(const QCString&,const QByteArray&)), + this, SLOT(desktopMessage(const QCString&,const QByteArray&)) ); cardChannel = new QCopChannel( "QPE/Card", this ); - connect( cardChannel, SIGNAL(received(const QCString &, const QByteArray &)), - this, SLOT(desktopMessage( const QCString &, const QByteArray &)) ); + connect( cardChannel, SIGNAL(received(const QCString&,const QByteArray&)), + this, SLOT(desktopMessage(const QCString&,const QByteArray&)) ); #endif } sendSync = FALSE; openConnections.setAutoDelete( TRUE ); authorizeConnections(); } QCopBridge::~QCopBridge() { #ifndef QT_NO_COP delete desktopChannel; #endif } void QCopBridge::authorizeConnections() { Config cfg("Security"); cfg.setGroup("SyncMode"); m_mode = Mode(cfg.readNumEntry("Mode", Sharp )); QListIterator<QCopBridgePI> it(openConnections); while ( it.current() ) { if ( !it.current()->verifyAuthorised() ) { - disconnect ( it.current(), SIGNAL( connectionClosed( QCopBridgePI *) ), this, SLOT( closed( QCopBridgePI *) ) ); + disconnect ( it.current(), SIGNAL( connectionClosed(QCopBridgePI*) ), this, SLOT( closed(QCopBridgePI*) ) ); openConnections.removeRef( it.current() ); } else ++it; } } void QCopBridge::newConnection( int socket ) { QCopBridgePI *pi = new QCopBridgePI( socket, this ); openConnections.append( pi ); - connect ( pi, SIGNAL( connectionClosed( QCopBridgePI *) ), this, SLOT( closed( QCopBridgePI *) ) ); + connect ( pi, SIGNAL( connectionClosed(QCopBridgePI*) ), this, SLOT( closed(QCopBridgePI*) ) ); /* ### libqtopia merge FIXME */ #if 0 QPEApplication::setTempScreenSaverMode( QPEApplication::DisableSuspend ); #endif #ifndef QT_NO_COP QCopEnvelope( "QPE/System", "setScreenSaverMode(int)" ) << QPEApplication::DisableSuspend; #endif if ( sendSync ) { pi ->startSync(); sendSync = FALSE; } } void QCopBridge::closed( QCopBridgePI *pi ) { emit connectionClosed( pi->peerAddress() ); openConnections.removeRef( pi ); if ( openConnections.count() == 0 ) { /* ### FIXME libqtopia merge */ #if 0 QPEApplication::setTempScreenSaverMode( QPEApplication::Enable ); #endif #ifndef QT_NO_COP QCopEnvelope( "QPE/System", "setScreenSaverMode(int)" ) << QPEApplication::Enable; #endif } } void QCopBridge::closeOpenConnections() { QCopBridgePI *pi; for ( pi = openConnections.first(); pi != 0; pi = openConnections.next() ) pi->close(); } void QCopBridge::desktopMessage( const QCString &command, const QByteArray &data ) { if ( command == "startSync()" ) { // we need to buffer it a bit sendSync = TRUE; startTimer( 20000 ); } if ( m_mode & Qtopia1_7 ) { // send the command to all open connections QCopBridgePI *pi; for ( pi = openConnections.first(); pi != 0; pi = openConnections.next() ) { pi->sendDesktopMessage( command, data ); } } if ( ( m_mode & Sharp ) || (m_mode & IntelliSync) ) sendDesktopMessageOld( command, data ); } #ifndef OPIE_NO_OLD_SYNC_CODE /* * Old compat mode */ void QCopBridge::sendDesktopMessageOld( const QCString& command, const QByteArray& args) { command.stripWhiteSpace(); int paren = command.find( "(" ); if ( paren <= 0 ) { qDebug("DesktopMessage: bad qcop syntax"); return; } QString params = command.mid( paren + 1 ); if ( params[params.length()-1] != ')' ) { qDebug("DesktopMessage: bad qcop syntax"); return; } params.truncate( params.length()-1 ); QStringList paramList = QStringList::split( ",", params ); QString data; if ( paramList.count() ) { QDataStream stream( args, IO_ReadOnly ); for ( QStringList::Iterator it = paramList.begin(); it != paramList.end(); ++it ) { QString str; if ( *it == "QString" ) { stream >> str; } else if ( *it == "QCString" ) { QCString cstr; stream >> cstr; str = QString::fromLocal8Bit( cstr ); } else if ( *it == "int" ) { int i; stream >> i; str = QString::number( i ); } else if ( *it == "bool" ) { int i; stream >> i; str = QString::number( i ); } else { qDebug(" cannot route the argument type %s throught the qcop bridge", (*it).latin1() ); return; } QString estr; for (int i=0; i<(int)str.length(); i++) { QChar ch = str[i]; if ( ch.row() ) goto quick; switch (ch.cell()) { case '&': estr.append( "&" ); break; case ' ': estr.append( "&0x20;" ); break; case '\n': estr.append( "&0x0d;" ); break; case '\r': estr.append( "&0x0a;" ); break; default: quick: estr.append(ch); } } data += " " + estr; } } QString sendCommand = QString(command.data()) + data; // send the command to all open connections QCopBridgePI *pi; for ( pi = openConnections.first(); pi != 0; pi = openConnections.next() ) pi->sendDesktopMessage( sendCommand ); } #endif void QCopBridge::timerEvent( QTimerEvent * ) { sendSync = FALSE; killTimers(); } QCopBridgePI::QCopBridgePI( int socket, QObject *parent, const char* name ) : QSocket( parent, name ) { setSocket( socket ); peerport = peerPort(); peeraddress = peerAddress(); #ifndef INSECURE if ( !SyncAuthentication::isAuthorized(peeraddress) ) { state = Forbidden; close(); } else #endif { state = Connected; connect( this, SIGNAL( readyRead() ), SLOT( read() ) ); QString intro="220 Qtopia "; intro += QPE_VERSION; intro += ";"; intro += "challenge="; intro += SyncAuthentication::serverId(); intro += ";"; // No tr intro += "loginname="; intro += SyncAuthentication::loginName(); intro += ";"; intro += "displayname="; intro += SyncAuthentication::ownerName(); intro += ";"; send( intro ); state = Wait_USER; } sendSync = FALSE; connect( this, SIGNAL( connectionClosed() ), SLOT( myConnectionClosed() ) ); // idle timer to close connections when not used anymore timer = new QTimer(this); connect( timer, SIGNAL(timeout()), this, SLOT(myConnectionClosed()) ); timer->start( 300000, TRUE ); } QCopBridgePI::~QCopBridgePI() { } bool QCopBridgePI::verifyAuthorised() { if ( !SyncAuthentication::isAuthorized(peerAddress()) ) { state = Forbidden; return FALSE; } return TRUE; diff --git a/core/launcher/runningappbar.cpp b/core/launcher/runningappbar.cpp index 11d10dc..2e9d2a9 100644 --- a/core/launcher/runningappbar.cpp +++ b/core/launcher/runningappbar.cpp @@ -1,172 +1,172 @@ /********************************************************************** ** Copyright (C) 2000-2002 Trolltech AS. All rights reserved. ** ** This file is part of the Qtopia Environment. ** ** This file may be distributed and/or modified under the terms of the ** GNU General Public License version 2 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. ** ** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE ** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. ** ** See http://www.trolltech.com/gpl/ for GPL licensing information. ** ** Contact info@trolltech.com if any conditions of this licensing are ** not clear to you. ** ***********************************************************************/ #define QTOPIA_INTERNAL_PRELOADACCESS #include <stdlib.h> #include <qpainter.h> #include <qtopia/qcopenvelope_qws.h> #include "runningappbar.h" #include "serverinterface.h" RunningAppBar::RunningAppBar(QWidget* parent) : QFrame(parent), selectedAppIndex(-1) { QCopChannel* channel = new QCopChannel( "QPE/System", this ); - connect( channel, SIGNAL(received(const QCString&, const QByteArray&)), - this, SLOT(received(const QCString&, const QByteArray&)) ); + connect( channel, SIGNAL(received(const QCString&,const QByteArray&)), + this, SLOT(received(const QCString&,const QByteArray&)) ); spacing = AppLnk::smallIconSize()+3; } RunningAppBar::~RunningAppBar() { } void RunningAppBar::received(const QCString& msg, const QByteArray& data) { // Since fast apps appear and disappear without disconnecting from their // channel we need to watch for the showing/hiding events and update according. QDataStream stream( data, IO_ReadOnly ); if ( msg == "fastAppShowing(QString)") { QString appName; stream >> appName; // qDebug("fastAppShowing %s", appName.data() ); const AppLnk* f = ServerInterface::appLnks().findExec(appName); if ( f ) addTask(*f); } else if ( msg == "fastAppHiding(QString)") { QString appName; stream >> appName; const AppLnk* f = ServerInterface::appLnks().findExec(appName); if ( f ) removeTask(*f); } } void RunningAppBar::addTask(const AppLnk& appLnk) { qDebug("Added %s to app list.", appLnk.name().latin1()); AppLnk* newApp = new AppLnk(appLnk); newApp->setExec(appLnk.exec()); appList.prepend(newApp); update(); } void RunningAppBar::removeTask(const AppLnk& appLnk) { unsigned int i = 0; for (; i < appList.count() ; i++) { AppLnk* target = appList.at(i); if (target->exec() == appLnk.exec()) { qDebug("Removing %s from app list.", appLnk.name().latin1()); appList.remove(); delete target; } } update(); } void RunningAppBar::mousePressEvent(QMouseEvent *e) { // Find out if the user is clicking on an app icon... // If so, snag the index so when we repaint we show it // as highlighed. selectedAppIndex = 0; int x=0; QListIterator<AppLnk> it( appList ); for ( ; it.current(); ++it,++selectedAppIndex,x+=spacing ) { if ( x + spacing <= width() ) { if ( e->x() >= x && e->x() < x+spacing ) { if ( selectedAppIndex < (int)appList.count() ) { repaint(FALSE); return; } } } else { break; } } selectedAppIndex = -1; repaint( FALSE ); } void RunningAppBar::mouseReleaseEvent(QMouseEvent *e) { if (e->button() == QMouseEvent::RightButton) return; if ( selectedAppIndex >= 0 ) { QString app = appList.at(selectedAppIndex)->exec(); QCopEnvelope e("QPE/System", "raise(QString)"); e << app; selectedAppIndex = -1; update(); } } void RunningAppBar::paintEvent( QPaintEvent * ) { QPainter p( this ); AppLnk *curApp; int x = 0; int y = (height() - AppLnk::smallIconSize()) / 2; int i = 0; p.fillRect( 0, 0, width(), height(), colorGroup().background() ); QListIterator<AppLnk> it(appList); for (; it.current(); i++, ++it ) { if ( x + spacing <= width() ) { curApp = it.current(); qWarning("Drawing %s", curApp->name().latin1() ); if ( (int)i == selectedAppIndex ) p.fillRect( x, y, spacing, curApp->pixmap().height()+1, colorGroup().highlight() ); else p.eraseRect( x, y, spacing, curApp->pixmap().height()+1 ); p.drawPixmap( x, y, curApp->pixmap() ); x += spacing; } } } QSize RunningAppBar::sizeHint() const { return QSize( frameWidth(), AppLnk::smallIconSize()+frameWidth()*2+3 ); } void RunningAppBar::applicationLaunched(const QString &appName) { qDebug("desktop:: app: %s launched with pid ", appName.data() ); const AppLnk* newGuy = ServerInterface::appLnks().findExec(appName); if ( newGuy && !newGuy->isPreloaded() ) { addTask( *newGuy ); } } void RunningAppBar::applicationTerminated(const QString &app) { const AppLnk* gone = ServerInterface::appLnks().findExec(app); if ( gone ) { removeTask(*gone); } } diff --git a/core/launcher/server.cpp b/core/launcher/server.cpp index 068d716..ea0b792 100644 --- a/core/launcher/server.cpp +++ b/core/launcher/server.cpp @@ -1,365 +1,365 @@ /********************************************************************** ** Copyright (C) 2000-2002 Trolltech AS. All rights reserved. ** ** This file is part of the Qtopia Environment. ** ** This file may be distributed and/or modified under the terms of the ** GNU General Public License version 2 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. ** ** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE ** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. ** ** See http://www.trolltech.com/gpl/ for GPL licensing information. ** ** Contact info@trolltech.com if any conditions of this licensing are ** not clear to you. ** **********************************************************************/ #include "server.h" #include "serverapp.h" #include "startmenu.h" #include "launcher.h" #include "transferserver.h" #include "qcopbridge.h" #include "irserver.h" #include "packageslave.h" #include "calibrate.h" #include "qrsync.h" #include "syncdialog.h" #include "shutdownimpl.h" #include "applauncher.h" #if 0 #include "suspendmonitor.h" #endif #include "documentlist.h" #include <qtopia/applnk.h> #include <qtopia/private/categories.h> #include <qtopia/mimetype.h> #include <qtopia/config.h> #include <qtopia/resource.h> #include <qtopia/version.h> #include <qtopia/storage.h> #include <qtopia/qcopenvelope_qws.h> #include <qwindowsystem_qws.h> #include <qgfx_qws.h> #include <qtopia/global.h> //#include <qtopia/custom.h> #include <opie2/odevicebutton.h> #include <opie2/odevice.h> #include <unistd.h> #include <qmainwindow.h> #include <qmessagebox.h> #include <qtimer.h> #include <qtextstream.h> #include <stdlib.h> extern QRect qt_maxWindowRect; using namespace Opie; static QWidget *calibrate(bool) { #ifdef Q_WS_QWS Calibrate *c = new Calibrate; c->show(); return c; #else return 0; #endif } #define FACTORY(T) \ static QWidget *new##T( bool maximized ) { \ QWidget *w = new T( 0, 0, QWidget::WDestructiveClose | QWidget::WGroupLeader ); \ if ( maximized ) { \ if ( qApp->desktop()->width() <= 350 ) { \ w->showMaximized(); \ } else { \ w->resize( QSize( 300, 300 ) ); \ } \ } \ w->show(); \ return w; \ } #ifdef SINGLE_APP #define APP(a,b,c,d) FACTORY(b) #include "apps.h" #undef APP #endif // SINGLE_APP static Global::Command builtins[] = { #ifdef SINGLE_APP #define APP(a,b,c,d) { a, new##b, c, d }, #include "apps.h" #undef APP #endif /* FIXME defines need to be defined*/ #if !defined(OPIE_NO_BUILTIN_CALIBRATE) { "calibrate", calibrate, 1, 0 }, // No tr #endif #if !defined(OPIE_NO_BUILTIN_SHUTDOWN) { "shutdown", Global::shutdown, 1, 0 }, // No tr // { "run", run, 1, 0 }, // No tr #endif { 0, calibrate, 0, 0 }, }; //--------------------------------------------------------------------------- //=========================================================================== Server::Server() : QWidget( 0, 0, WStyle_Tool | WStyle_Customize ), qcopBridge( 0 ), transferServer( 0 ), packageHandler( 0 ), syncDialog( 0 ) { Global::setBuiltinCommands(builtins); tid_xfer = 0; /* ### FIXME ### */ /* tid_today = startTimer(3600*2*1000);*/ last_today_show = QDate::currentDate(); #if 0 tsmMonitor = new TempScreenSaverMode(); connect( tsmMonitor, SIGNAL(forceSuspend()), qApp, SIGNAL(power()) ); #endif serverGui = new Launcher; serverGui->createGUI(); docList = new DocumentList( serverGui ); appLauncher = new AppLauncher(this); - connect(appLauncher, SIGNAL(launched(int, const QString &)), this, SLOT(applicationLaunched(int, const QString &)) ); - connect(appLauncher, SIGNAL(terminated(int, const QString &)), this, SLOT(applicationTerminated(int, const QString &)) ); - connect(appLauncher, SIGNAL(connected(const QString &)), this, SLOT(applicationConnected(const QString &)) ); + connect(appLauncher, SIGNAL(launched(int,const QString&)), this, SLOT(applicationLaunched(int,const QString&)) ); + connect(appLauncher, SIGNAL(terminated(int,const QString&)), this, SLOT(applicationTerminated(int,const QString&)) ); + connect(appLauncher, SIGNAL(connected(const QString&)), this, SLOT(applicationConnected(const QString&)) ); storage = new StorageInfo( this ); connect( storage, SIGNAL(disksChanged()), this, SLOT(storageChanged()) ); // start services startTransferServer(); (void) new IrServer( this ); packageHandler = new PackageHandler( this ); connect(qApp, SIGNAL(activate(const Opie::ODeviceButton*,bool)), this,SLOT(activate(const Opie::ODeviceButton*,bool))); setGeometry( -10, -10, 9, 9 ); QCopChannel *channel = new QCopChannel("QPE/System", this); - connect(channel, SIGNAL(received(const QCString &, const QByteArray &)), - this, SLOT(systemMsg(const QCString &, const QByteArray &)) ); + connect(channel, SIGNAL(received(const QCString&,const QByteArray&)), + this, SLOT(systemMsg(const QCString&,const QByteArray&)) ); QCopChannel *tbChannel = new QCopChannel( "QPE/TaskBar", this ); - connect( tbChannel, SIGNAL(received(const QCString&, const QByteArray&)), - this, SLOT(receiveTaskBar(const QCString&, const QByteArray&)) ); + connect( tbChannel, SIGNAL(received(const QCString&,const QByteArray&)), + this, SLOT(receiveTaskBar(const QCString&,const QByteArray&)) ); connect( qApp, SIGNAL(prepareForRestart()), this, SLOT(terminateServers()) ); connect( qApp, SIGNAL(timeChanged()), this, SLOT(pokeTimeMonitors()) ); preloadApps(); } void Server::show() { ServerApplication::login(TRUE); QWidget::show(); } Server::~Server() { serverGui->destroyGUI(); delete docList; delete qcopBridge; delete transferServer; delete serverGui; #if 0 delete tsmMonitor; #endif } static bool hasVisibleWindow(const QString& clientname, bool partial) { #ifdef QWS const QList<QWSWindow> &list = qwsServer->clientWindows(); QWSWindow* w; for (QListIterator<QWSWindow> it(list); (w=it.current()); ++it) { if ( w->client()->identity() == clientname ) { if ( partial && !w->isFullyObscured() ) return TRUE; if ( !partial && !w->isFullyObscured() && !w->isPartiallyObscured() ) { # if QT_VERSION < 0x030000 QRect mwr = qt_screen->mapToDevice(qt_maxWindowRect, QSize(qt_screen->width(),qt_screen->height()) ); # else QRect mwr = qt_maxWindowRect; # endif if ( mwr.contains(w->requested().boundingRect()) ) return TRUE; } } } #endif return FALSE; } void Server::activate(const Opie::ODeviceButton* button, bool held) { Global::terminateBuiltin("calibrate"); // No tr Opie::OQCopMessage om; if ( held ) { om = button->heldAction(); } else { om = button->pressedAction(); } if ( om.channel() != "ignore" ) om.send(); // A button with no action defined, will return a null ServiceRequest. Don't attempt // to send/do anything with this as it will crash /* ### FIXME */ #if 0 if ( !sr.isNull() ) { QString app = sr.app(); bool vis = hasVisibleWindow(app, app != "qpe"); if ( sr.message() == "raise()" && vis ) { sr.setMessage("nextView()"); } else { // "back door" sr << (int)vis; } sr.send(); } #endif } #ifdef Q_WS_QWS typedef struct KeyOverride { ushort scan_code; QWSServer::KeyMap map; }; static const KeyOverride jp109keys[] = { { 0x03, { Qt::Key_2, '2' , 0x22 , 0xffff } }, { 0x07, { Qt::Key_6, '6' , '&' , 0xffff } }, { 0x08, { Qt::Key_7, '7' , '\'' , 0xffff } }, { 0x09, { Qt::Key_8, '8' , '(' , 0xffff } }, { 0x0a, { Qt::Key_9, '9' , ')' , 0xffff } }, { 0x0b, { Qt::Key_0, '0' , 0xffff , 0xffff } }, { 0x0c, { Qt::Key_Minus, '-' , '=' , 0xffff } }, { 0x0d, { Qt::Key_AsciiCircum,'^' , '~' , '^' - 64 } }, { 0x1a, { Qt::Key_At, '@' , '`' , 0xffff } }, { 0x1b, { Qt::Key_BraceLeft, '[' , '{' , '[' - 64 } }, { 0x27, { Qt::Key_Semicolon, ';' , '+' , 0xffff } }, { 0x28, { Qt::Key_Colon, ':' , '*' , 0xffff } }, { 0x29, { Qt::Key_Zenkaku_Hankaku, 0xffff , 0xffff , 0xffff } }, { 0x2b, { Qt::Key_BraceRight, ']' , '}' , ']'-64 } }, { 0x70, { Qt::Key_Hiragana_Katakana, 0xffff , 0xffff , 0xffff } }, { 0x73, { Qt::Key_Backslash, '\\' , '_' , 0xffff } }, { 0x79, { Qt::Key_Henkan, 0xffff , 0xffff , 0xffff } }, { 0x7b, { Qt::Key_Muhenkan, 0xffff , 0xffff , 0xffff } }, { 0x7d, { Qt::Key_yen, 0x00a5 , '|' , 0xffff } }, { 0x00, { 0, 0xffff , 0xffff , 0xffff } } }; bool Server::setKeyboardLayout( const QString &kb ) { //quick demo version that can be extended QIntDict<QWSServer::KeyMap> *om = 0; if ( kb == "us101" ) { // No tr om = 0; } else if ( kb == "jp109" ) { om = new QIntDict<QWSServer::KeyMap>(37); const KeyOverride *k = jp109keys; while ( k->scan_code ) { om->insert( k->scan_code, &k->map ); k++; } } QWSServer::setOverrideKeys( om ); return TRUE; } #endif void Server::systemMsg(const QCString &msg, const QByteArray &data) { QDataStream stream( data, IO_ReadOnly ); if ( msg == "securityChanged()" ) { if ( transferServer ) transferServer->authorizeConnections(); if ( qcopBridge ) qcopBridge->authorizeConnections(); } /* ### FIXME support TempScreenSaverMode */ #if 0 else if ( msg == "setTempScreenSaverMode(int,int)" ) { int mode, pid; stream >> mode >> pid; tsmMonitor->setTempMode(mode, pid); } #endif else if ( msg == "linkChanged(QString)" ) { QString link; stream >> link; qDebug( "desktop.cpp systemMsg -> linkchanged( %s )", link.latin1() ); docList->linkChanged(link); } else if ( msg == "serviceChanged(QString)" ) { MimeType::updateApplications(); } else if ( msg == "mkdir(QString)" ) { QString dir; stream >> dir; if ( !dir.isEmpty() ) mkdir( dir ); } else if ( msg == "rdiffGenSig(QString,QString)" ) { QString baseFile, sigFile; stream >> baseFile >> sigFile; QRsync::generateSignature( baseFile, sigFile ); } else if ( msg == "rdiffGenDiff(QString,QString,QString)" ) { QString baseFile, sigFile, deltaFile; stream >> baseFile >> sigFile >> deltaFile; QRsync::generateDiff( baseFile, sigFile, deltaFile ); } else if ( msg == "rdiffApplyPatch(QString,QString)" ) { QString baseFile, deltaFile; stream >> baseFile >> deltaFile; if ( !QFile::exists( baseFile ) ) { QFile f( baseFile ); f.open( IO_WriteOnly ); f.close(); } QRsync::applyDiff( baseFile, deltaFile ); #ifndef QT_NO_COP QCopEnvelope e( "QPE/Desktop", "patchApplied(QString)" ); e << baseFile; #endif } else if ( msg == "rdiffCleanup()" ) { mkdir( "/tmp/rdiff" ); QDir dir; dir.setPath( "/tmp/rdiff" ); @@ -424,306 +424,306 @@ void Server::systemMsg(const QCString &msg, const QByteArray &data) cfg.setGroup("SyncDate"); #ifndef QT_NO_COP QCopEnvelope e( "QPE/Desktop", "syncDate(QString,QString)" ); e << app << cfg.readEntry( app ); #endif //qDebug("QPE/System sendSyncDate for %s: response %s", app.latin1(), //cfg.readEntry( app ).latin1() ); } else if ( msg == "setSyncDate(QString,QString)" ) { QString app, date; stream >> app >> date; Config cfg( "qpe" ); cfg.setGroup("SyncDate"); cfg.writeEntry( app, date ); //qDebug("setSyncDate(QString,QString) %s %s", app.latin1(), date.latin1()); } else if ( msg == "startSync(QString)" ) { QString what; stream >> what; delete syncDialog; syncDialog = new SyncDialog( this, what ); syncDialog->show(); connect( syncDialog, SIGNAL(cancel()), SLOT(cancelSync()) ); } else if ( msg == "stopSync()") { delete syncDialog; syncDialog = 0; } else if (msg == "restoreDone(QString)") { docList->restoreDone(); } else if ( msg == "getAllDocLinks()" ) { docList->sendAllDocLinks(); } #ifdef Q_WS_QWS else if ( msg == "setMouseProto(QString)" ) { QString mice; stream >> mice; setenv("QWS_MOUSE_PROTO",mice.latin1(),1); qwsServer->openMouse(); } else if ( msg == "setKeyboard(QString)" ) { QString kb; stream >> kb; setenv("QWS_KEYBOARD",kb.latin1(),1); qwsServer->openKeyboard(); } else if ( msg == "setKeyboardAutoRepeat(int,int)" ) { int delay, period; stream >> delay >> period; qwsSetKeyboardAutoRepeat( delay, period ); Config cfg( "qpe" ); cfg.setGroup("Keyboard"); cfg.writeEntry( "RepeatDelay", delay ); cfg.writeEntry( "RepeatPeriod", period ); } else if ( msg == "setKeyboardLayout(QString)" ) { QString kb; stream >> kb; setKeyboardLayout( kb ); Config cfg( "qpe" ); cfg.setGroup("Keyboard"); cfg.writeEntry( "Layout", kb ); } else if ( msg == "autoStart(QString)" ) { QString appName; stream >> appName; Config cfg( "autostart" ); cfg.setGroup( "AutoStart" ); if ( appName.compare("clear") == 0){ cfg.writeEntry("Apps", ""); } } else if ( msg == "autoStart(QString,QString)" ) { QString modifier, appName; stream >> modifier >> appName; Config cfg( "autostart" ); cfg.setGroup( "AutoStart" ); if ( modifier.compare("add") == 0 ){ // only add if appname is entered if (!appName.isEmpty()) { cfg.writeEntry("Apps", appName); } } else if (modifier.compare("remove") == 0 ) { // need to change for multiple entries // actually remove is right now simular to clear, but in future there // should be multiple apps in autostart possible. QString checkName; checkName = cfg.readEntry("Apps", ""); if (checkName == appName) { cfg.writeEntry("Apps", ""); } } // case the autostart feature should be delayed } else if ( msg == "autoStart(QString,QString,QString)") { QString modifier, appName, delay; stream >> modifier >> appName >> delay; Config cfg( "autostart" ); cfg.setGroup( "AutoStart" ); if ( modifier.compare("add") == 0 ){ // only add it appname is entered if (!appName.isEmpty()) { cfg.writeEntry("Apps", appName); cfg.writeEntry("Delay", delay); } } else { } } #endif } void Server::receiveTaskBar(const QCString &msg, const QByteArray &data) { QDataStream stream( data, IO_ReadOnly ); if ( msg == "reloadApps()" ) { docList->reloadAppLnks(); } else if ( msg == "soundAlarm()" ) { ServerApplication::soundAlarm(); } else if ( msg == "setLed(int,bool)" ) { int led, status; stream >> led >> status; QValueList <OLed> ll = ODevice::inst ( )-> ledList ( ); if ( ll. count ( )) { OLed l = ll. contains ( Led_Mail ) ? Led_Mail : ll [0]; bool canblink = ODevice::inst ( )-> ledStateList ( l ). contains ( Led_BlinkSlow ); ODevice::inst ( )-> setLedState ( l, status ? ( canblink ? Led_BlinkSlow : Led_On ) : Led_Off ); } } } void Server::cancelSync() { #ifndef QT_NO_COP QCopEnvelope e( "QPE/Desktop", "cancelSync()" ); #endif delete syncDialog; syncDialog = 0; } bool Server::mkdir(const QString &localPath) { QDir fullDir(localPath); if (fullDir.exists()) return true; // at this point the directory doesn't exist // go through the directory tree and start creating the direcotories // that don't exist; if we can't create the directories, return false QString dirSeps = "/"; int dirIndex = localPath.find(dirSeps); QString checkedPath; // didn't find any seps; weird, use the cur dir instead if (dirIndex == -1) { //qDebug("No seperators found in path %s", localPath.latin1()); checkedPath = QDir::currentDirPath(); } while (checkedPath != localPath) { // no more seperators found, use the local path if (dirIndex == -1) checkedPath = localPath; else { // the next directory to check checkedPath = localPath.left(dirIndex) + "/"; // advance the iterator; the next dir seperator dirIndex = localPath.find(dirSeps, dirIndex+1); } QDir checkDir(checkedPath); if (!checkDir.exists()) { //qDebug("mkdir making dir %s", checkedPath.latin1()); if (!checkDir.mkdir(checkedPath)) { qDebug("Unable to make directory %s", checkedPath.latin1()); return FALSE; } } } return TRUE; } void Server::styleChange( QStyle &s ) { QWidget::styleChange( s ); } void Server::startTransferServer() { if ( !qcopBridge ) { // start qcop bridge server qcopBridge = new QCopBridge( 4243 ); if ( qcopBridge->ok() ) { // ... OK - connect( qcopBridge, SIGNAL(connectionClosed(const QHostAddress &)), - this, SLOT(syncConnectionClosed(const QHostAddress &)) ); + connect( qcopBridge, SIGNAL(connectionClosed(const QHostAddress&)), + this, SLOT(syncConnectionClosed(const QHostAddress&)) ); } else { delete qcopBridge; qcopBridge = 0; } } if ( !transferServer ) { // start transfer server transferServer = new TransferServer( 4242 ); if ( transferServer->ok() ) { // ... OK } else { delete transferServer; transferServer = 0; } } if ( !transferServer || !qcopBridge ) tid_xfer = startTimer( 2000 ); } void Server::timerEvent( QTimerEvent *e ) { if ( e->timerId() == tid_xfer ) { killTimer( tid_xfer ); tid_xfer = 0; startTransferServer(); } /* ### FIXME today startin */ #if 0 else if ( e->timerId() == tid_today ) { QDate today = QDate::currentDate(); if ( today != last_today_show ) { last_today_show = today; Config cfg("today"); cfg.setGroup("Start"); #ifndef QPE_DEFAULT_TODAY_MODE #define QPE_DEFAULT_TODAY_MODE "Never" #endif if ( cfg.readEntry("Mode",QPE_DEFAULT_TODAY_MODE) == "Daily" ) { QCopEnvelope env(Service::channel("today"),"raise()"); } } } #endif } void Server::terminateServers() { delete transferServer; delete qcopBridge; transferServer = 0; qcopBridge = 0; } void Server::syncConnectionClosed( const QHostAddress & ) { qDebug( "Lost sync connection" ); delete syncDialog; syncDialog = 0; } void Server::pokeTimeMonitors() { #if 0 // inform all TimeMonitors QStrList tms = Service::channels("TimeMonitor"); for (const char* ch = tms.first(); ch; ch=tms.next()) { QString t = getenv("TZ"); QCopEnvelope e(ch, "timeChange(QString)"); e << t; } #endif } void Server::applicationLaunched(int, const QString &app) { serverGui->applicationStateChanged( app, ServerInterface::Launching ); } void Server::applicationTerminated(int pid, const QString &app) { serverGui->applicationStateChanged( app, ServerInterface::Terminated ); #if 0 tsmMonitor->applicationTerminated( pid ); #endif } void Server::applicationConnected(const QString &app) { serverGui->applicationStateChanged( app, ServerInterface::Running ); } void Server::storageChanged() { system( "qtopia-update-symlinks" ); serverGui->storageChanged( storage->fileSystems() ); docList->storageChanged(); } void Server::preloadApps() { Config cfg("Launcher"); cfg.setGroup("Preload"); QStringList apps = cfg.readListEntry("Apps",','); for (QStringList::ConstIterator it=apps.begin(); it!=apps.end(); ++it) { #ifndef QT_NO_COP QCopEnvelope e("QPE/Application/"+(*it).local8Bit(), "enablePreload()"); #endif } } diff --git a/core/launcher/serverapp.cpp b/core/launcher/serverapp.cpp index f7c2341..d38dd97 100644 --- a/core/launcher/serverapp.cpp +++ b/core/launcher/serverapp.cpp @@ -112,396 +112,396 @@ private: int alertCount; }; void DesktopPowerAlerter::alert( const QString &text, int priority ) { alertCount++; if ( alertCount < priority ) return; if ( priority > currentPriority ) return; currentPriority = priority; setText( text ); show(); } void DesktopPowerAlerter::hideEvent( QHideEvent *e ) { QMessageBox::hideEvent( e ); alertCount = 0; currentPriority = INT_MAX; } //--------------------------------------------------------------------------- KeyFilter::KeyFilter(QObject* parent) : QObject(parent), held_tid(0), heldButton(0) { /* We don't do this cause it would interfere with ODevice */ #if 0 qwsServer->setKeyboardFilter(this); #endif } void KeyFilter::timerEvent(QTimerEvent* e) { if ( e->timerId() == held_tid ) { killTimer(held_tid); // button held if ( heldButton ) { emit activate(heldButton, TRUE); heldButton = 0; } held_tid = 0; } } void KeyFilter::registerKey( const QCopKeyRegister& key ) { m_keys.insert( key.keyCode(), key ); } void KeyFilter::unregisterKey( const QCopKeyRegister& key ) { m_keys.remove( key.keyCode() ); } bool KeyFilter::keyRegistered( int key ) { /* * Check if we've a key registered */ if ( !m_keys[key].send()) return false; else return true; } bool KeyFilter::checkButtonAction(bool db, int keycode, int press, int autoRepeat) { if ( !loggedin // Permitted keys && keycode != Key_F34 // power && keycode != Key_F30 // select && keycode != Key_Enter && keycode != Key_Return && keycode != Key_Space && keycode != Key_Left && keycode != Key_Right && keycode != Key_Up && keycode != Key_Down ) return TRUE; /* check if it was registered */ if (!db ) { if (keycode != 0 &&press && !autoRepeat && keyRegistered(keycode) ) return true; }else { // First check to see if DeviceButtonManager knows something about this button: const Opie::ODeviceButton* button = Opie::ODevice::inst()->buttonForKeycode(keycode); if (button && !autoRepeat) { if ( held_tid ) { killTimer(held_tid); held_tid = 0; } if ( button->heldAction().isNull() ) { if ( press ) emit activate(button, FALSE); } else if ( press ) { heldButton = button; held_tid = startTimer( ODevice::inst ()->buttonHoldTime () ); } else if ( heldButton ) { heldButton = 0; emit activate(button, FALSE); } QWSServer::screenSaverActivate(FALSE); return TRUE; } return false; } if ( keycode == HardKey_Suspend ) { if ( press ) emit power(); return TRUE; } if ( keycode == HardKey_Backlight ) { if ( press ) emit backlight(); return TRUE; } if ( keycode == Key_F32 ) { #ifndef QT_NO_COP if ( press ) QCopEnvelope e( "QPE/Desktop", "startSync()" ); #endif return TRUE; } if ( keycode == Key_F31 ) { if ( press ) emit symbol(); QWSServer::screenSaverActivate(FALSE); return TRUE; } if ( keycode == Key_NumLock ) if ( press ) emit numLockStateToggle(); if ( keycode == Key_CapsLock ) if ( press ) emit capsLockStateToggle(); if ( serverApp ) serverApp->keyClick(keycode,press,autoRepeat); return FALSE; } enum MemState { MemUnknown, MemVeryLow, MemLow, MemNormal } memstate=MemUnknown; #if defined(QPE_HAVE_MEMALERTER) QPE_MEMALERTER_IMPL #endif //--------------------------------------------------------------------------- bool ServerApplication::doRestart = FALSE; bool ServerApplication::allowRestart = TRUE; bool ServerApplication::ms_is_starting = TRUE; void ServerApplication::switchLCD( bool on ) { if ( !qApp ) return; ServerApplication *dapp = ServerApplication::me() ; if ( !dapp-> m_screensaver ) return; if ( on ) { dapp-> m_screensaver-> setDisplayState ( true ); dapp-> m_screensaver-> setBacklight ( -3 ); }else dapp-> m_screensaver-> setDisplayState ( false ); } ServerApplication::ServerApplication( int& argc, char **argv, Type t ) : QPEApplication( argc, argv, t ) { ms_is_starting = true; // We know we'll have lots of cached pixmaps due to App/DocLnks QPixmapCache::setCacheLimit(512); m_ps = new PowerStatus; m_ps_last = new PowerStatus; pa = new DesktopPowerAlerter( 0 ); m_apm_timer = new QTimer( this ); connect(m_apm_timer, SIGNAL( timeout() ), this, SLOT( apmTimeout() ) ); reloadPowerWarnSettings(); QCopChannel *channel = new QCopChannel( "QPE/System", this ); - connect(channel, SIGNAL(received( const QCString&, const QByteArray& ) ), - this, SLOT(systemMessage(const QCString&, const QByteArray& ) ) ); + connect(channel, SIGNAL(received(const QCString&,const QByteArray&) ), + this, SLOT(systemMessage(const QCString&,const QByteArray&) ) ); channel = new QCopChannel("QPE/Launcher", this ); - connect(channel, SIGNAL(received( const QCString&, const QByteArray& ) ), - this, SLOT(launcherMessage( const QCString&, const QByteArray& ) ) ); + connect(channel, SIGNAL(received(const QCString&,const QByteArray&) ), + this, SLOT(launcherMessage(const QCString&,const QByteArray&) ) ); m_screensaver = new OpieScreenSaver(); m_screensaver->setInterval( -1 ); QWSServer::setScreenSaver( m_screensaver ); - connect( qApp, SIGNAL( volumeChanged( bool ) ), + connect( qApp, SIGNAL( volumeChanged(bool) ), this, SLOT( rereadVolumes() ) ); /* ### PluginLoader libqtopia SafeMode */ #if 0 if ( PluginLoader::inSafeMode() ) QTimer::singleShot(500, this, SLOT(showSafeMode()) ); QTimer::singleShot(20*1000, this, SLOT(clearSafeMode()) ); #endif kf = new KeyFilter(this); connect( kf, SIGNAL(launch()), this, SIGNAL(launch()) ); connect( kf, SIGNAL(power()), this, SIGNAL(power()) ); connect( kf, SIGNAL(backlight()), this, SIGNAL(backlight()) ); connect( kf, SIGNAL(symbol()), this, SIGNAL(symbol())); connect( kf, SIGNAL(numLockStateToggle()), this,SIGNAL(numLockStateToggle())); connect( kf, SIGNAL(capsLockStateToggle()), this,SIGNAL(capsLockStateToggle())); connect( kf, SIGNAL(activate(const Opie::ODeviceButton*,bool)), this,SIGNAL(activate(const Opie::ODeviceButton*,bool))); connect( kf, SIGNAL(backlight()), this, SLOT(toggleLight()) ); connect( this, SIGNAL(power() ), SLOT(togglePower() ) ); rereadVolumes(); serverApp = this; apmTimeout(); grabKeyboard(); /* make sure the event filter is installed */ const Opie::ODeviceButton* but = Opie::ODevice::inst()->buttonForKeycode( -1 ); } ServerApplication::~ServerApplication() { ungrabKeyboard(); delete pa; delete m_ps; delete m_ps_last; } void ServerApplication::apmTimeout() { serverApp-> checkMemory( ); // in case no events are generated *m_ps_last = *m_ps; *m_ps = PowerStatusManager::readStatus(); if ( m_ps->acStatus() != m_ps_last-> acStatus() ) m_screensaver-> powerStatusChanged( *m_ps ); if ( m_ps->acStatus() == PowerStatus::Online ) { return; } int bat = m_ps-> batteryPercentRemaining(); if ( bat < m_ps_last-> batteryPercentRemaining() ) { if ( bat <= m_powerCritical ) { QMessageBox battlow( tr("WARNING"), tr("<p>The battery level is critical!" "<p>Keep power off until AC is restored"), QMessageBox::Warning, QMessageBox::Cancel, QMessageBox::NoButton, QMessageBox::NoButton, 0, QString::null, TRUE, WStyle_StaysOnTop); battlow.setButtonText(QMessageBox::Cancel, tr("Ok")); battlow.exec(); } else if ( bat <= m_powerVeryLow ) pa->alert( tr( "The battery is running very low. "), 2 ); } if ( m_ps-> backupBatteryStatus() == PowerStatus::VeryLow ) { QMessageBox battlow( tr("WARNING"), tr("<p>The Back-up battery is very low" "<p>Please charge the back-up battery"), QMessageBox::Warning, QMessageBox::Cancel, QMessageBox::NoButton, QMessageBox::NoButton, 0, QString::null, TRUE, WStyle_StaysOnTop); battlow.setButtonText(QMessageBox::Cancel, tr("Ok")); battlow.exec(); } } void ServerApplication::systemMessage( const QCString& msg, const QByteArray& data ) { QDataStream stream ( data, IO_ReadOnly ); if ( msg == "setScreenSaverInterval(int)" ) { int time; stream >> time; m_screensaver-> setInterval( time ); } else if ( msg == "setScreenSaverIntervals(int,int,int)" ) { int t1, t2, t3; stream >> t1 >> t2 >> t3; m_screensaver-> setIntervals( t1, t2, t3 ); } else if ( msg == "setBacklight(int)" ) { int bright; stream >> bright; m_screensaver-> setBacklight( bright ); } else if ( msg == "setScreenSaverMode(int)" ) { int mode; stream >> mode; m_screensaver-> setMode ( mode ); } else if ( msg == "reloadPowerWarnSettings()" ) { reloadPowerWarnSettings(); } else if ( msg == "setDisplayState(int)" ) { int state; stream >> state; m_screensaver-> setDisplayState ( state != 0 ); } else if ( msg == "suspend()" ) { emit power(); } else if ( msg == "sendBusinessCard()" ) { QString card = ::getenv ( "HOME" ); card += "/Applications/addressbook/businesscard.vcf"; if ( QFile::exists( card ) ) { QCopEnvelope e ( "QPE/Obex", "send(QString,QString,QString)" ); QString mimetype = "text/x-vCard"; e << tr( "business card" ) << card << mimetype; } } } void ServerApplication::reloadPowerWarnSettings ( ) { Config cfg ( "apm" ); cfg. setGroup ( "Warnings" ); int iv = cfg. readNumEntry ( "checkinterval", 10000 ); m_apm_timer-> stop ( ); if ( iv ) m_apm_timer-> start ( iv ); m_powerVeryLow = cfg. readNumEntry ( "powerverylow", 10 ); m_powerCritical = cfg. readNumEntry ( "powervcritical", 5 ); } void ServerApplication::launcherMessage( const QCString & msg, const QByteArray & data ) { QDataStream stream ( data, IO_ReadOnly ); if ( msg == "deviceButton(int,int,int)" ) { int keycode, press, autoRepeat; stream >> keycode >> press >> autoRepeat; kf->checkButtonAction ( true, keycode, press, autoRepeat ); } else if ( msg == "keyRegister(int,QCString,QCString)" ) { int k; QCString c, m; stream >> k >> c >> m; kf -> registerKey( QCopKeyRegister(k, c, m) ); } } bool ServerApplication::screenLocked() { return loggedin == 0; } void ServerApplication::login(bool at_poweron) { if ( !loggedin ) { Global::terminateBuiltin("calibrate"); // No tr Password::authenticate(at_poweron); loggedin=1; #ifndef QT_NO_COP QCopEnvelope e( "QPE/Desktop", "unlocked()" ); #endif } } #if defined(QPE_HAVE_TOGGLELIGHT) #include <qtopia/config.h> diff --git a/core/launcher/shutdownimpl.cpp b/core/launcher/shutdownimpl.cpp index f43a2a3..2731568 100644 --- a/core/launcher/shutdownimpl.cpp +++ b/core/launcher/shutdownimpl.cpp @@ -1,173 +1,173 @@ /********************************************************************** ** Copyright (C) 2000 Trolltech AS. All rights reserved. ** ** This file is part of Qtopia Environment. ** ** This file may be distributed and/or modified under the terms of the ** GNU General Public License version 2 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. ** ** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE ** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. ** ** See http://www.trolltech.com/gpl/ for GPL licensing information. ** ** Contact info@trolltech.com if any conditions of this licensing are ** not clear to you. ** **********************************************************************/ #include "shutdownimpl.h" #include <qpe/global.h> #include <qpe/qcopenvelope_qws.h> #include <qtimer.h> #include <qprogressbar.h> #include <qpushbutton.h> #include <qbuttongroup.h> #include <qlabel.h> #include <qlayout.h> static void changeButtonColor ( QPushButton *btn, const QColor &col ) { QPalette pal = btn-> palette ( ); pal. setColor ( QPalette::Active, QColorGroup::Button, col ); pal. setColor ( QPalette::Disabled, QColorGroup::Button, col ); pal. setColor ( QPalette::Inactive, QColorGroup::Button, col ); btn-> setPalette ( pal ); } ShutdownImpl::ShutdownImpl( QWidget* parent, const char *name, WFlags fl ) : QWidget ( parent, name, fl ) { setCaption ( tr( "Shutdown..." ) ); QVBoxLayout *vbox = new QVBoxLayout ( this ); vbox-> setSpacing ( 3 ); vbox-> setMargin ( 6 ); QButtonGroup *btngrp = new QButtonGroup ( this ); btngrp-> setTitle ( tr( "Terminate" ) ); btngrp-> setColumnLayout ( 0, Qt::Vertical ); btngrp-> layout ( ) -> setSpacing ( 0 ); btngrp-> layout ( ) -> setMargin ( 0 ); QGridLayout *grid = new QGridLayout ( btngrp-> layout ( ) ); grid-> setAlignment ( Qt::AlignTop ); grid-> setSpacing ( 3 ); grid-> setMargin ( 7 ); QPushButton *quit = new QPushButton ( tr( "Terminate Opie" ), btngrp, "quit" ); changeButtonColor ( quit, QColor ( 236, 236, 179 ) ); btngrp-> insert ( quit, 4 ); grid-> addWidget ( quit, 1, 1 ); QPushButton *reboot = new QPushButton ( tr( "Reboot" ), btngrp, "reboot" ); changeButtonColor ( reboot, QColor( 236, 183, 181 ) ); btngrp-> insert ( reboot, 2 ); grid-> addWidget( reboot, 1, 0 ); QPushButton *restart = new QPushButton ( tr( "Restart Opie" ), btngrp, "restart" ); changeButtonColor ( restart, QColor( 236, 236, 179 ) ); btngrp-> insert ( restart, 3 ); grid-> addWidget ( restart, 0, 1 ); QPushButton *shutdown = new QPushButton( tr( "Shutdown" ), btngrp, "shutdown" ); changeButtonColor ( shutdown, QColor( 236, 183, 181 ) ); btngrp-> insert ( shutdown, 1 ); grid-> addWidget ( shutdown, 0, 0 ); vbox-> addWidget ( btngrp ); m_info = new QLabel ( this, "info" ); m_info-> setText( tr( "<p>\n" "These termination options are provided primarily for use while developing and testing the Opie system. In a normal environment, these concepts are unnecessary." ) ); vbox-> addWidget ( m_info ); m_progress = new QProgressBar ( this, "progressBar" ); m_progress-> setFrameShape ( QProgressBar::Panel ); m_progress-> setFrameShadow ( QProgressBar::Sunken ); m_progress-> setTotalSteps ( 20 ); m_progress-> setIndicatorFollowsStyle ( false ); vbox-> addWidget ( m_progress ); vbox-> addItem ( new QSpacerItem ( 20, 20, QSizePolicy::Minimum, QSizePolicy::Expanding ) ); QPushButton *cancel = new QPushButton ( tr( "Cancel" ), this, "cancel" ); changeButtonColor ( cancel, QColor( 181, 222, 178 ) ); cancel-> setDefault ( true ); cancel-> setSizePolicy ( QSizePolicy ( QSizePolicy::Minimum, QSizePolicy::Expanding, cancel-> sizePolicy ( ). hasHeightForWidth ( ) ) ); vbox-> addWidget ( cancel ); m_timer = new QTimer ( this ); - connect ( m_timer, SIGNAL( timeout ( ) ), this, SLOT( timeout ( ) ) ); + connect ( m_timer, SIGNAL( timeout() ), this, SLOT( timeout() ) ); - connect ( btngrp, SIGNAL( clicked ( int ) ), this, SLOT( buttonClicked ( int ) ) ); - connect ( cancel, SIGNAL( clicked ( ) ), this, SLOT( cancelClicked ( ) ) ); + connect ( btngrp, SIGNAL( clicked(int) ), this, SLOT( buttonClicked(int) ) ); + connect ( cancel, SIGNAL( clicked() ), this, SLOT( cancelClicked() ) ); m_progress-> hide ( ); Global::hideInputMethod ( ); } void ShutdownImpl::buttonClicked ( int b ) { m_counter = 0; switch ( b ) { case 1: m_operation = ShutdownSystem; break; case 2: m_operation = RebootSystem; break; case 3: m_operation = RestartDesktop; break; case 4: m_operation = TerminateDesktop; break; } m_info-> hide ( ); m_progress-> show ( ); m_timer-> start ( 300 ); timeout ( ); } void ShutdownImpl::cancelClicked ( ) { m_progress-> hide ( ); m_info-> show ( ); if ( m_timer-> isActive ( ) ) m_timer-> stop ( ); else close ( ); } void ShutdownImpl::timeout ( ) { if ( ( m_counter += 2 ) > m_progress-> totalSteps ( ) ) { m_progress-> hide ( ); m_timer-> stop ( ); emit shutdown ( m_operation ); } else m_progress-> setProgress ( m_counter ); } void ShutdownImpl::hide ( ) { if ( isVisible ( )) { // hack - shutdown is a launcher dialog, but treated like a standalone app QCopEnvelope e( "QPE/System", "closing(QString)" ); e << QString ( "shutdown" ); } QWidget::hide ( ); } diff --git a/core/launcher/taskbar.cpp b/core/launcher/taskbar.cpp index 491a8a3..91e2f20 100644 --- a/core/launcher/taskbar.cpp +++ b/core/launcher/taskbar.cpp @@ -24,354 +24,354 @@ #include "systray.h" #include "wait.h" #include "appicons.h" #include "taskbar.h" #include "server.h" #include <qtopia/config.h> #include <qtopia/qpeapplication.h> #ifdef QWS #include <qtopia/qcopenvelope_qws.h> #endif #include <qtopia/global.h> //#include <qtopia/custom.h> #include <qlabel.h> #include <qlayout.h> #include <qtimer.h> #ifdef QWS #include <qwindowsystem_qws.h> #endif #include <qwidgetstack.h> #if defined( Q_WS_QWS ) #include <qwsdisplay_qws.h> #include <qgfx_qws.h> #endif static bool initNumLock() { #ifdef QPE_INITIAL_NUMLOCK_STATE QPE_INITIAL_NUMLOCK_STATE #endif return FALSE; } //--------------------------------------------------------------------------- class SafeMode : public QWidget { Q_OBJECT public: SafeMode( QWidget *parent ) : QWidget( parent ), menu(0) { message = tr("Safe Mode"); QFont f( font() ); f.setWeight( QFont::Bold ); setFont( f ); } void mousePressEvent( QMouseEvent *); QSize sizeHint() const; void paintEvent( QPaintEvent* ); private slots: void action(int i); private: QString message; QPopupMenu *menu; }; void SafeMode::mousePressEvent( QMouseEvent *) { if ( !menu ) { menu = new QPopupMenu(this); menu->insertItem( tr("Plugin Manager..."), 0 ); menu->insertItem( tr("Restart Qtopia"), 1 ); menu->insertItem( tr("Help..."), 2 ); connect(menu, SIGNAL(activated(int)), this, SLOT(action(int))); } QPoint curPos = mapToGlobal( QPoint(0,0) ); QSize sh = menu->sizeHint(); menu->popup( curPos-QPoint((sh.width()-width())/2,sh.height()) ); } void SafeMode::action(int i) { switch (i) { case 0: Global::execute( "pluginmanager" ); break; case 1: Global::restart(); break; case 2: Global::execute( "helpbrowser", "safemode.html" ); break; } } QSize SafeMode::sizeHint() const { QFontMetrics fm = fontMetrics(); return QSize( fm.width(message), fm.height() ); } void SafeMode::paintEvent( QPaintEvent* ) { QPainter p(this); p.drawText( rect(), AlignCenter, message ); } //--------------------------------------------------------------------------- class LockKeyState : public QWidget { public: LockKeyState( QWidget *parent ) : QWidget(parent), nl(initNumLock()), cl(FALSE) { nl_pm = Resource::loadPixmap("numlock"); cl_pm = Resource::loadPixmap("capslock"); } QSize sizeHint() const { return QSize(nl_pm.width()+2,nl_pm.width()+nl_pm.height()+1); } void toggleNumLockState() { nl = !nl; repaint(); } void toggleCapsLockState() { cl = !cl; repaint(); } void paintEvent( QPaintEvent * ) { int y = (height()-sizeHint().height())/2; QPainter p(this); if ( nl ) p.drawPixmap(1,y,nl_pm); if ( cl ) p.drawPixmap(1,y+nl_pm.height()+1,cl_pm); } private: QPixmap nl_pm, cl_pm; bool nl, cl; }; //--------------------------------------------------------------------------- TaskBar::~TaskBar() { } TaskBar::TaskBar() : QHBox(0, 0, WStyle_Customize | WStyle_Tool | WStyle_StaysOnTop | WGroupLeader) { Config cfg( "Launcher" ); cfg.setGroup( "InputMethods" ); resizeRunningApp = cfg.readBoolEntry( "Resize", true ); sm = new StartMenu( this ); connect( sm, SIGNAL(tabSelected(const QString&)), this, SIGNAL(tabSelected(const QString&)) ); inputMethods = new InputMethods( this ); connect( inputMethods, SIGNAL(inputToggled(bool)), this, SLOT(calcMaxWindowRect()) ); stack = new QWidgetStack( this ); stack->setSizePolicy( QSizePolicy( QSizePolicy::Expanding, QSizePolicy::Minimum ) ); label = new QLabel(stack); runningAppBar = new RunningAppBar(stack); stack->raiseWidget(runningAppBar); waitIcon = new Wait( this ); (void) new AppIcons( this ); sysTray = new SysTray( this ); /* ### FIXME plugin loader and safe mode */ #if 0 if (PluginLoader::inSafeMode()) (void)new SafeMode( this ); #endif // ## make customizable in some way? #ifdef QT_QWS_CUSTOM lockState = new LockKeyState( this ); #else lockState = 0; #endif #if defined(Q_WS_QWS) #if !defined(QT_NO_COP) QCopChannel *channel = new QCopChannel( "QPE/TaskBar", this ); - connect( channel, SIGNAL(received(const QCString&, const QByteArray&)), - this, SLOT(receive(const QCString&, const QByteArray&)) ); + connect( channel, SIGNAL(received(const QCString&,const QByteArray&)), + this, SLOT(receive(const QCString&,const QByteArray&)) ); #endif #endif waitTimer = new QTimer( this ); connect( waitTimer, SIGNAL( timeout() ), this, SLOT( stopWait() ) ); clearer = new QTimer( this ); QObject::connect(clearer, SIGNAL(timeout()), SLOT(clearStatusBar())); connect( qApp, SIGNAL(symbol()), this, SLOT(toggleSymbolInput()) ); connect( qApp, SIGNAL(numLockStateToggle()), this, SLOT(toggleNumLockState()) ); connect( qApp, SIGNAL(capsLockStateToggle()), this, SLOT(toggleCapsLockState()) ); } void TaskBar::setStatusMessage( const QString &text ) { if ( !text.isEmpty() ) { label->setText( text ); stack->raiseWidget( label ); if ( sysTray && ( label->fontMetrics().width( text ) > label->width() ) ) sysTray->hide(); clearer->start( 3000, TRUE ); } else { clearStatusBar(); } } void TaskBar::clearStatusBar() { label->clear(); stack->raiseWidget(runningAppBar); if ( sysTray ) sysTray->show(); // stack->raiseWidget( mru ); } void TaskBar::startWait() { waitIcon->setWaiting( true ); // a catchall stop after 10 seconds... waitTimer->start( 10 * 1000, true ); } void TaskBar::stopWait(const QString&) { waitTimer->stop(); waitIcon->setWaiting( false ); } void TaskBar::stopWait() { waitTimer->stop(); waitIcon->setWaiting( false ); } /* * This resizeEvent will be captured by * the ServerInterface and it'll layout * and calc rect. Now if we go from bigger * to smaller screen the SysTray is out of * bounds and repaint() won't trigger an Event */ void TaskBar::resizeEvent( QResizeEvent *e ) { if ( sysTray ) sysTray->hide(); QHBox::resizeEvent( e ); if ( sysTray ) sysTray->show(); qWarning("TaskBar::resize event"); } void TaskBar::styleChange( QStyle &s ) { QHBox::styleChange( s ); calcMaxWindowRect(); } void TaskBar::calcMaxWindowRect() { if ( resizeRunningApp ) { #if defined(Q_WS_QWS) QRect wr; int displayWidth = qApp->desktop()->width(); QRect ir = inputMethods->inputRect(); if ( ir.isValid() ) { wr.setCoords( 0, 0, displayWidth-1, ir.top()-1 ); } else { wr.setCoords( 0, 0, displayWidth-1, y()-1 ); } #if QT_VERSION < 0x030000 QWSServer::setMaxWindowRect( qt_screen->mapToDevice(wr,QSize(qt_screen->width(),qt_screen->height())) ); #else QWSServer::setMaxWindowRect( wr ); #endif #endif } } void TaskBar::receive( const QCString &msg, const QByteArray &data ) { QDataStream stream( data, IO_ReadOnly ); if ( msg == "message(QString)" ) { QString text; stream >> text; setStatusMessage( text ); } else if ( msg == "hideInputMethod()" ) { inputMethods->hideInputMethod(); } else if ( msg == "showInputMethod()" ) { inputMethods->showInputMethod(); } else if ( msg == "showInputMethod(QString)" ) { QString name; stream >> name; inputMethods->showInputMethod(name); } else if ( msg == "reloadInputMethods()" ) { inputMethods->loadInputMethods(); } else if ( msg == "reloadApplets()" ) { sysTray->clearApplets(); sm->createMenu(); sysTray->addApplets(); }else if ( msg == "toggleMenu()" ) { if ( sm-> launchMenu-> isVisible() ) sm-> launch(); else QCopEnvelope e( "QPE/System", "toggleApplicationMenu()" ); }else if ( msg == "toggleStartMenu()" ) sm->launch(); } void TaskBar::setApplicationState( const QString &name, ServerInterface::ApplicationState state ) { if ( state == ServerInterface::Launching ) runningAppBar->applicationLaunched( name ); else if ( state == ServerInterface::Terminated ) runningAppBar->applicationTerminated( name ); } void TaskBar::toggleNumLockState() { if ( lockState ) lockState->toggleNumLockState(); } void TaskBar::toggleCapsLockState() { if ( lockState ) lockState->toggleCapsLockState(); } void TaskBar::toggleSymbolInput() { QString unicodeInput = qApp->translate( "InputMethods", "Unicode" ); if ( inputMethods->currentShown() == unicodeInput ) { inputMethods->hideInputMethod(); } else { inputMethods->showInputMethod( unicodeInput ); } } #include "taskbar.moc" diff --git a/core/launcher/transferserver.cpp b/core/launcher/transferserver.cpp index b998e95..a5e20b2 100644 --- a/core/launcher/transferserver.cpp +++ b/core/launcher/transferserver.cpp @@ -1,540 +1,540 @@ /********************************************************************** ** Copyright (C) 2000-2002 Trolltech AS. All rights reserved. ** ** This file is part of the Qtopia Environment. ** ** This file may be distributed and/or modified under the terms of the ** GNU General Public License version 2 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. ** ** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE ** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. ** ** See http://www.trolltech.com/gpl/ for GPL licensing information. ** ** Contact info@trolltech.com if any conditions of this licensing are ** not clear to you. ** **********************************************************************/ //#define _XOPEN_SOURCE #include <opie2/oglobal.h> #ifndef Q_OS_WIN32 #include <pwd.h> #include <sys/types.h> #include <unistd.h> #include <stdlib.h> #include <time.h> #ifndef Q_OS_MACX #include <shadow.h> #include <crypt.h> #endif /* Q_OS_MACX */ #else #include <stdlib.h> #include <time.h> #endif #if defined(_OS_LINUX_) #include <shadow.h> #endif #include <qtextstream.h> #include <qmessagebox.h> //#include <qtopia/qcopchannel_qws.h> #include <qtopia/process.h> #include <qtopia/private/contact.h> #include <qtopia/version.h> #ifdef Q_WS_QWS #include <qtopia/qcopenvelope_qws.h> #endif #include "transferserver.h" #include <qtopia/qprocess.h> const int block_size = 51200; TransferServer::TransferServer( Q_UINT16 port, QObject *parent, const char* name) : QServerSocket( port, 1, parent, name ) { connections.setAutoDelete( TRUE ); if ( !ok() ) qWarning( "Failed to bind to port %d", port ); } void TransferServer::authorizeConnections() { QListIterator<ServerPI> it(connections); while ( it.current() ) { if ( !it.current()->verifyAuthorised() ) { - disconnect( it.current(), SIGNAL(connectionClosed(ServerPI *)), this, SLOT( closed(ServerPI *)) ); + disconnect( it.current(), SIGNAL(connectionClosed(ServerPI*)), this, SLOT( closed(ServerPI*)) ); connections.removeRef( it.current() ); } else ++it; } } void TransferServer::closed(ServerPI *item) { connections.removeRef(item); } TransferServer::~TransferServer() { } void TransferServer::newConnection( int socket ) { ServerPI *ptr = new ServerPI( socket, this ); - connect( ptr, SIGNAL(connectionClosed(ServerPI *)), this, SLOT( closed(ServerPI *)) ); + connect( ptr, SIGNAL(connectionClosed(ServerPI*)), this, SLOT( closed(ServerPI*)) ); connections.append( ptr ); } QString SyncAuthentication::serverId() { Config cfg("Security"); cfg.setGroup("Sync"); QString r = cfg.readEntry("serverid"); if ( r.isEmpty() ) { r = OGlobal::generateUuid(); cfg.writeEntry("serverid", r ); } return r; } QString SyncAuthentication::ownerName() { QString vfilename = Global::applicationFileName("addressbook", "businesscard.vcf"); if (QFile::exists(vfilename)) { Contact c; c = Contact::readVCard( vfilename )[0]; return c.fullName(); } return QString::null; } QString SyncAuthentication::loginName() { struct passwd *pw = 0L; #ifndef Q_OS_WIN32 pw = getpwuid( geteuid() ); return QString::fromLocal8Bit( pw->pw_name ); #else //### revise return QString(); #endif } int SyncAuthentication::isAuthorized(QHostAddress peeraddress) { Config cfg("Security"); cfg.setGroup("Sync"); // QString allowedstr = cfg.readEntry("auth_peer","192.168.1.0"); uint auth_peer = cfg.readNumEntry("auth_peer", 0xc0a80100); // QHostAddress allowed; // allowed.setAddress(allowedstr); // uint auth_peer = allowed.ip4Addr(); uint auth_peer_bits = cfg.readNumEntry("auth_peer_bits", 24); uint mask = auth_peer_bits >= 32 // shifting by 32 is not defined ? 0xffffffff : (((1 << auth_peer_bits) - 1) << (32 - auth_peer_bits)); return (peeraddress.ip4Addr() & mask) == auth_peer; } bool SyncAuthentication::checkUser( const QString& user ) { if ( user.isEmpty() ) return FALSE; QString euser = loginName(); return user == euser; } bool SyncAuthentication::checkPassword( const QString& password ) { #ifdef ALLOW_UNIX_USER_FTP // First, check system password... struct passwd *pw = 0; struct spwd *spw = 0; pw = getpwuid( geteuid() ); spw = getspnam( pw->pw_name ); QString cpwd = QString::fromLocal8Bit( pw->pw_passwd ); if ( cpwd == "x" && spw ) cpwd = QString::fromLocal8Bit( spw->sp_pwdp ); // Note: some systems use more than crypt for passwords. QString cpassword = QString::fromLocal8Bit( crypt( password.local8Bit(), cpwd.local8Bit() ) ); if ( cpwd == cpassword ) return TRUE; #endif static int lastdenial=0; static int denials=0; int now = time(0); Config cfg("Security"); cfg.setGroup("SyncMode"); int mode = cfg.readNumEntry("Mode", 0x02 ); //No pass word needed if the user really needs it if (mode & 0x04) { QMessageBox unauth( tr("Sync Connection"), tr("<qt><p>An unauthorized system is requesting access to this device." "<p>You chose IntelliSync so you may I allow or deny this connection.</qt>" ), QMessageBox::Warning, QMessageBox::Ok, QMessageBox::Cancel|QMessageBox::Default, QMessageBox::NoButton, 0, QString::null, TRUE, WStyle_StaysOnTop); unauth.setButtonText(QMessageBox::Ok, tr("Allow" ) ); unauth.setButtonText(QMessageBox::Cancel, tr("Deny")); switch( unauth.exec() ) { case QMessageBox::Ok: return TRUE; break; case QMessageBox::Cancel: default: denials++; lastdenial=now; return FALSE; } } // Detect old Qtopia Desktop (no password) and fail if ( password.isEmpty() ) { if ( denials < 3 || now > lastdenial+600 ) { QMessageBox unauth( tr("Sync Connection"), tr("<p>An unauthorized system is requesting access to this device." "<p>If you are using a version of Qtopia Desktop older than 1.5.1, " "please upgrade or change the security setting to use IntelliSync." ), QMessageBox::Warning, QMessageBox::Cancel, QMessageBox::NoButton, QMessageBox::NoButton, 0, QString::null, TRUE, WStyle_StaysOnTop); unauth.setButtonText(QMessageBox::Cancel, tr("Deny")); unauth.exec(); denials++; lastdenial=now; } return FALSE; } // Second, check sync password... static int lock=0; if ( lock ) return FALSE; ++lock; /* * we need to support old Sync software and QtopiaDesktop */ if ( password.left(6) == "Qtopia" || password.left(6) == "rootme" ) { Config cfg( "Security" ); cfg.setGroup("Sync"); QStringList pwds = cfg.readListEntry("Passwords",' '); for (QStringList::ConstIterator it=pwds.begin(); it!=pwds.end(); ++it) { #ifndef Q_OS_WIN32 QString cpassword = QString::fromLocal8Bit( crypt( password.mid(8).local8Bit(), (*it).left(2).latin1() ) ); #else // ### revise QString cpassword(""); #endif if ( *it == cpassword ) { lock--; return TRUE; } } // Unrecognized system. Be careful... QMessageBox unrecbox( tr("Sync Connection"), tr( "<p>An unrecognized system is requesting access to this device." "<p>If you have just initiated a Sync for the first time, this is normal."), QMessageBox::Warning, QMessageBox::Cancel, QMessageBox::Yes, QMessageBox::NoButton, 0, QString::null, TRUE, WStyle_StaysOnTop); unrecbox.setButtonText(QMessageBox::Cancel, tr("Deny")); unrecbox.setButtonText(QMessageBox::Yes, tr("Allow")); if ( (denials > 2 && now < lastdenial+600) || unrecbox.exec() != QMessageBox::Yes) { denials++; lastdenial=now; lock--; return FALSE; } else { const char salty[]="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789/."; char salt[2]; salt[0]= salty[rand() % (sizeof(salty)-1)]; salt[1]= salty[rand() % (sizeof(salty)-1)]; #ifndef Q_OS_WIN32 QString cpassword = QString::fromLocal8Bit( crypt( password.mid(8).local8Bit(), salt ) ); #else //### revise QString cpassword(""); #endif denials=0; pwds.prepend(cpassword); cfg.writeEntry("Passwords",pwds,' '); lock--; return TRUE; } } lock--; return FALSE; } ServerPI::ServerPI( int socket, QObject *parent, const char* name ) : QSocket( parent, name ) , dtp( 0 ), serversocket( 0 ), waitsocket( 0 ), storFileSize(-1) { state = Connected; setSocket( socket ); peerport = peerPort(); peeraddress = peerAddress(); #ifndef INSECURE if ( !SyncAuthentication::isAuthorized(peeraddress) ) { state = Forbidden; startTimer( 0 ); } else #endif { connect( this, SIGNAL( readyRead() ), SLOT( read() ) ); connect( this, SIGNAL( connectionClosed() ), SLOT( connectionClosed() ) ); passiv = FALSE; for( int i = 0; i < 4; i++ ) wait[i] = FALSE; send( "220 Qtopia " QPE_VERSION " FTP Server" ); // No tr state = Wait_USER; dtp = new ServerDTP( this ); connect( dtp, SIGNAL( completed() ), SLOT( dtpCompleted() ) ); connect( dtp, SIGNAL( failed() ), SLOT( dtpFailed() ) ); - connect( dtp, SIGNAL( error( int ) ), SLOT( dtpError( int ) ) ); + connect( dtp, SIGNAL( error(int) ), SLOT( dtpError(int) ) ); directory = QDir::currentDirPath(); static int p = 1024; while ( !serversocket || !serversocket->ok() ) { delete serversocket; serversocket = new ServerSocket( ++p, this ); } - connect( serversocket, SIGNAL( newIncomming( int ) ), - SLOT( newConnection( int ) ) ); + connect( serversocket, SIGNAL( newIncomming(int) ), + SLOT( newConnection(int) ) ); } } ServerPI::~ServerPI() { close(); if ( dtp ) dtp->close(); delete dtp; delete serversocket; } bool ServerPI::verifyAuthorised() { if ( !SyncAuthentication::isAuthorized(peerAddress()) ) { state = Forbidden; return FALSE; } return TRUE; } void ServerPI::connectionClosed() { // qDebug( "Debug: Connection closed" ); emit connectionClosed(this); } void ServerPI::send( const QString& msg ) { QTextStream os( this ); os << msg << endl; //qDebug( "Reply: %s", msg.latin1() ); } void ServerPI::read() { while ( canReadLine() ) process( readLine().stripWhiteSpace() ); } bool ServerPI::checkReadFile( const QString& file ) { QString filename; if ( file[0] != "/" ) filename = directory.path() + "/" + file; else filename = file; QFileInfo fi( filename ); return ( fi.exists() && fi.isReadable() ); } bool ServerPI::checkWriteFile( const QString& file ) { QString filename; if ( file[0] != "/" ) filename = directory.path() + "/" + file; else filename = file; QFileInfo fi( filename ); if ( fi.exists() ) if ( !QFile( filename ).remove() ) return FALSE; return TRUE; } void ServerPI::process( const QString& message ) { //qDebug( "Command: %s", message.latin1() ); // split message using "," as separator QStringList msg = QStringList::split( " ", message ); if ( msg.isEmpty() ) return; // command token QString cmd = msg[0].upper(); // argument token QString arg; if ( msg.count() >= 2 ) arg = msg[1]; // full argument string QString args; if ( msg.count() >= 2 ) { QStringList copy( msg ); // FIXME: for Qt3 // copy.pop_front() copy.remove( copy.begin() ); args = copy.join( " " ); } //qDebug( "args: %s", args.latin1() ); // we always respond to QUIT, regardless of state if ( cmd == "QUIT" ) { send( "211 Good bye!" ); // No tr close(); return; } // connected to client if ( Connected == state ) return; // waiting for user name if ( Wait_USER == state ) { if ( cmd != "USER" || msg.count() < 2 || !SyncAuthentication::checkUser( arg ) ) { send( "530 Please login with USER and PASS" ); // No tr return; } send( "331 User name ok, need password" ); // No tr state = Wait_PASS; return; } // waiting for password if ( Wait_PASS == state ) { if ( cmd != "PASS" || !SyncAuthentication::checkPassword( arg ) ) { send( "530 Please login with USER and PASS" ); // No tr return; } send( "230 User logged in, proceed" ); // No tr state = Ready; return; } // ACCESS CONTROL COMMANDS // Only an ALLO sent immediately before STOR is valid. if ( cmd != "STOR" ) storFileSize = -1; // account (ACCT) if ( cmd == "ACCT" ) { // even wu-ftp does not support it send( "502 Command not implemented" ); // No tr } // change working directory (CWD) else if ( cmd == "CWD" ) { if ( !args.isEmpty() ) { if ( directory.cd( args, TRUE ) ) send( "250 Requested file action okay, completed" ); // No tr else send( "550 Requested action not taken" ); // No tr } else send( "500 Syntax error, command unrecognized" ); // No tr } // change to parent directory (CDUP) else if ( cmd == "CDUP" ) { if ( directory.cdUp() ) send( "250 Requested file action okay, completed" ); // No tr else send( "550 Requested action not taken" ); // No tr } // structure mount (SMNT) else if ( cmd == "SMNT" ) { // even wu-ftp does not support it send( "502 Command not implemented" ); // No tr } // reinitialize (REIN) else if ( cmd == "REIN" ) { // even wu-ftp does not support it send( "502 Command not implemented" ); // No tr } // TRANSFER PARAMETER COMMANDS // data port (PORT) else if ( cmd == "PORT" ) { if ( parsePort( arg ) ) send( "200 Command okay" ); // No tr else send( "500 Syntax error, command unrecognized" ); // No tr } // passive (PASV) @@ -897,385 +897,385 @@ bool ServerPI::sendList( const QString& arg ) } // return directory listing else if ( fi.isDir() ) { QDir dir( fn ); const QFileInfoList *list = dir.entryInfoList( QDir::All | QDir::Hidden ); QFileInfoListIterator it( *list ); QFileInfo *info; unsigned long total = 0; while ( ( info = it.current() ) ) { if ( info->fileName() != "." && info->fileName() != ".." ) total += info->size(); ++it; } ts << "total " << QString::number( total / 1024 ) << endl; // No tr it.toFirst(); while ( ( info = it.current() ) ) { if ( info->fileName() == "." || info->fileName() == ".." ) { ++it; continue; } ts << fileListing( info ) << endl; ++it; } } if ( passiv ) { waitarray = buffer.buffer(); wait[SendByteArray] = TRUE; if ( waitsocket ) newConnection( waitsocket ); } else dtp->sendByteArray( buffer.buffer(), peeraddress, peerport ); return TRUE; } QString ServerPI::fileListing( QFileInfo *info ) { if ( !info ) return QString::null; QString s; // type char if ( info->isDir() ) s += "d"; else if ( info->isSymLink() ) s += "l"; else s += "-"; // permisson string s += permissionString( info ) + " "; // number of hardlinks int subdirs = 1; if ( info->isDir() ) subdirs = 2; // FIXME : this is to slow //if ( info->isDir() ) //subdirs = QDir( info->absFilePath() ).entryList( QDir::Dirs ).count(); s += QString::number( subdirs ).rightJustify( 3, ' ', TRUE ) + " "; // owner QString o = info->owner(); if ( o.isEmpty() ) o = QString::number(info->ownerId()); s += o.leftJustify( 8, ' ', TRUE ) + " "; // group QString g = info->group(); if ( g.isEmpty() ) g = QString::number(info->groupId()); s += g.leftJustify( 8, ' ', TRUE ) + " "; // file size in bytes s += QString::number( info->size() ).rightJustify( 9, ' ', TRUE ) + " "; // last modified date QDate date = info->lastModified().date(); QTime time = info->lastModified().time(); s += date.monthName( date.month() ) + " " + QString::number( date.day() ).rightJustify( 2, ' ', TRUE ) + " " + QString::number( time.hour() ).rightJustify( 2, '0', TRUE ) + ":" + QString::number( time.minute() ).rightJustify( 2,'0', TRUE ) + " "; // file name s += info->fileName(); return s; } QString ServerPI::permissionString( QFileInfo *info ) { if ( !info ) return QString( "---------" ); QString s; // user if ( info->permission( QFileInfo::ReadUser ) ) s += "r"; else s += "-"; if ( info->permission( QFileInfo::WriteUser ) ) s += "w"; else s += "-"; if ( info->permission( QFileInfo::ExeUser ) ) s += "x"; else s += "-"; // group if ( info->permission( QFileInfo::ReadGroup ) ) s += "r"; else s += "-"; if ( info->permission( QFileInfo::WriteGroup ) )s += "w"; else s += "-"; if ( info->permission( QFileInfo::ExeGroup ) ) s += "x"; else s += "-"; // exec if ( info->permission( QFileInfo::ReadOther ) ) s += "r"; else s += "-"; if ( info->permission( QFileInfo::WriteOther ) ) s += "w"; else s += "-"; if ( info->permission( QFileInfo::ExeOther ) ) s += "x"; else s += "-"; return s; } void ServerPI::newConnection( int socket ) { //qDebug( "New incomming connection" ); if ( !passiv ) return; if ( wait[SendFile] ) { QStringList targets; if ( backupRestoreGzip( waitfile, targets ) ) dtp->sendGzipFile( waitfile, targets ); else dtp->sendFile( waitfile ); dtp->setSocket( socket ); } else if ( wait[RetrieveFile] ) { qDebug("check retrieve file"); if ( backupRestoreGzip( waitfile ) ) dtp->retrieveGzipFile( waitfile ); else dtp->retrieveFile( waitfile, storFileSize ); dtp->setSocket( socket ); } else if ( wait[SendByteArray] ) { dtp->sendByteArray( waitarray ); dtp->setSocket( socket ); } else if ( wait[RetrieveByteArray] ) { qDebug("retrieve byte array"); dtp->retrieveByteArray(); dtp->setSocket( socket ); } else waitsocket = socket; for( int i = 0; i < 4; i++ ) wait[i] = FALSE; } QString ServerPI::absFilePath( const QString& file ) { if ( file.isEmpty() ) return file; QString filepath( file ); if ( file[0] != "/" ) filepath = directory.path() + "/" + file; return filepath; } void ServerPI::timerEvent( QTimerEvent * ) { connectionClosed(); } ServerDTP::ServerDTP( QObject *parent, const char* name) : QSocket( parent, name ), mode( Idle ), createTargzProc( 0 ), retrieveTargzProc( 0 ) { connect( this, SIGNAL( connected() ), SLOT( connected() ) ); connect( this, SIGNAL( connectionClosed() ), SLOT( connectionClosed() ) ); - connect( this, SIGNAL( bytesWritten( int ) ), SLOT( bytesWritten( int ) ) ); + connect( this, SIGNAL( bytesWritten(int) ), SLOT( bytesWritten(int) ) ); connect( this, SIGNAL( readyRead() ), SLOT( readyRead() ) ); createTargzProc = new QProcess( QString("tar"), this, "createTargzProc"); // No tr createTargzProc->setCommunication( QProcess::Stdout ); createTargzProc->setWorkingDirectory( QDir::rootDirPath() ); connect( createTargzProc, SIGNAL( processExited() ), SLOT( targzDone() ) ); retrieveTargzProc = new QProcess( this, "retrieveTargzProc" ); retrieveTargzProc->setCommunication( QProcess::Stdin ); retrieveTargzProc->setWorkingDirectory( QDir::rootDirPath() ); connect( retrieveTargzProc, SIGNAL( processExited() ), SIGNAL( completed() ) ); connect( retrieveTargzProc, SIGNAL( processExited() ), SLOT( extractTarDone() ) ); } ServerDTP::~ServerDTP() { buf.close(); if ( RetrieveFile == mode && file.isOpen() ) { // We're being shutdown before the client closed. file.close(); if ( recvFileSize >= 0 && (int)file.size() != recvFileSize ) { qDebug( "STOR incomplete" ); file.remove(); } } else { file.close(); } createTargzProc->kill(); } void ServerDTP::extractTarDone() { qDebug("extract done"); #ifndef QT_NO_COP QCopEnvelope e( "QPE/System", "restoreDone(QString)" ); e << file.name(); #endif } void ServerDTP::connected() { // send file mode switch ( mode ) { case SendFile : if ( !file.exists() || !file.open( IO_ReadOnly) ) { emit failed(); mode = Idle; return; } //qDebug( "Debug: Sending file '%s'", file.name().latin1() ); bytes_written = 0; if ( file.size() == 0 ) { //make sure it doesn't hang on empty files file.close(); emit completed(); mode = Idle; } else { // Don't write more if there is plenty buffered already. if ( bytesToWrite() <= block_size && !file.atEnd() ) { QCString s; s.resize( block_size ); int bytes = file.readBlock( s.data(), block_size ); writeBlock( s.data(), bytes ); } } break; case SendGzipFile: if ( createTargzProc->isRunning() ) { // SHOULDN'T GET HERE, BUT DOING A SAFETY CHECK ANYWAY qWarning("Previous tar --gzip process is still running; killing it..."); createTargzProc->kill(); } bytes_written = 0; qDebug("==>start send tar process"); if ( !createTargzProc->start() ) qWarning("Error starting %s", createTargzProc->arguments().join(" ").latin1()); break; case SendBuffer: if ( !buf.open( IO_ReadOnly) ) { emit failed(); mode = Idle; return; } // qDebug( "Debug: Sending byte array" ); bytes_written = 0; while( !buf.atEnd() ) putch( buf.getch() ); buf.close(); break; case RetrieveFile: // retrieve file mode if ( file.exists() && !file.remove() ) { emit failed(); mode = Idle; return; } if ( !file.open( IO_WriteOnly) ) { emit failed(); mode = Idle; return; } // qDebug( "Debug: Retrieving file %s", file.name().latin1() ); break; case RetrieveGzipFile: qDebug("=-> starting tar process to receive .tgz file"); break; case RetrieveBuffer: // retrieve buffer mode if ( !buf.open( IO_WriteOnly) ) { emit failed(); mode = Idle; return; } // qDebug( "Debug: Retrieving byte array" ); break; case Idle: qDebug("connection established but mode set to Idle; BUG!"); break; } } void ServerDTP::connectionClosed() { //qDebug( "Debug: Data connection closed %ld bytes written", bytes_written ); // send file mode if ( SendFile == mode ) { if ( bytes_written == file.size() ) emit completed(); else emit failed(); } // send buffer mode else if ( SendBuffer == mode ) { if ( bytes_written == buf.size() ) emit completed(); else emit failed(); } // retrieve file mode else if ( RetrieveFile == mode ) { file.close(); if ( recvFileSize >= 0 && (int)file.size() != recvFileSize ) { qDebug( "STOR incomplete" ); file.remove(); emit failed(); } else { emit completed(); } } else if ( RetrieveGzipFile == mode ) { qDebug("Done writing ungzip file; closing input"); retrieveTargzProc->flushStdin(); retrieveTargzProc->closeStdin(); } // retrieve buffer mode else if ( RetrieveBuffer == mode ) { buf.close(); emit completed(); } mode = Idle; } void ServerDTP::bytesWritten( int bytes ) { bytes_written += bytes; // send file mode if ( SendFile == mode ) { if ( bytes_written == file.size() ) { // qDebug( "Debug: Sending complete: %d bytes", file.size() ); file.close(); emit completed(); mode = Idle; } else if( !file.atEnd() ) { QCString s; s.resize( block_size ); diff --git a/core/multimedia/opieplayer/loopcontrol.cpp b/core/multimedia/opieplayer/loopcontrol.cpp index 82242a3..4ed5921 100644 --- a/core/multimedia/opieplayer/loopcontrol.cpp +++ b/core/multimedia/opieplayer/loopcontrol.cpp @@ -252,234 +252,234 @@ void LoopControl::startAudio() { if( mediaPlayerState->isStreaming == FALSE) audioSampleCounter = currentSample + samplesRead - 1; moreAudio = readOk && (audioSampleCounter <= total_audio_samples); } else { moreAudio = FALSE; } } audioMutex->unlock(); } void LoopControl::killTimers() { audioMutex->lock(); if ( hasVideoChannel ) killTimer( videoId ); killTimer( sliderId ); threadOkToGo = FALSE; audioMutex->unlock(); } void LoopControl::startTimers() { audioMutex->lock(); moreVideo = FALSE; moreAudio = FALSE; if ( hasVideoChannel ) { moreVideo = TRUE; int mSecsBetweenFrames = (int)(100 / framerate); // 10% of the real value videoId = startTimer( mSecsBetweenFrames ); } if ( hasAudioChannel ) { moreAudio = TRUE; threadOkToGo = TRUE; } sliderId = startTimer( 300 ); // update slider every 1/3 second audioMutex->unlock(); } void LoopControl::setPaused( bool pause ) { if ( !mediaPlayerState->curDecoder() || !mediaPlayerState->curDecoder()->isOpen() ) return; if ( pause ) { killTimers(); } else { // Force an update of the position mediaPlayerState->setPosition( mediaPlayerState->position() + 1 ); mediaPlayerState->setPosition( mediaPlayerState->position() - 1 ); // Just like we never stopped startTimers(); } } void LoopControl::stop( bool willPlayAgainShortly ) { #if defined(Q_WS_QWS) && !defined(QT_NO_COP) if ( !willPlayAgainShortly && disabledSuspendScreenSaver ) { disabledSuspendScreenSaver = FALSE; // Re-enable the suspend mode QCopEnvelope("QPE/System", "setScreenSaverMode(int)" ) << QPEApplication::Enable; } #endif if ( mediaPlayerState->curDecoder() && mediaPlayerState->curDecoder()->isOpen() ) { killTimers(); audioMutex->lock(); mediaPlayerState->curDecoder()->close(); if ( audioDevice ) { delete audioDevice; delete audioBuffer; audioDevice = 0; audioBuffer = 0; } audioMutex->unlock(); } audioSampleCounter=0; current_frame=0; total_audio_samples=0; } bool LoopControl::init( const QString& filename ) { stop(); audioMutex->lock(); fileName = filename; stream = 0; // only play stream 0 for now current_frame = total_video_frames = total_audio_samples = 0; // qDebug( "Using the %s decoder", mediaPlayerState->curDecoder()->pluginName() ); // ### Hack to use libmpeg3plugin to get the number of audio samples if we are using the libmad plugin // if ( mediaPlayerState->curDecoder()->pluginName() == QString("LibMadPlugin") ) { // if ( mediaPlayerState->libMpeg3Decoder() && mediaPlayerState->libMpeg3Decoder()->open( filename )) { // total_audio_samples = mediaPlayerState->libMpeg3Decoder()->audioSamples( 0 ); // mediaPlayerState->libMpeg3Decoder()->close(); // } // } if ( !mediaPlayerState->curDecoder()|| !mediaPlayerState->curDecoder()->open( filename ) ) { audioMutex->unlock(); return FALSE; } hasAudioChannel = mediaPlayerState->curDecoder()->audioStreams() > 0; hasVideoChannel = mediaPlayerState->curDecoder()->videoStreams() > 0; if ( hasAudioChannel ) { int astream = 0; if ( mediaPlayerState->curDecoder()->pluginName() == QString("LibMpeg3Plugin") ) channels = 2; //dont akx me why, but it needs this hack else channels = mediaPlayerState->curDecoder()->audioChannels( astream ); // qDebug( "LC- channels = %d", channels ); // if ( !total_audio_samples ) total_audio_samples = mediaPlayerState->curDecoder()->audioSamples( astream ); total_audio_samples += 1000; // qDebug("total samples %d", total_audio_samples); mediaPlayerState->setLength( total_audio_samples ); freq = mediaPlayerState->curDecoder()->audioFrequency( astream ); // qDebug( "LC- frequency = %d", freq ); audioSampleCounter = 0; int bits_per_sample; if ( mediaPlayerState->curDecoder()->pluginName() == QString("LibWavPlugin") ) { bits_per_sample =(int) mediaPlayerState->curDecoder()->getTime(); // qDebug("using stupid hack"); } else { bits_per_sample=0; } audioDevice = new AudioDevice( freq, channels, bits_per_sample); audioBuffer = new char[ audioDevice->bufferSize() ]; channels = audioDevice->channels(); //### must check which frequency is actually used. static const int size = 1; short int buf[size]; long samplesRead = 0; mediaPlayerState->curDecoder()->audioReadSamples( buf, channels, size, samplesRead, stream ); } if ( hasVideoChannel ) { total_video_frames = mediaPlayerState->curDecoder()->videoFrames( stream ); mediaPlayerState->setLength( total_video_frames ); framerate = mediaPlayerState->curDecoder()->videoFrameRate( stream ); DecodeLoopDebug(( "Frame rate %g total %ld", framerate, total_video_frames )); if ( framerate <= 1.0 ) { DecodeLoopDebug(( "Crazy frame rate, resetting to sensible" )); framerate = 25; } if ( total_video_frames == 1 ) { DecodeLoopDebug(( "Cannot seek to frame" )); } } current_frame = 0; prev_frame = -1; - connect( mediaPlayerState, SIGNAL( positionChanged( long ) ), this, SLOT( setPosition( long ) ) ); - connect( mediaPlayerState, SIGNAL( pausedToggled( bool ) ), this, SLOT( setPaused( bool ) ) ); + connect( mediaPlayerState, SIGNAL( positionChanged(long) ), this, SLOT( setPosition(long) ) ); + connect( mediaPlayerState, SIGNAL( pausedToggled(bool) ), this, SLOT( setPaused(bool) ) ); audioMutex->unlock(); return TRUE; } void LoopControl::play() { // qDebug("LC- play"); mediaPlayerState->setPosition( 0); //uglyhack #if defined(Q_WS_QWS) && !defined(QT_NO_COP) if ( !disabledSuspendScreenSaver || previousSuspendMode != hasVideoChannel ) { disabledSuspendScreenSaver = TRUE; previousSuspendMode = hasVideoChannel; // Stop the screen from blanking and power saving state QCopEnvelope("QPE/System", "setScreenSaverMode(int)" ) << ( hasVideoChannel ? QPEApplication::Disable : QPEApplication::DisableSuspend ); } #endif playtime.start(); startTimers(); } void LoopControl::setMute( bool on ) { if ( on != isMuted ) { isMuted = on; if ( !on ) { // Force an update of the position mediaPlayerState->setPosition( mediaPlayerState->position() + 1 ); mediaPlayerState->setPosition( mediaPlayerState->position() - 1 ); // Resume playing audio moreAudio = TRUE; } } } diff --git a/core/multimedia/opieplayer/loopcontrol_threaded.cpp b/core/multimedia/opieplayer/loopcontrol_threaded.cpp index 3796549..0a1fc17 100644 --- a/core/multimedia/opieplayer/loopcontrol_threaded.cpp +++ b/core/multimedia/opieplayer/loopcontrol_threaded.cpp @@ -392,233 +392,233 @@ void LoopControl::startAudio() { moreAudio = audioSampleCounter <= total_audio_samples; } else { if ( mediaPlayerState->curDecoder() && hasAudioChannel ) usleep( 100000 ); // Check every 1/10 sec to see if mute is off else moreAudio = FALSE; } } // qDebug( "End of file" ); if ( !moreVideo && !moreAudio ) emitPlayFinished = TRUE; pthread_exit(NULL); } void LoopControl::killTimers() { if ( hasVideoChannel ) { if ( pthread_self() != video_tid ) { if ( pthread_cancel(video_tid) == 0 ) { void *thread_result = 0; if ( pthread_join(video_tid,&thread_result) != 0 ) // qDebug("thread join error 1"); pthread_attr_destroy(&video_attr); } } } if ( hasAudioChannel ) { if ( pthread_self() != audio_tid ) { if ( pthread_cancel(audio_tid) == 0 ) { void *thread_result = 0; if ( pthread_join(audio_tid,&thread_result) != 0 ) // qDebug("thread join error 2"); pthread_attr_destroy(&audio_attr); } } } } void LoopControl::startTimers() { moreVideo = FALSE; moreAudio = FALSE; if ( hasVideoChannel ) { moreVideo = TRUE; pthread_attr_init(&video_attr); pthread_create(&video_tid, &video_attr, (void * (*)(void *))startVideoThread, this); } if ( hasAudioChannel ) { moreAudio = TRUE; pthread_attr_init(&audio_attr); #ifdef USE_REALTIME_AUDIO_THREAD pthread_attr_setschedpolicy(&audio_attr,SCHED_RR); // Real-time round robin //qDebug("min: %i, max: %i", sched_get_priority_min( SCHED_RR ), sched_get_priority_max( SCHED_RR ) ); sched_param params; params.sched_priority = 50; pthread_attr_setschedparam(&audio_attr,¶ms); #endif pthread_create(&audio_tid, &audio_attr, (void * (*)(void *))startAudioThread, this); } } void LoopControl::setPaused( bool pause ) { static int whenPaused = 0; if ( !mediaPlayerState->curDecoder() || !mediaPlayerState->curDecoder()->isOpen() ) return; if ( pause ) { // Remember where we are whenPaused = playtime.elapsed(); killTimers(); } else { // Just like we never stopped playtime.restart(); playtime = playtime.addMSecs( -whenPaused ); whenPaused = 0; startTimers(); } } void LoopControl::stop( bool willPlayAgainShortly ) { #if defined(Q_WS_QWS) && !defined(QT_NO_COP) if ( !willPlayAgainShortly && disabledSuspendScreenSaver ) { disabledSuspendScreenSaver = FALSE; // Re-enable the suspend mode QCopEnvelope("QPE/System", "setScreenSaverMode(int)" ) << QPEApplication::Enable; } #endif if ( mediaPlayerState->curDecoder() && mediaPlayerState->curDecoder()->isOpen() ) { killTimers(); mediaPlayerState->curDecoder()->close(); if ( audioDevice ) { delete audioDevice; delete audioBuffer; audioDevice = 0; audioBuffer = 0; } } } bool LoopControl::init( const QString& filename ) { stop(); fileName = filename; stream = 0; // only play stream 0 for now current_frame = total_video_frames = total_audio_samples = 0; // qDebug( "Using the %s decoder", mediaPlayerState->curDecoder()->pluginName() ); // ### Hack to use libmpeg3plugin to get the number of audio samples if we are using the libmad plugin if ( mediaPlayerState->curDecoder()->pluginName() == QString("LibMadPlugin") ) { if ( mediaPlayerState->libMpeg3Decoder() && mediaPlayerState->libMpeg3Decoder()->open( filename ) ) { total_audio_samples = mediaPlayerState->libMpeg3Decoder()->audioSamples( 0 ); mediaPlayerState->libMpeg3Decoder()->close(); } } if ( !mediaPlayerState->curDecoder()|| !mediaPlayerState->curDecoder()->open( filename ) ) return FALSE; hasAudioChannel = mediaPlayerState->curDecoder()->audioStreams() > 0; hasVideoChannel = mediaPlayerState->curDecoder()->videoStreams() > 0; if ( hasAudioChannel ) { int astream = 0; channels = mediaPlayerState->curDecoder()->audioChannels( astream ); DecodeLoopDebug(( "channels = %d\n", channels )); if ( !total_audio_samples ) total_audio_samples = mediaPlayerState->curDecoder()->audioSamples( astream ); mediaPlayerState->setLength( total_audio_samples ); freq = mediaPlayerState->curDecoder()->audioFrequency( astream ); DecodeLoopDebug(( "frequency = %d\n", freq )); audioSampleCounter = 0; static const int bytes_per_sample = 2; //16 bit audioDevice = new AudioDevice( freq, channels, bytes_per_sample ); audioBuffer = new char[ audioDevice->bufferSize() ]; channels = audioDevice->channels(); //### must check which frequency is actually used. static const int size = 1; short int buf[size]; long samplesRead = 0; mediaPlayerState->curDecoder()->audioReadSamples( buf, channels, size, samplesRead, stream ); } if ( hasVideoChannel ) { total_video_frames = mediaPlayerState->curDecoder()->videoFrames( stream ); mediaPlayerState->setLength( total_video_frames ); framerate = mediaPlayerState->curDecoder()->videoFrameRate( stream ); DecodeLoopDebug(( "Frame rate %g total %ld", framerate, total_video_frames )); if ( framerate <= 1.0 ) { DecodeLoopDebug(( "Crazy frame rate, resetting to sensible" )); framerate = 25; } if ( total_video_frames == 1 ) { DecodeLoopDebug(( "Cannot seek to frame" )); } } videoMutex->lock(); current_frame = 0; prev_frame = -1; videoMutex->unlock(); - connect( mediaPlayerState, SIGNAL( positionChanged( long ) ), this, SLOT( setPosition( long ) ) ); - connect( mediaPlayerState, SIGNAL( pausedToggled( bool ) ), this, SLOT( setPaused( bool ) ) ); + connect( mediaPlayerState, SIGNAL( positionChanged(long) ), this, SLOT( setPosition(long) ) ); + connect( mediaPlayerState, SIGNAL( pausedToggled(bool) ), this, SLOT( setPaused(bool) ) ); //setBackgroundColor( black ); return TRUE; } void LoopControl::play() { #if defined(Q_WS_QWS) && !defined(QT_NO_COP) if ( !disabledSuspendScreenSaver ) { disabledSuspendScreenSaver = TRUE; // Stop the screen from blanking and power saving state QCopEnvelope("QPE/System", "setScreenSaverMode(int)" ) << ( hasVideoChannel ? QPEApplication::Disable : QPEApplication::DisableSuspend ); } #endif //begin = clock(); playtime.start(); startTimers(); //updateGeometry(); } void LoopControl::setMute( bool on ) { if ( isMuted != on ) { isMuted = on; if ( isMuted ) { } else { int frame = current_frame; // mediaPlayerState->curDecoder()->videoGetFrame( stream ); playtime.restart(); playtime = playtime.addMSecs( -frame * 1000 / framerate ); //begin = clock() - (double)frame * CLOCKS_PER_SEC / framerate; mediaPlayerState->curDecoder()->audioSetSample( frame*freq/framerate, stream ); } } } diff --git a/core/multimedia/opieplayer/mediaplayer.cpp b/core/multimedia/opieplayer/mediaplayer.cpp index b77708c..6c743ec 100644 --- a/core/multimedia/opieplayer/mediaplayer.cpp +++ b/core/multimedia/opieplayer/mediaplayer.cpp @@ -1,238 +1,238 @@ /********************************************************************** ** Copyright (C) 2000-2002 Trolltech AS. All rights reserved. ** ** This file is part of the Qtopia Environment. ** ** This file may be distributed and/or modified under the terms of the ** GNU General Public License version 2 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. ** ** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE ** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. ** ** See http://www.trolltech.com/gpl/ for GPL licensing information. ** ** Contact info@trolltech.com if any conditions of this licensing are ** not clear to you. ** **********************************************************************/ #include <qmessagebox.h> #include "mediaplayer.h" #include "playlistwidget.h" #include "audiowidget.h" #include "loopcontrol.h" #include "audiodevice.h" #include "mediaplayerstate.h" extern AudioWidget *audioUI; extern PlayListWidget *playList; extern LoopControl *loopControl; extern MediaPlayerState *mediaPlayerState; MediaPlayer::MediaPlayer( QObject *parent, const char *name ) : QObject( parent, name ), volumeDirection( 0 ), currentFile( NULL ) { // QPEApplication::grabKeyboard(); connect( qApp,SIGNAL( aboutToQuit()),SLOT( cleanUp()) ); - connect( mediaPlayerState, SIGNAL( playingToggled( bool ) ), this, SLOT( setPlaying( bool ) ) ); - connect( mediaPlayerState, SIGNAL( pausedToggled( bool ) ), this, SLOT( pauseCheck( bool ) ) ); + connect( mediaPlayerState, SIGNAL( playingToggled(bool) ), this, SLOT( setPlaying(bool) ) ); + connect( mediaPlayerState, SIGNAL( pausedToggled(bool) ), this, SLOT( pauseCheck(bool) ) ); connect( mediaPlayerState, SIGNAL( next() ), this, SLOT( next() ) ); connect( mediaPlayerState, SIGNAL( prev() ), this, SLOT( prev() ) ); connect( audioUI, SIGNAL( moreClicked() ), this, SLOT( startIncreasingVolume() ) ); connect( audioUI, SIGNAL( lessClicked() ), this, SLOT( startDecreasingVolume() ) ); connect( audioUI, SIGNAL( moreReleased() ), this, SLOT( stopChangingVolume() ) ); connect( audioUI, SIGNAL( lessReleased() ), this, SLOT( stopChangingVolume() ) ); } MediaPlayer::~MediaPlayer() { } void MediaPlayer::pauseCheck( bool b ) { // Only pause if playing if ( b && !mediaPlayerState->playing() ) mediaPlayerState->setPaused( FALSE ); } void MediaPlayer::play() { mediaPlayerState->setPlaying( FALSE ); mediaPlayerState->setPlaying( TRUE ); } void MediaPlayer::setPlaying( bool play ) { // qDebug("MediaPlayer setPlaying %d", play); if ( !play ) { mediaPlayerState->setPaused( FALSE ); loopControl->stop( FALSE ); return; } if ( mediaPlayerState->paused() ) { mediaPlayerState->setPaused( FALSE ); return; } // qDebug("about to ctrash"); const DocLnk *playListCurrent = playList->current(); if ( playListCurrent != NULL ) { loopControl->stop( TRUE ); currentFile = playListCurrent; } if ( currentFile == NULL ) { QMessageBox::critical( 0, tr( "No file"), tr( "Error: There is no file selected" ) ); mediaPlayerState->setPlaying( FALSE ); return; } if ( ((currentFile->file()).left(4) != "http") && !QFile::exists( currentFile->file() ) ) { QMessageBox::critical( 0, tr( "File not found"), tr( "The following file was not found: <i>" ) + currentFile->file() + "</i>" ); mediaPlayerState->setPlaying( FALSE ); return; } if ( !mediaPlayerState->newDecoder( currentFile->file() ) ) { QMessageBox::critical( 0, tr( "No decoder found"), tr( "Sorry, no appropriate decoders found for this file: <i>" ) + currentFile->file() + "</i>" ); mediaPlayerState->setPlaying( FALSE ); return; } if ( !loopControl->init( currentFile->file() ) ) { QMessageBox::critical( 0, tr( "Error opening file"), tr( "Sorry, an error occured trying to play the file: <i>" ) + currentFile->file() + "</i>" ); mediaPlayerState->setPlaying( FALSE ); return; } long seconds = loopControl->totalPlaytime(); QString time; time.sprintf("%li:%02i", seconds/60, (int)seconds%60 ); QString tickerText; if( currentFile->file().left(4) == "http" ) tickerText= tr( " File: " ) + currentFile->name(); else tickerText = tr( " File: " ) + currentFile->name() + tr(", Length: ") + time; QString fileInfo = mediaPlayerState->curDecoder()->fileInfo(); if ( !fileInfo.isEmpty() ) tickerText += ", " + fileInfo; audioUI->setTickerText( tickerText + "." ); loopControl->play(); mediaPlayerState->setView( loopControl->hasVideo() ? 'v' : 'a' ); } void MediaPlayer::prev() { if ( playList->prev() ) play(); else if ( mediaPlayerState->looping() ) { if ( playList->last() ) play(); } else mediaPlayerState->setList(); } void MediaPlayer::next() { if ( playList->next() ) play(); else if ( mediaPlayerState->looping() ) { if ( playList->first() ) play(); } else mediaPlayerState->setList(); } void MediaPlayer::startDecreasingVolume() { volumeDirection = -1; startTimer( 100 ); AudioDevice::decreaseVolume(); } void MediaPlayer::startIncreasingVolume() { volumeDirection = +1; startTimer( 100 ); AudioDevice::increaseVolume(); } bool drawnOnScreenDisplay = FALSE; unsigned int onScreenDisplayVolume = 0; const int yoff = 110; void MediaPlayer::stopChangingVolume() { killTimers(); // Get rid of the on-screen display stuff drawnOnScreenDisplay = FALSE; onScreenDisplayVolume = 0; int w = audioUI->width(); int h = audioUI->height(); audioUI->repaint( (w - 200) / 2, h - yoff, 200 + 9, 70, FALSE ); } void MediaPlayer::timerEvent( QTimerEvent * ) { // qDebug("timer"); if ( volumeDirection == +1 ) AudioDevice::increaseVolume(); else if ( volumeDirection == -1 ) AudioDevice::decreaseVolume(); // Display an on-screen display volume unsigned int l, r, v; bool m; AudioDevice::getVolume( l, r, m ); v = ((l + r) * 11) / (2*0xFFFF); if ( drawnOnScreenDisplay && onScreenDisplayVolume == v ) { // qDebug("returning %d, %d, %d, %d", v, l, r, m); return; } int w = audioUI->width(); int h = audioUI->height(); if ( drawnOnScreenDisplay ) { if ( onScreenDisplayVolume > v ) audioUI->repaint( (w - 200) / 2 + v * 20 + 0, h - yoff + 40, (onScreenDisplayVolume - v) * 20 + 9, 30, FALSE ); } drawnOnScreenDisplay = TRUE; onScreenDisplayVolume = v; QPainter p( audioUI ); p.setPen( QColor( 0x10, 0xD0, 0x10 ) ); p.setBrush( QColor( 0x10, 0xD0, 0x10 ) ); QFont f; f.setPixelSize( 20 ); f.setBold( TRUE ); p.setFont( f ); p.drawText( (w - 200) / 2, h - yoff + 20, tr("Volume") ); for ( unsigned int i = 0; i < 10; i++ ) { if ( v > i ) p.drawRect( (w - 200) / 2 + i * 20 + 0, h - yoff + 40, 9, 30 ); else p.drawRect( (w - 200) / 2 + i * 20 + 3, h - yoff + 50, 3, 10 ); } } diff --git a/core/multimedia/opieplayer/playlistwidget.cpp b/core/multimedia/opieplayer/playlistwidget.cpp index a359843..efb5df3 100644 --- a/core/multimedia/opieplayer/playlistwidget.cpp +++ b/core/multimedia/opieplayer/playlistwidget.cpp @@ -1,522 +1,522 @@ /********************************************************************** ** Copyright (C) 2000 Trolltech AS. All rights reserved. ** ** This file is part of Qtopia Environment. ** ** This file may be distributed and/or modified under the terms of the ** GNU General Public License version 2 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. ** ** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE ** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. ** ** See http://www.trolltech.com/gpl/ for GPL licensing information. ** ** Contact info@trolltech.com if any conditions of this licensing are ** not clear to you. ** **********************************************************************/ // code added by L. J. Potter Sat 03-02-2002 06:17:54 #define QTOPIA_INTERNAL_FSLP #include <qtoolbar.h> #include <qpe/qpemenubar.h> #include <qpe/lnkproperties.h> #include <qaction.h> #include <qlayout.h> #include <qmessagebox.h> //#include <qtimer.h> #include "playlistselection.h" #include "playlistwidget.h" #include "mediaplayerstate.h" #include "inputDialog.h" #include <stdlib.h> #include "audiowidget.h" #include "videowidget.h" #include <unistd.h> #include <sys/file.h> #include <sys/ioctl.h> #include <sys/soundcard.h> // for setBacklight() #include <linux/fb.h> #include <sys/types.h> #include <sys/stat.h> #include <stdlib.h> #define BUTTONS_ON_TOOLBAR #define SIDE_BUTTONS #define CAN_SAVE_LOAD_PLAYLISTS extern AudioWidget *audioUI; extern VideoWidget *videoUI; extern MediaPlayerState *mediaPlayerState; static inline QString fullBaseName ( const QFileInfo &fi ) { QString str = fi. fileName ( ); return str. left ( str. findRev ( '.' )); } QString audioMimes ="audio/mpeg;audio/x-wav;application/ogg;audio/x-mod"; // class myFileSelector { // }; class PlayListWidgetPrivate { public: QToolButton *tbPlay, *tbFull, *tbLoop, *tbScale, *tbShuffle, *tbAddToList, *tbRemoveFromList, *tbMoveUp, *tbMoveDown, *tbRemove; QFrame *playListFrame; FileSelector *files; PlayListSelection *selectedFiles; bool setDocumentUsed; DocLnk *current; }; class ToolButton : public QToolButton { public: ToolButton( QWidget *parent, const char *name, const QString& icon, QObject *handler, const QString& slot, bool t = FALSE ) : QToolButton( parent, name ) { setTextLabel( name ); setPixmap( Resource::loadPixmap( icon ) ); setAutoRaise( TRUE ); setFocusPolicy( QWidget::NoFocus ); setToggleButton( t ); connect( this, t ? SIGNAL( toggled(bool) ) : SIGNAL( clicked() ), handler, slot ); QPEMenuToolFocusManager::manager()->addWidget( this ); } }; class MenuItem : public QAction { public: MenuItem( QWidget *parent, const QString& text, QObject *handler, const QString& slot ) : QAction( text, QString::null, 0, 0 ) { connect( this, SIGNAL( activated() ), handler, slot ); addTo( parent ); } }; PlayListWidget::PlayListWidget( QWidget* parent, const char* name, WFlags fl ) : QMainWindow( parent, name, fl ) { d = new PlayListWidgetPrivate; d->setDocumentUsed = FALSE; d->current = NULL; fromSetDocument = FALSE; insanityBool=FALSE; audioScan = FALSE; videoScan = FALSE; // menuTimer = new QTimer( this ,"menu timer"), // connect( menuTimer, SIGNAL( timeout() ), SLOT( addSelected() ) ); channel = new QCopChannel( "QPE/Application/opieplayer", this ); - connect( channel, SIGNAL(received(const QCString&, const QByteArray&)), - this, SLOT( qcopReceive(const QCString&, const QByteArray&)) ); + connect( channel, SIGNAL(received(const QCString&,const QByteArray&)), + this, SLOT( qcopReceive(const QCString&,const QByteArray&)) ); setBackgroundMode( PaletteButton ); setCaption( tr("OpiePlayer") ); setIcon( Resource::loadPixmap( "opieplayer/MPEGPlayer" ) ); setToolBarsMovable( FALSE ); // Create Toolbar QToolBar *toolbar = new QToolBar( this ); toolbar->setHorizontalStretchable( TRUE ); // Create Menubar QMenuBar *menu = new QMenuBar( toolbar ); menu->setMargin( 0 ); QToolBar *bar = new QToolBar( this ); bar->setLabel( tr( "Play Operations" ) ); // d->tbPlayCurList = new ToolButton( bar, tr( "play List" ), "opieplayer/play_current_list", // this , SLOT( addSelected()) ); tbDeletePlaylist = new QPushButton( Resource::loadIconSet("trash"),"",bar,"close"); tbDeletePlaylist->setFlat(TRUE); tbDeletePlaylist->setFixedSize(20,20); d->tbAddToList = new ToolButton( bar, tr( "Add to Playlist" ), "opieplayer/add_to_playlist", this , SLOT(addSelected()) ); d->tbRemoveFromList = new ToolButton( bar, tr( "Remove from Playlist" ), "opieplayer/remove_from_playlist", this , SLOT(removeSelected()) ); -// d->tbPlay = new ToolButton( bar, tr( "Play" ), "opieplayer/play", /*this */mediaPlayerState , SLOT(setPlaying(bool) /* btnPlay() */), TRUE ); +// d->tbPlay = new ToolButton( bar, tr( "Play" ), "opieplayer/play", /*this */mediaPlayerState , SLOT(setPlaying(bool)/*btnPlay()*/), TRUE ); d->tbPlay = new ToolButton( bar, tr( "Play" ), "opieplayer/play", this , SLOT( btnPlay(bool) ), TRUE ); d->tbShuffle = new ToolButton( bar, tr( "Randomize" ),"opieplayer/shuffle", mediaPlayerState, SLOT(setShuffled(bool)), TRUE ); d->tbLoop = new ToolButton( bar, tr( "Loop" ),"opieplayer/loop", mediaPlayerState, SLOT(setLooping(bool)), TRUE ); tbDeletePlaylist->hide(); QPopupMenu *pmPlayList = new QPopupMenu( this ); menu->insertItem( tr( "File" ), pmPlayList ); new MenuItem( pmPlayList, tr( "Clear List" ), this, SLOT( clearList() ) ); new MenuItem( pmPlayList, tr( "Add all audio files" ), this, SLOT( addAllMusicToList() ) ); new MenuItem( pmPlayList, tr( "Add all video files" ), this, SLOT( addAllVideoToList() ) ); new MenuItem( pmPlayList, tr( "Add all files" ), this, SLOT( addAllToList() ) ); pmPlayList->insertSeparator(-1); new MenuItem( pmPlayList, tr( "Save PlayList" ), this, SLOT( saveList() ) ); new MenuItem( pmPlayList, tr( "Open File or URL" ), this,SLOT( openFile() ) ); pmPlayList->insertSeparator(-1); new MenuItem( pmPlayList, tr( "Rescan for Audio Files" ), this,SLOT( scanForAudio() ) ); new MenuItem( pmPlayList, tr( "Rescan for Video Files" ), this,SLOT( scanForVideo() ) ); QPopupMenu *pmView = new QPopupMenu( this ); menu->insertItem( tr( "View" ), pmView ); fullScreenButton = new QAction(tr("Full Screen"), Resource::loadPixmap("fullscreen"), QString::null, 0, this, 0); fullScreenButton->addTo(pmView); scaleButton = new QAction(tr("Scale"), Resource::loadPixmap("opieplayer/scale"), QString::null, 0, this, 0); scaleButton->addTo(pmView); skinsMenu = new QPopupMenu( this ); menu->insertItem( tr( "Skins" ), skinsMenu ); skinsMenu->isCheckable(); - connect( skinsMenu, SIGNAL( activated( int ) ) , - this, SLOT( skinsMenuActivated( int ) ) ); + connect( skinsMenu, SIGNAL( activated(int) ) , + this, SLOT( skinsMenuActivated(int) ) ); populateSkinsMenu(); QVBox *vbox5 = new QVBox( this ); vbox5->setBackgroundMode( PaletteButton ); QVBox *vbox4 = new QVBox( vbox5 ); vbox4->setBackgroundMode( PaletteButton ); QHBox *hbox6 = new QHBox( vbox4 ); hbox6->setBackgroundMode( PaletteButton ); tabWidget = new QTabWidget( hbox6, "tabWidget" ); // tabWidget->setTabShape(QTabWidget::Triangular); QWidget *pTab; pTab = new QWidget( tabWidget, "pTab" ); // playlistView = new QListView( pTab, "playlistview" ); // playlistView->setMinimumSize(236,260); tabWidget->insertTab( pTab,"Playlist"); // Add the playlist area QVBox *vbox3 = new QVBox( pTab ); vbox3->setBackgroundMode( PaletteButton ); d->playListFrame = vbox3; QGridLayout *layoutF = new QGridLayout( pTab ); layoutF->setSpacing( 2); layoutF->setMargin( 2); layoutF->addMultiCellWidget( d->playListFrame , 0, 0, 0, 1 ); QHBox *hbox2 = new QHBox( vbox3 ); hbox2->setBackgroundMode( PaletteButton ); d->selectedFiles = new PlayListSelection( hbox2); QVBox *vbox1 = new QVBox( hbox2 ); vbox1->setBackgroundMode( PaletteButton ); QPEApplication::setStylusOperation( d->selectedFiles->viewport(),QPEApplication::RightOnHold); QVBox *stretch1 = new QVBox( vbox1 ); stretch1->setBackgroundMode( PaletteButton ); // add stretch new ToolButton( vbox1, tr( "Move Up" ), "opieplayer/up", d->selectedFiles, SLOT(moveSelectedUp()) ); new ToolButton( vbox1, tr( "Remove" ), "opieplayer/cut", d->selectedFiles, SLOT(removeSelected()) ); new ToolButton( vbox1, tr( "Move Down" ), "opieplayer/down", d->selectedFiles, SLOT(moveSelectedDown()) ); QVBox *stretch2 = new QVBox( vbox1 ); stretch2->setBackgroundMode( PaletteButton ); // add stretch QWidget *aTab; aTab = new QWidget( tabWidget, "aTab" ); audioView = new QListView( aTab, "Audioview" ); QGridLayout *layoutA = new QGridLayout( aTab ); layoutA->setSpacing( 2); layoutA->setMargin( 2); layoutA->addMultiCellWidget( audioView, 0, 0, 0, 1 ); audioView->addColumn( tr("Title"),-1); audioView->addColumn(tr("Size"), -1); audioView->addColumn(tr("Media"),-1); audioView->addColumn( tr( "Path" ), -1 ); audioView->setColumnAlignment(1, Qt::AlignRight); audioView->setColumnAlignment(2, Qt::AlignRight); audioView->setAllColumnsShowFocus(TRUE); audioView->setMultiSelection( TRUE ); audioView->setSelectionMode( QListView::Extended); audioView->setSorting( 3, TRUE ); tabWidget->insertTab(aTab,tr("Audio")); QPEApplication::setStylusOperation( audioView->viewport(),QPEApplication::RightOnHold); // audioView // populateAudioView(); // videowidget QWidget *vTab; vTab = new QWidget( tabWidget, "vTab" ); videoView = new QListView( vTab, "Videoview" ); QGridLayout *layoutV = new QGridLayout( vTab ); layoutV->setSpacing( 2); layoutV->setMargin( 2); layoutV->addMultiCellWidget( videoView, 0, 0, 0, 1 ); videoView->addColumn(tr("Title"),-1); videoView->addColumn(tr("Size"),-1); videoView->addColumn(tr("Media"),-1); videoView->addColumn(tr( "Path" ), -1 ); videoView->setColumnAlignment(1, Qt::AlignRight); videoView->setColumnAlignment(2, Qt::AlignRight); videoView->setAllColumnsShowFocus(TRUE); videoView->setMultiSelection( TRUE ); videoView->setSelectionMode( QListView::Extended); QPEApplication::setStylusOperation( videoView->viewport(),QPEApplication::RightOnHold); tabWidget->insertTab( vTab,tr("Video")); QWidget *LTab; LTab = new QWidget( tabWidget, "LTab" ); playLists = new FileSelector( "playlist/plain;audio/x-mpegurl", LTab, "fileselector" , FALSE, FALSE); QGridLayout *layoutL = new QGridLayout( LTab ); layoutL->setSpacing( 2); layoutL->setMargin( 2); layoutL->addMultiCellWidget( playLists, 0, 0, 0, 1 ); tabWidget->insertTab(LTab,tr("Lists")); connect(tbDeletePlaylist,(SIGNAL(released())),SLOT( deletePlaylist())); connect( fullScreenButton, SIGNAL(activated()), mediaPlayerState, SLOT(toggleFullscreen()) ); connect( scaleButton, SIGNAL(activated()), mediaPlayerState, SLOT(toggleScaled()) ); - connect( d->selectedFiles, SIGNAL( mouseButtonPressed( int, QListViewItem *, const QPoint&, int)), - this,SLOT( playlistViewPressed(int, QListViewItem *, const QPoint&, int)) ); + connect( d->selectedFiles, SIGNAL( mouseButtonPressed(int,QListViewItem*,const QPoint&,int)), + this,SLOT( playlistViewPressed(int,QListViewItem*,const QPoint&,int)) ); ///audioView - connect( audioView, SIGNAL( mouseButtonPressed( int, QListViewItem *, const QPoint&, int)), - this,SLOT( viewPressed(int, QListViewItem *, const QPoint&, int)) ); + connect( audioView, SIGNAL( mouseButtonPressed(int,QListViewItem*,const QPoint&,int)), + this,SLOT( viewPressed(int,QListViewItem*,const QPoint&,int)) ); - connect( audioView, SIGNAL( returnPressed( QListViewItem *)), - this,SLOT( playIt( QListViewItem *)) ); - connect( audioView, SIGNAL( doubleClicked( QListViewItem *) ), this, SLOT( addToSelection( QListViewItem *) ) ); + connect( audioView, SIGNAL( returnPressed(QListViewItem*)), + this,SLOT( playIt(QListViewItem*)) ); + connect( audioView, SIGNAL( doubleClicked(QListViewItem*) ), this, SLOT( addToSelection(QListViewItem*) ) ); //videoView - connect( videoView, SIGNAL( mouseButtonPressed( int, QListViewItem *, const QPoint&, int)), - this,SLOT( viewPressed(int, QListViewItem *, const QPoint&, int)) ); - connect( videoView, SIGNAL( returnPressed( QListViewItem *)), - this,SLOT( playIt( QListViewItem *)) ); - connect( videoView, SIGNAL( doubleClicked( QListViewItem *) ), this, SLOT( addToSelection( QListViewItem *) ) ); + connect( videoView, SIGNAL( mouseButtonPressed(int,QListViewItem*,const QPoint&,int)), + this,SLOT( viewPressed(int,QListViewItem*,const QPoint&,int)) ); + connect( videoView, SIGNAL( returnPressed(QListViewItem*)), + this,SLOT( playIt(QListViewItem*)) ); + connect( videoView, SIGNAL( doubleClicked(QListViewItem*) ), this, SLOT( addToSelection(QListViewItem*) ) ); //playlists - connect( playLists, SIGNAL( fileSelected( const DocLnk &) ), this, SLOT( loadList( const DocLnk & ) ) ); + connect( playLists, SIGNAL( fileSelected(const DocLnk&) ), this, SLOT( loadList(const DocLnk&) ) ); connect( tabWidget, SIGNAL (currentChanged(QWidget*)),this,SLOT(tabChanged(QWidget*))); - connect( mediaPlayerState, SIGNAL( playingToggled( bool ) ), d->tbPlay, SLOT( setOn( bool ) ) ); + connect( mediaPlayerState, SIGNAL( playingToggled(bool) ), d->tbPlay, SLOT( setOn(bool) ) ); - connect( mediaPlayerState, SIGNAL( loopingToggled( bool ) ), d->tbLoop, SLOT( setOn( bool ) ) ); - connect( mediaPlayerState, SIGNAL( shuffledToggled( bool ) ), d->tbShuffle, SLOT( setOn( bool ) ) ); - connect( mediaPlayerState, SIGNAL( playlistToggled( bool ) ), this, SLOT( setPlaylist( bool ) ) ); + connect( mediaPlayerState, SIGNAL( loopingToggled(bool) ), d->tbLoop, SLOT( setOn(bool) ) ); + connect( mediaPlayerState, SIGNAL( shuffledToggled(bool) ), d->tbShuffle, SLOT( setOn(bool) ) ); + connect( mediaPlayerState, SIGNAL( playlistToggled(bool) ), this, SLOT( setPlaylist(bool) ) ); - connect( d->selectedFiles, SIGNAL( doubleClicked( QListViewItem *) ), this, SLOT( playIt( QListViewItem *) ) ); + connect( d->selectedFiles, SIGNAL( doubleClicked(QListViewItem*) ), this, SLOT( playIt(QListViewItem*) ) ); setCentralWidget( vbox5 ); Config cfg( "OpiePlayer" ); readConfig( cfg ); currentPlayList = cfg.readEntry("CurrentPlaylist","default"); loadList(DocLnk( currentPlayList)); setCaption(tr("OpiePlayer: ")+ fullBaseName ( QFileInfo(currentPlayList))); initializeStates(); } PlayListWidget::~PlayListWidget() { Config cfg( "OpiePlayer" ); writeConfig( cfg ); if ( d->current ) delete d->current; if(d) delete d; } void PlayListWidget::initializeStates() { d->tbPlay->setOn( mediaPlayerState->playing() ); d->tbLoop->setOn( mediaPlayerState->looping() ); d->tbShuffle->setOn( mediaPlayerState->shuffled() ); setPlaylist( true); } void PlayListWidget::readConfig( Config& cfg ) { cfg.setGroup("PlayList"); QString currentString = cfg.readEntry("current", "" ); int noOfFiles = cfg.readNumEntry("NumberOfFiles", 0 ); for ( int i = 0; i < noOfFiles; i++ ) { QString entryName; entryName.sprintf( "File%i", i + 1 ); QString linkFile = cfg.readEntry( entryName ); DocLnk lnk( linkFile ); if ( lnk.isValid() ) { d->selectedFiles->addToSelection( lnk ); } } d->selectedFiles->setSelectedItem( currentString); } void PlayListWidget::writeConfig( Config& cfg ) const { d->selectedFiles->writeCurrent( cfg); cfg.setGroup("PlayList"); int noOfFiles = 0; d->selectedFiles->first(); do { const DocLnk *lnk = d->selectedFiles->current(); if ( lnk ) { QString entryName; entryName.sprintf( "File%i", noOfFiles + 1 ); // qDebug(entryName); cfg.writeEntry( entryName, lnk->linkFile() ); // if this link does exist, add it so we have the file // next time... if ( !QFile::exists( lnk->linkFile() ) ) { // the way writing lnks doesn't really check for out // of disk space, but check it anyway. // if ( !lnk->writeLink() ) { // QMessageBox::critical( 0, tr("Out of space"), // tr( "There was a problem saving " // "the playlist.\n" // "Your playlist " // "may be missing some entries\n" // "the next time you start it." ) // ); // } } noOfFiles++; } } while ( d->selectedFiles->next() ); cfg.writeEntry("NumberOfFiles", noOfFiles ); } void PlayListWidget::addToSelection( const DocLnk& lnk ) { d->setDocumentUsed = false; if ( mediaPlayerState->playlist() ) { if(QFileInfo(lnk.file()).exists() || lnk.file().left(4) == "http" ) d->selectedFiles->addToSelection( lnk ); } else mediaPlayerState->setPlaying( true); } void PlayListWidget::clearList() { while ( first() ) d->selectedFiles->removeSelected(); Config cfg( "OpiePlayer" ); cfg.setGroup("PlayList"); cfg.writeEntry("CurrentPlaylist",""); currentPlayList=""; } void PlayListWidget::addAllToList() { DocLnkSet filesAll; Global::findDocuments(&filesAll, "video/*;audio/*"); QListIterator<DocLnk> Adit( filesAll.children() ); for ( ; Adit.current(); ++Adit ) if(QFileInfo(Adit.current()->file()).exists()) d->selectedFiles->addToSelection( **Adit ); tabWidget->setCurrentPage(0); writeCurrentM3u(); d->selectedFiles->first(); } void PlayListWidget::addAllMusicToList() { QListIterator<DocLnk> dit( files.children() ); for ( ; dit.current(); ++dit ) if(QFileInfo(dit.current()->file()).exists()) d->selectedFiles->addToSelection( **dit ); tabWidget->setCurrentPage(0); writeCurrentM3u(); d->selectedFiles->first(); } void PlayListWidget::addAllVideoToList() { QListIterator<DocLnk> dit( vFiles.children() ); for ( ; dit.current(); ++dit ) if(QFileInfo( dit.current()->file()).exists()) d->selectedFiles->addToSelection( **dit ); tabWidget->setCurrentPage(0); writeCurrentM3u(); d->selectedFiles->first(); } void PlayListWidget::setDocument(const QString& fileref) { fromSetDocument = true; d->setDocumentUsed = TRUE; setDocumentEx(fileref); } void PlayListWidget::setDocumentEx(const QString& fileref) { qDebug("opieplayer receive "+fileref); clearList(); DocLnk lnk; QFileInfo fileInfo(fileref); if ( !fileInfo.exists() ) { QMessageBox::critical( 0, tr( "Invalid File" ), tr( "There was a problem in getting the file." ) ); return; } // qDebug("<<<<<<<<<<<<<<<<<<<<<<setDocument "+fileref); QString extension = fileInfo.extension(false); if( extension.find( "m3u", 0, false) != -1) { //is m3u readm3u( fileref); } else if( extension.find( "pls", 0, false) != -1 ) { //is pls readPls( fileref); } else if( fileref.find("playlist",0,TRUE) != -1) {//is playlist clearList(); lnk.setName( fileInfo.baseName() ); //sets name lnk.setFile( fileref ); //sets file name lnk.setIcon("Sound"); //addToSelection( lnk ); loadList( lnk); d->selectedFiles->first(); } else { if( fileref.find(".desktop",0,TRUE) != -1) { lnk = DocLnk(fileref); } else { lnk.setName( fileInfo.baseName() ); //sets name lnk.setFile( fileref ); //sets file name lnk.setIcon("Sound"); } addToSelection( lnk ); // addToSelection( DocLnk( fileref ) ); @@ -751,385 +751,385 @@ void PlayListWidget::addToSelection( QListViewItem *it) { }; // case 1: { DocLnk lnk; QString filename; filename=it->text(3); lnk.setName( fullBaseName ( QFileInfo(filename)) ); //sets name lnk.setFile( filename ); //sets file name d->selectedFiles->addToSelection( lnk); if(tabWidget->currentPageIndex() == 0) writeCurrentM3u(); // tabWidget->setCurrentPage(0); } } void PlayListWidget::tabChanged(QWidget *) { switch ( tabWidget->currentPageIndex()) { case 0: { if( !tbDeletePlaylist->isHidden()) tbDeletePlaylist->hide(); d->tbRemoveFromList->setEnabled(TRUE); d->tbAddToList->setEnabled(FALSE); } break; case 1: { audioView->clear(); populateAudioView(); if( !tbDeletePlaylist->isHidden()) tbDeletePlaylist->hide(); d->tbRemoveFromList->setEnabled(FALSE); d->tbAddToList->setEnabled(TRUE); } break; case 2: { videoView->clear(); populateVideoView(); if( !tbDeletePlaylist->isHidden()) tbDeletePlaylist->hide(); d->tbRemoveFromList->setEnabled(FALSE); d->tbAddToList->setEnabled(TRUE); } break; case 3: { if( tbDeletePlaylist->isHidden()) tbDeletePlaylist->show(); playLists->reread(); } break; }; } void PlayListWidget::btnPlay(bool b) { // mediaPlayerState->setPlaying(b); switch ( tabWidget->currentPageIndex()) { case 0: { // if( d->selectedFiles->current()->file().find(" ",0,TRUE) != -1 // if( d->selectedFiles->current()->file().find("%20",0,TRUE) != -1) { // QMessageBox::message("Note","You are trying to play\na malformed url."); // } else { mediaPlayerState->setPlaying(b); insanityBool=FALSE; qDebug("insanity"); // } } break; case 1: { // d->selectedFiles->unSelect(); addToSelection( audioView->currentItem() ); mediaPlayerState->setPlaying( b); d->selectedFiles->removeSelected( ); d->selectedFiles->unSelect(); tabWidget->setCurrentPage(1); insanityBool=FALSE; }// audioView->clearSelection(); break; case 2: { addToSelection( videoView->currentItem() ); mediaPlayerState->setPlaying( b); // qApp->processEvents(); d->selectedFiles->removeSelected( ); d->selectedFiles->unSelect(); tabWidget->setCurrentPage(2); insanityBool=FALSE; }// videoView->clearSelection(); break; }; } void PlayListWidget::deletePlaylist() { switch( QMessageBox::information( this, (tr("Remove Playlist?")), (tr("You really want to delete\nthis playlist?")), (tr("Yes")), (tr("No")), 0 )){ case 0: // Yes clicked, QFile().remove(playLists->selectedDocument().file()); QFile().remove(playLists->selectedDocument().linkFile()); playLists->reread(); break; case 1: // Cancel break; }; } void PlayListWidget::viewPressed( int mouse, QListViewItem *, const QPoint&, int ) { switch (mouse) { case 1: break; case 2:{ QPopupMenu m; m.insertItem( tr( "Play" ), this, SLOT( playSelected() )); m.insertItem( tr( "Add to Playlist" ), this, SLOT( addSelected() )); m.insertSeparator(); if( QFile(QPEApplication::qpeDir()+"lib/libopie.so").exists() ) m.insertItem( tr( "Properties" ), this, SLOT( listDelete() )); m.exec( QCursor::pos() ); } break; }; } void PlayListWidget::playSelected() { btnPlay( true); // d->selectedFiles->unSelect(); } void PlayListWidget::playlistViewPressed( int mouse, QListViewItem *, const QPoint&, int) { switch (mouse) { case 1: break; case 2:{ QPopupMenu m; m.insertItem( tr( "Play Selected" ), this, SLOT( playSelected() )); m.insertItem( tr( "Remove" ), this, SLOT( removeSelected() )); // m.insertSeparator(); // m.insertItem( tr( "Properties" ), this, SLOT( listDelete() )); m.exec( QCursor::pos() ); } break; }; } void PlayListWidget::listDelete() { Config cfg( "OpiePlayer" ); cfg.setGroup("PlayList"); currentPlayList = cfg.readEntry("CurrentPlaylist",""); QString file; // int noOfFiles = cfg.readNumEntry("NumberOfFiles", 0 ); switch ( tabWidget->currentPageIndex()) { case 0: break; case 1: { file = audioView->currentItem()->text(0); QListIterator<DocLnk> Pdit( files.children() ); for ( ; Pdit.current(); ++Pdit ) { if( Pdit.current()->name() == file) { LnkProperties prop( Pdit.current() ); QPEApplication::execDialog( &prop ); } } populateAudioView(); } break; case 2: { // file = videoView->selectedItem()->text(0); // for ( int i = 0; i < noOfFiles; i++ ) { // QString entryName; // entryName.sprintf( "File%i", i + 1 ); // QString linkFile = cfg.readEntry( entryName ); // AppLnk lnk( AppLnk(linkFile)); // if( lnk.name() == file ) { // LnkProperties prop( &lnk); - // // connect(&prop, SIGNAL(select(const AppLnk *)), this, SLOT(externalSelected(const AppLnk *))); + // // connect(&prop, SIGNAL(select(const AppLnk*)), this, SLOT(externalSelected(const AppLnk*))); // prop.showMaximized(); // prop.exec(); // } // } } break; }; } void PlayListWidget::scanForAudio() { // qDebug("scan for audio"); files.detachChildren(); QListIterator<DocLnk> sdit( files.children() ); for ( ; sdit.current(); ++sdit ) { delete sdit.current(); } Global::findDocuments( &files, audioMimes); audioScan = true; } void PlayListWidget::scanForVideo() { // qDebug("scan for video"); vFiles.detachChildren(); QListIterator<DocLnk> sdit( vFiles.children() ); for ( ; sdit.current(); ++sdit ) { delete sdit.current(); } Global::findDocuments(&vFiles, "video/*"); videoScan = true; } void PlayListWidget::populateAudioView() { audioView->clear(); StorageInfo storageInfo; const QList<FileSystem> &fs = storageInfo.fileSystems(); if(!audioScan) scanForAudio(); QListIterator<DocLnk> dit( files.children() ); QListIterator<FileSystem> it ( fs ); QString storage; for ( ; dit.current(); ++dit ) { for( ; it.current(); ++it ){ const QString name = (*it)->name(); const QString path = (*it)->path(); if(dit.current()->file().find(path) != -1 ) storage=name; } QListViewItem * newItem; if ( QFile( dit.current()->file()).exists() || dit.current()->file().left(4) == "http" ) { long size; if( dit.current()->file().left(4) == "http" ) size=0; else size = QFile( dit.current()->file() ).size(); // qDebug(dit.current()->name()); newItem= /*(void)*/ new QListViewItem( audioView, dit.current()->name(), QString::number(size ), storage, dit.current()->file()); newItem->setPixmap(0, Resource::loadPixmap( "opieplayer/musicfile" )); } } } void PlayListWidget::populateVideoView() { videoView->clear(); StorageInfo storageInfo; const QList<FileSystem> &fs = storageInfo.fileSystems(); if(!videoScan ) scanForVideo(); QListIterator<DocLnk> Vdit( vFiles.children() ); QListIterator<FileSystem> it ( fs ); videoView->clear(); QString storage; for ( ; Vdit.current(); ++Vdit ) { for( ; it.current(); ++it ){ const QString name = (*it)->name(); const QString path = (*it)->path(); if( Vdit.current()->file().find(path) != -1 ) storage=name; } QListViewItem * newItem; if ( QFile( Vdit.current()->file()).exists() ) { newItem= /*(void)*/ new QListViewItem( videoView, Vdit.current()->name(), QString::number( QFile( Vdit.current()->file() ).size() ), storage, Vdit.current()->file()); newItem->setPixmap(0, Resource::loadPixmap( "opieplayer/videofile" )); } } } void PlayListWidget::openFile() { QString filename, name; InputDialog *fileDlg; fileDlg = new InputDialog(this,tr("Open file or URL"),TRUE, 0); fileDlg->exec(); if( fileDlg->result() == 1 ) { filename = fileDlg->text(); // qDebug( "Selected filename is " + filename ); DocLnk lnk; Config cfg( "OpiePlayer" ); cfg.setGroup("PlayList"); QString m3uFile; m3uFile = filename; if(filename.left(4) == "http") { if(filename.find(":",8,TRUE) != -1) { //found a port m3uFile = filename; if( m3uFile.right( 1 ).find( '/' ) == -1) { m3uFile += "/"; } filename = m3uFile; } lnk.setName( m3uFile ); //sets name lnk.setFile( filename ); //sets file name lnk.setIcon("opieplayer2/musicfile"); d->selectedFiles->addToSelection( lnk ); writeCurrentM3u(); } else if( filename.right( 3) == "m3u" ) { readm3u( filename ); } else if( filename.right(3) == "pls" ) { readPls( filename ); } else { lnk.setName( fullBaseName ( QFileInfo(filename)) ); //sets name lnk.setFile( filename ); //sets file name d->selectedFiles->addToSelection( lnk); lnk.removeLinkFile(); writeCurrentM3u(); } } if( fileDlg ) { delete fileDlg; } } /* reads m3u and shows files/urls to playlist widget */ void PlayListWidget::readm3u( const QString &filename ) { // qDebug( "read m3u filename " + filename ); Om3u *m3uList; QString s, name; m3uList = new Om3u( filename, IO_ReadOnly ); m3uList->readM3u(); DocLnk lnk; for ( QStringList::ConstIterator it = m3uList->begin(); it != m3uList->end(); ++it ) { s = *it; // qDebug("reading "+ s); if(s.left(4)=="http") { lnk.setName( s ); //sets file name lnk.setIcon("opieplayer2/musicfile"); // if(s.right(4) != '.' || s.right(5) != '.') if(s.right(4) != '.' || s.right(5) != '.' ) if( s.right(1) != "/") lnk.setFile( s+"/"); //if url with no extension else lnk.setFile( s ); //sets file name } else { // if( QFileInfo( s ).exists() ) { lnk.setName( fullBaseName ( QFileInfo(s))); // if(s.right(4) == '.') {//if regular file if(s.left(1) != "/") { // qDebug("set link "+QFileInfo(filename).dirPath()+"/"+s); lnk.setFile( QFileInfo(filename).dirPath()+"/"+s); lnk.setIcon("SoundPlayer"); } else { // qDebug("set link2 "+s); lnk.setFile( s); lnk.setIcon("SoundPlayer"); } } d->selectedFiles->addToSelection( lnk ); } Config config( "OpiePlayer" ); config.setGroup( "PlayList" ); config.writeEntry("CurrentPlaylist",filename); config.write(); currentPlayList=filename; // m3uList->write(); m3uList->close(); if(m3uList) delete m3uList; diff --git a/core/obex/obexhandler.cpp b/core/obex/obexhandler.cpp index 4034560..28f9b5b 100644 --- a/core/obex/obexhandler.cpp +++ b/core/obex/obexhandler.cpp @@ -1,67 +1,67 @@ #include <qpe/qcopenvelope_qws.h> #include <qpe/qpeapplication.h> #include "obexsend.h" #include "receiver.h" #include "obexhandler.h" using namespace OpieObex; /* TRANSLATOR OpieObex::ObexHandler */ ObexHandler::ObexHandler() { m_wasRec = false; m_sender = 0l; m_receiver = 0l; QCopChannel* chan = new QCopChannel("QPE/Obex"); - connect(chan, SIGNAL(received(const QCString&, const QByteArray& ) ), - this, SLOT(irdaMessage(const QCString&, const QByteArray& ) ) ); + connect(chan, SIGNAL(received(const QCString&,const QByteArray&) ), + this, SLOT(irdaMessage(const QCString&,const QByteArray&) ) ); } ObexHandler::~ObexHandler() { delete m_sender; delete m_receiver; } void ObexHandler::doSend(const QString& str, const QString& desc) { delete m_sender; m_sender = new SendWidget; m_sender->raise(); QPEApplication::showWidget( m_sender ); connect(m_sender, SIGNAL(done() ), this, SLOT(slotSent() ) ); m_sender->send( str, desc ); } void ObexHandler::doReceive(bool b) { if (m_receiver && b ) return; // we should enable receiver and it is on else if (!m_receiver && !b ) return; // we should disbale receiver and it is off else if (m_receiver && !b ) { delete m_receiver; m_receiver=0; }else if (!m_receiver && b ) { m_receiver= new Receiver; } } void ObexHandler::slotSent() { QString file = m_sender->file(); delete m_sender; m_sender = 0; QCopEnvelope e ("QPE/Obex", "done(QString)" ); e << file; doReceive(m_wasRec ); m_wasRec = false; } void ObexHandler::irdaMessage( const QCString& msg, const QByteArray& data) { QDataStream stream( data, IO_ReadOnly ); if ( msg == "send(QString,QString,QString)" ) { QString name, desc; stream >> desc; stream >> name; m_wasRec = (m_receiver != 0 ); doReceive( false ); doSend(name, desc); }else if (msg == "receive(int)") { int rec; stream >> rec; doReceive(rec); } } diff --git a/core/obex/obexsend.cpp b/core/obex/obexsend.cpp index 6b8d467..cd8d58e 100644 --- a/core/obex/obexsend.cpp +++ b/core/obex/obexsend.cpp @@ -1,254 +1,254 @@ #include <qpushbutton.h> #include <qlabel.h> #include <qlayout.h> #include <qtimer.h> #include <qpe/qcopenvelope_qws.h> #include "obex.h" #include "obexsend.h" using namespace OpieObex; /* TRANSLATOR OpieObex::SendWidget */ SendWidget::SendWidget( QWidget* parent, const char* name ) : QWidget( parent, name ) { initUI(); } SendWidget::~SendWidget() { } void SendWidget::initUI() { m_obex = new Obex(this, "obex"); connect(m_obex, SIGNAL(error(int) ), this, SLOT(slotIrError(int) ) ); connect(m_obex, SIGNAL(sent(bool) ), this, SLOT(slotIrSent(bool) ) ); - connect(m_obex, SIGNAL(currentTry(unsigned int ) ), - this, SLOT(slotIrTry(unsigned int ) ) ); + connect(m_obex, SIGNAL(currentTry(unsigned int) ), + this, SLOT(slotIrTry(unsigned int) ) ); QCopChannel* chan = new QCopChannel("QPE/IrDaAppletBack", this ); - connect(chan, SIGNAL(received(const QCString&, const QByteArray& ) ), - this, SLOT(dispatchIrda(const QCString&, const QByteArray& ) ) ); + connect(chan, SIGNAL(received(const QCString&,const QByteArray&) ), + this, SLOT(dispatchIrda(const QCString&,const QByteArray&) ) ); chan = new QCopChannel("QPE/BluetoothBack", this ); - connect(chan, SIGNAL(received(const QCString&, const QByteArray& ) ), - this, SLOT(dispatchBt(const QCString&, const QByteArray& ) ) ); + connect(chan, SIGNAL(received(const QCString&,const QByteArray&) ), + this, SLOT(dispatchBt(const QCString&,const QByteArray&) ) ); QVBoxLayout* lay = new QVBoxLayout(this); QHBox* nameBox = new QHBox(this); QLabel* name = new QLabel(nameBox); name->setText( tr("<qt><h1>Sending:</h1></qt>") ); name->setAlignment( AlignLeft | AlignTop ); m_lblFile = new QLabel(nameBox); lay->addWidget(nameBox, 0); QFrame* frame = new QFrame(this); frame->setFrameShape( QFrame::HLine ); frame->setFrameShadow( QFrame::Sunken ); lay->addWidget(frame, 10); QLabel* devices = new QLabel(this); devices->setText("<qt><b>Devices:</b></qt>"); devices->setAlignment( AlignLeft | AlignTop ); lay->addWidget( devices,10 ); m_devBox = new DeviceBox(this); lay->addWidget( m_devBox, 50 ); - connect(m_devBox, SIGNAL(selectedDevice(int, int ) ), - this, SLOT(slotSelectedDevice(int, int) ) ); + connect(m_devBox, SIGNAL(selectedDevice(int,int) ), + this, SLOT(slotSelectedDevice(int,int) ) ); QPushButton *but = new QPushButton(this); but->setText(tr("Done") ); connect(but, SIGNAL(clicked() ), this, SLOT(slotDone() ) ); lay->addWidget( but ); m_lay = lay; // QT does not like if you add items to an layout which already exits.... // and was layouted invalidate() does not help too // so we use RichText.... } /* * in send we'll first set everything up * and then wait for a list of devices. */ void SendWidget::send( const QString& file, const QString& desc ) { m_file = file; m_irDa.clear(); m_start = 0; m_lblFile->setText(desc.isEmpty() ? file : desc ); if ( !QCopChannel::isRegistered("QPE/IrDaApplet") ) { m_irDeSearch = m_devBox->addDevice( tr("IrDa is not enabled!"), DeviceBox::Error ); m_start++; }else m_irDeSearch = m_devBox->addDevice( tr("Searching for IrDa Devices."), DeviceBox::Search ); if ( !QCopChannel::isRegistered("QPE/Bluetooth") ) { m_btDeSearch = m_devBox->addDevice( tr("Bluetooth is not available"), DeviceBox::Error ); m_start++; }else m_btDeSearch = m_devBox->addDevice( tr("Searching for bluetooth Devices."), DeviceBox::Search ); if (m_start != 2 ) { QCopEnvelope e0("QPE/IrDaApplet", "enableIrda()"); QCopEnvelope e1("QPE/Bluetooth", "enableBluetooth()"); QCopEnvelope e2("QPE/IrDaApplet", "listDevices()"); QCopEnvelope e3("QPE/Bluetooth", "listDevices()"); } } void SendWidget::slotIrDaDevices( const QStringList& list) { qWarning("slot it irda devices "); for (QStringList::ConstIterator it = list.begin(); it != list.end(); ++it ) { int id = m_devBox->addDevice( (*it), DeviceBox::IrDa, tr("Scheduling for beam.") ); m_irDa.insert( id, (*it) ); } m_devBox->removeDevice( m_irDeSearch ); m_irDaIt = m_irDa.begin(); slotStartIrda(); } void SendWidget::slotBTDevices( const QMap<QString, QString>& str ) { for(QMap<QString, QString>::ConstIterator it = str.begin(); it != str.end(); ++it ) { int id = m_devBox->addDevice( it.key(), DeviceBox::BT, tr("Click to beam") ); m_bt.insert( id, Pair( it.key(), it.data() ) ); } m_devBox->removeDevice( m_btDeSearch ); } void SendWidget::slotSelectedDevice( int name, int dev ) { qWarning("Start beam? %d %d", name, dev ); if ( name == m_irDeSearch ) { for (QMap<int, QString>::Iterator it= m_irDa.begin(); it != m_irDa.end(); ++it ) m_devBox->removeDevice( it.key() ); QCopEnvelope e2("QPE/IrDaApplet", "listDevices()"); } } void SendWidget::dispatchIrda( const QCString& str, const QByteArray& ar ) { qWarning("dispatch irda %s", str.data() ); if ( str == "devices(QStringList)" ) { QDataStream stream( ar, IO_ReadOnly ); QStringList list; stream >> list; slotIrDaDevices( list ); } } void SendWidget::dispatchBt( const QCString&, const QByteArray& ) { } void SendWidget::slotIrError( int ) { } void SendWidget::slotIrSent( bool b) { qWarning("irda sent!!"); QString text = b ? tr("Sent") : tr("Failure"); m_devBox->setStatus( m_irDaIt.key(), text ); ++m_irDaIt; slotStartIrda(); } void SendWidget::slotIrTry(unsigned int trI) { m_devBox->setStatus( m_irDaIt.key(), tr("Try %1").arg( QString::number( trI ) ) ); } void SendWidget::slotStartIrda() { if (m_irDaIt == m_irDa.end() ) { m_irDeSearch = m_devBox->addDevice(tr("Search again for IrDa."), DeviceBox::Search ); return; } m_devBox->setStatus( m_irDaIt.key(), tr("Start sending") ); m_obex->send( m_file ); } void SendWidget::closeEvent( QCloseEvent* e) { e->accept(); // make sure QTimer::singleShot(0, this, SLOT(slotDone() ) ); } void SendWidget::slotDone() { QCopEnvelope e0("QPE/IrDaApplet", "disableIrda()"); QCopEnvelope e1("QPE/Bluetooth", "disableBluetooth()"); emit done(); } QString SendWidget::file()const { return m_file; } DeviceBox::DeviceBox( QWidget* parent ) : QTextBrowser( parent ) { } DeviceBox::~DeviceBox() { } int DeviceBox::addDevice( const QString& name, int dev, const QString& status ) { /* return a id for a range of devices */ int id = idFor ( dev ); DeviceItem item( name, status, dev,id ); m_dev.insert( id, item ); setText( allText() ); return id; } void DeviceBox::removeDevice( int id ) { if (!m_dev.contains(id) ) return; m_dev.remove( id ); setText( allText() ); } void DeviceBox::setStatus( int id, const QString& status ) { if ( !m_dev.contains(id) ) return; m_dev[id].setStatus(status ); setText( allText() ); } void DeviceBox::setSource( const QString& str ) { qWarning("SetSource:%d", str.toInt() ); int id = str.toInt(); emit selectedDevice( id, m_dev[id].device() ); } int DeviceBox::idFor ( int id ) { static int irId = 1501; static int irBT = 1001; static int irSr = 501; static int irEr = 0; int ret = -1; switch(id ) { case IrDa: ret = irId; irId++; break; case BT: ret = irBT; irBT++; break; case Search: ret = irSr; irSr++; break; case Error: ret = irEr; irEr++; break; } return ret; } QString DeviceBox::allText() { QString str; typedef QMap<int, DeviceItem> DeviceMap; for (QMap<int, DeviceItem>::Iterator it = m_dev.begin(); it != m_dev.end(); ++it ) { str += it.data().toString() + "<br>"; } return str; } DeviceItem::DeviceItem( const QString& name, const QString& status, int dev, int id) { m_name = name; m_status = status; m_dev = dev; m_id = id; diff --git a/core/obex/receiver.cpp b/core/obex/receiver.cpp index 7d9f7ec..ee2668b 100644 --- a/core/obex/receiver.cpp +++ b/core/obex/receiver.cpp @@ -1,199 +1,199 @@ #include <sys/types.h> #include <sys/stat.h> #include <sys/mman.h> #include <stdlib.h> // int system #include <unistd.h> #include <fcntl.h> #include <qfileinfo.h> #include <qlabel.h> #include <qtextview.h> #include <qpushbutton.h> #include <qpe/applnk.h> #include <qpe/qpeapplication.h> #include <qpe/qcopenvelope_qws.h> #include "obex.h" #include "receiver.h" using namespace OpieObex; /* TRANSLATOR OpieObex::Receiver */ Receiver::Receiver() { m_obex = new Obex(this, "Receiver"); - connect(m_obex, SIGNAL(receivedFile(const QString& ) ), - this, SLOT(slotReceived(const QString& ) ) ); + connect(m_obex, SIGNAL(receivedFile(const QString&) ), + this, SLOT(slotReceived(const QString&) ) ); m_obex->receive(); } Receiver::~Receiver() { m_obex->setReceiveEnabled( false ); delete m_obex; } void Receiver::slotReceived( const QString& _file ) { QString file = _file; int check = checkFile(file); if ( check == AddressBook ) handleAddr( file ); else if ( check == Datebook ) handleDateTodo( file ); else handleOther( file ); } void Receiver::handleAddr( const QString& str ) { QCopEnvelope e("QPE/Application/addressbook", "setDocument(QString)" ); e << str; } /* we can not say for sure if it's a VEevent ot VTodo */ void Receiver::handleDateTodo( const QString& str ) { QCopEnvelope e0("QPE/Application/todolist", "setDocument(QString)"); e0 << str; QCopEnvelope e1("QPE/Application/datebook", "setDocument(QString)" ); e1 << str; } /* * Handle other asks if it should accept the * beamed object and creates a DocLnk */ void Receiver::handleOther( const QString& other ) { OtherHandler* hand = new OtherHandler(); hand->handle( other ); } void Receiver::tidyUp( QString& _file, const QString& ending) { /* libversit fails on BASE64 encoding we try to sed it away */ QString file = _file; char foo[24]; // big enough (void)::strcpy(foo, "/tmp/opie-XXXXXX"); int fd = ::mkstemp(foo); if ( fd == -1 ) return; (void)::strncat( foo, ending.latin1(), 4 ); _file = QString::fromLatin1( foo ); QString cmd = QString("sed -e \"s/^\\(X-MICROSOFT-BODYINK\\)\\;/\\1:/;\" < %2 > %2 ").arg( Global::shellQuote(file)).arg( Global::shellQuote(_file) ); qWarning("Executing: %s", cmd.latin1() ); (void)::system( cmd.latin1() ); cmd = QString("rm %1").arg( Global::shellQuote(file) ); (void)::system( cmd.latin1() ); } int Receiver::checkFile( QString& file ) { qWarning("check file!! %s", file.latin1() ); int ret; QString ending; if (file.right(4) == ".vcs" ) { ret = Datebook; ending = QString::fromLatin1(".vcs"); }else if ( file.right(4) == ".vcf") { ret = AddressBook; ending = QString::fromLatin1(".vcf"); }else ret = Other; if (ending.isEmpty() ) return ret; /** * currently the parser is broken in regard of BASE64 encoding * and M$ likes to send that. So we will executed a small * tidy up system sed script * At this point we can also remove umlaute from the filename */ tidyUp( file, ending ); qWarning("check it now %d", ret ); return ret; } /* TRANSLATOR OpieObex::OtherHandler */ OtherHandler::OtherHandler() : QVBox() { QHBox* box = new QHBox(this); QLabel* lbl = new QLabel(box); lbl->setText(tr("<qt><b>Received:</b></qt>")); m_na = new QLabel(box); QFrame* frame = new QFrame(this); frame->setFrameShape( QFrame::HLine ); frame->setFrameShadow( QFrame::Sunken ); m_view = new QTextView(this); box = new QHBox(this); QPushButton *but = new QPushButton(box); but->setText(tr("Accept") ); connect(but, SIGNAL(clicked() ), this, SLOT(accept()) ); but = new QPushButton(box); but->setText(tr("Deny") ); connect(but, SIGNAL(clicked() ), this, SLOT(deny() ) ); raise(); showMaximized(); } OtherHandler::~OtherHandler() { } void OtherHandler::handle( const QString& file ) { m_file = file; m_na->setText(file); DocLnk lnk(file); qWarning(" %s %s", lnk.type().latin1(), lnk.icon().latin1() ); QString str = tr("<p>You received a file of type %1 (<img src=\"%2\"> )What do you want to do?").arg(lnk.type() ).arg(lnk.icon() ); m_view->setText( str ); } /* * hehe evil evil mmap ahead :) * we quickly copy the file and then we'll create a DocLnk for it */ void OtherHandler::accept() { QString na = targetName( m_file ); copy(m_file, na ); DocLnk lnk(na); lnk.writeLink(); QFile::remove(m_file); delete this; } void OtherHandler::deny() { QFile::remove( m_file ); delete this; } QString OtherHandler::targetName( const QString& file ) { QFileInfo info( file ); /* $HOME needs to be set!!!! */ Global::createDocDir(); QString newFile = QPEApplication::documentDir()+ "/"+ info.baseName(); QString newFileBase = newFile; int trie = 0; while (QFile::exists(newFile + "."+info.extension() ) ) { newFile = newFileBase + "_"+QString::number(trie) ; trie++; } newFile += "." + info.extension(); return newFile; } /* fast cpy */ void OtherHandler::copy(const QString& src, const QString& file) { qWarning("src %s, dest %s", src.latin1(),file.latin1() ); QString cmd = QString("mv %1 %2").arg( Global::shellQuote( src )). arg( Global::shellQuote( file ) ); ::system( cmd.latin1() ); // done } diff --git a/core/opie-login/loginwindowimpl.cpp b/core/opie-login/loginwindowimpl.cpp index 3037ba3..e1b9360 100644 --- a/core/opie-login/loginwindowimpl.cpp +++ b/core/opie-login/loginwindowimpl.cpp @@ -1,250 +1,250 @@ /* =. This file is part of the OPIE Project .=l. Copyright (c) 2002 Robert Griebl <sandman@handhelds.org> .>+-= _;:, .> :=|. This file is free software; you can .> <`_, > . <= redistribute it and/or modify it under :`=1 )Y*s>-.-- : the terms of the GNU General Public .="- .-=="i, .._ License as published by the Free Software - . .-<_> .<> Foundation; either version 2 of the License, ._= =} : or (at your option) any later version. .%`+i> _;_. .i_,=:_. -<s. This file 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 General ..}^=.= = ; Public License for more details. ++= -. .` .: : = ...= . :.=- You should have received a copy of the GNU -. .:....=;==+<; General Public License along with this file; -_. . . )=. = see the file COPYING. If not, write to the -- :-=` Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include <qpe/version.h> #include <qpushbutton.h> #include <qlayout.h> #include <qlineedit.h> #include <qtimer.h> #include <qcombobox.h> #include <qlabel.h> #include <qpopupmenu.h> #include <qmessagebox.h> #if QT_VERSION < 300 #include <qgfx_qws.h> #endif #include <qwindowsystem_qws.h> #include <qpe/resource.h> #include <qpe/qcopenvelope_qws.h> #include <qpe/config.h> #include <opie/odevice.h> #include <stdio.h> #include <stdlib.h> #include "loginwindowimpl.h" #include "loginapplication.h" #include "inputmethods.h" using namespace Opie; LoginWindowImpl::LoginWindowImpl ( ) : LoginWindow ( 0, "LOGIN-WINDOW", WStyle_Customize | WStyle_NoBorder | WDestructiveClose ) { QPopupMenu *pop = new QPopupMenu ( this ); - pop-> insertItem ( tr( "Restart" ), this, SLOT( restart ( ))); - pop-> insertItem ( tr( "Quit" ), this, SLOT( quit ( ))); + pop-> insertItem ( tr( "Restart" ), this, SLOT( restart())); + pop-> insertItem ( tr( "Quit" ), this, SLOT( quit())); m_menu-> setPopup ( pop ); QCopChannel *channel = new QCopChannel ( "QPE/TaskBar", this ); - connect ( channel, SIGNAL( received ( const QCString &, const QByteArray & )), this, SLOT( receive ( const QCString &, const QByteArray & ))); + connect ( channel, SIGNAL( received(const QCString&,const QByteArray&)), this, SLOT( receive(const QCString&,const QByteArray&))); QHBoxLayout *lay = new QHBoxLayout ( m_taskbar, 4, 4 ); m_input = new InputMethods ( m_taskbar ); - connect ( m_input, SIGNAL( inputToggled ( bool )), this, SLOT( calcMaxWindowRect ( ))); + connect ( m_input, SIGNAL( inputToggled(bool)), this, SLOT( calcMaxWindowRect())); lay-> addWidget ( m_input ); lay-> addStretch ( 10 ); setActiveWindow ( ); m_password-> setFocus ( ); m_user-> insertStringList ( lApp-> allUsers ( )); //there is no point in displaying the IM for a zaurus if (ODevice::inst ( )-> series ( ) != Model_Zaurus){ - QTimer::singleShot ( 0, this, SLOT( showIM ( ))); + QTimer::singleShot ( 0, this, SLOT( showIM())); } QString opiedir = ::getenv ( "OPIEDIR" ); QPixmap bgpix ( opiedir + "/pics/launcher/opie-background.jpg" ); if ( !bgpix. isNull ( )) { setBackgroundPixmap ( bgpix ); m_caption-> setBackgroundPixmap ( bgpix); TextLabel1-> setBackgroundPixmap ( bgpix); TextLabel2-> setBackgroundPixmap ( bgpix); } m_caption-> setText ( tr("<center>Welcome to OPIE %1</center><center>& %2 %3</center>"). arg(QPE_VERSION). arg ( ODevice::inst ( )-> systemString ( )). arg ( ODevice::inst ( )-> systemVersionString ( ))); Config cfg ( "opie-login" ); cfg. setGroup ( "General" ); QString last = cfg. readEntry ( "LastLogin" ); if ( !last. isEmpty ( )) m_user-> setEditText ( last ); calcMaxWindowRect ( ); } LoginWindowImpl::~LoginWindowImpl ( ) { } void LoginWindowImpl::receive ( const QCString &msg, const QByteArray &data ) { QDataStream stream ( data, IO_ReadOnly ); if ( msg == "hideInputMethod()" ) m_input-> hideInputMethod ( ); else if ( msg == "showInputMethod()" ) m_input-> showInputMethod ( ); else if ( msg == "reloadInputMethods()" ) m_input-> loadInputMethods ( ); } void LoginWindowImpl::calcMaxWindowRect ( ) { #ifdef Q_WS_QWS QRect wr; int displayWidth = qApp-> desktop ( )-> width ( ); QRect ir = m_input-> inputRect ( ); if ( ir.isValid() ) wr.setCoords( 0, 0, displayWidth-1, ir.top()-1 ); else wr.setCoords( 0, 0, displayWidth-1, m_taskbar->y()-1 ); #if QT_VERSION < 300 wr = qt_screen-> mapToDevice ( wr, QSize ( qt_screen-> width ( ), qt_screen-> height ( ))); #endif QWSServer::setMaxWindowRect( wr ); #endif } void LoginWindowImpl::keyPressEvent ( QKeyEvent *e ) { switch ( e-> key ( )) { case HardKey_Suspend: suspend ( ); break; case HardKey_Backlight: backlight ( ); break; default: e-> ignore ( ); break; } LoginWindow::keyPressEvent ( e ); } void LoginWindowImpl::toggleEchoMode ( bool t ) { m_password-> setEchoMode ( t ? QLineEdit::Normal : QLineEdit::Password ); } void LoginWindowImpl::showIM ( ) { m_input-> showInputMethod ( ); } void LoginWindowImpl::restart ( ) { qApp-> quit ( ); } void LoginWindowImpl::quit ( ) { lApp-> quitToConsole ( ); } void LoginWindowImpl::suspend ( ) { ODevice::inst ( )-> suspend ( ); QCopEnvelope e("QPE/System", "setBacklight(int)"); e << -3; // Force on } void LoginWindowImpl::backlight ( ) { QCopEnvelope e("QPE/System", "setBacklight(int)"); e << -2; // toggle } class WaitLogo : public QLabel { public: WaitLogo ( ) : QLabel ( 0, "wait hack!", WStyle_Customize | WStyle_NoBorder | WStyle_Tool ) { QImage img = Resource::loadImage ( "launcher/new_wait" ); QPixmap pix; pix. convertFromImage ( img ); setPixmap ( pix ); setAlignment ( AlignCenter ); move ( 0, 0 ); resize ( qApp-> desktop ( )-> width ( ), qApp-> desktop ( )-> height ( )); m_visible = false; show ( ); } virtual void showEvent ( QShowEvent *e ) { QLabel::showEvent ( e ); m_visible = true; } virtual void paintEvent ( QPaintEvent *e ) { QLabel::paintEvent ( e ); if ( m_visible ) qApp-> quit ( ); } private: bool m_visible; }; void LoginWindowImpl::login ( ) { const char *user = ::strdup ( m_user-> currentText ( ). local8Bit ( )); const char *pass = ::strdup ( m_password-> text ( ). local8Bit ( )); if ( !user || !user [0] ) return; if ( !pass ) pass = ""; if ( lApp-> checkPassword ( user, pass )) { Config cfg ( "opie-login" ); cfg. setGroup ( "General" ); cfg. writeEntry ( "LastLogin", user ); cfg. write ( ); lApp-> setLoginAs ( user ); // Draw a big wait icon, the image can be altered in later revisions m_input-> hideInputMethod ( ); new WaitLogo ( ); // WaitLogo::showEvent() calls qApp-> quit() } else { QMessageBox::warning ( this, tr( "Wrong password" ), tr( "The given password is incorrect." )); m_password-> clear ( ); } } diff --git a/core/opie-login/main.cpp b/core/opie-login/main.cpp index 7d5792e..8d0976f 100644 --- a/core/opie-login/main.cpp +++ b/core/opie-login/main.cpp @@ -1,366 +1,366 @@ /* =. This file is part of the OPIE Project .=l. Copyright (c) 2002 Robert Griebl <sandman@handhelds.org> .>+-= _;:, .> :=|. This file is free software; you can .> <`_, > . <= redistribute it and/or modify it under :`=1 )Y*s>-.-- : the terms of the GNU General Public .="- .-=="i, .._ License as published by the Free Software - . .-<_> .<> Foundation; either version 2 of the License, ._= =} : or (at your option) any later version. .%`+i> _;_. .i_,=:_. -<s. This file 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 General ..}^=.= = ; Public License for more details. ++= -. .` .: : = ...= . :.=- You should have received a copy of the GNU -. .:....=;==+<; General Public License along with this file; -_. . . )=. = see the file COPYING. If not, write to the -- :-=` Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include "loginapplication.h" #include "loginwindowimpl.h" #include "calibrate.h" /* OPIE */ #include <opie2/odevice.h> #include <qpe/qpestyle.h> #include <qpe/power.h> #include <qpe/config.h> /* QT */ #include <qwindowsystem_qws.h> #include <qmessagebox.h> #include <qlabel.h> #include <qtimer.h> #include <qfile.h> /* STD */ #include <sys/types.h> #include <time.h> #include <sys/time.h> #include <sys/resource.h> #include <unistd.h> #include <syslog.h> #include <sys/wait.h> #include <stdio.h> #include <stdlib.h> #include <signal.h> #include <getopt.h> #include <string.h> using namespace Opie; int login_main ( int argc, char **argv, pid_t ppid ); void sigterm ( int sig ); void sigint ( int sig ); void exit_closelog ( ); static struct option long_options [] = { { "autologin", 1, 0, 'a' }, { 0, 0, 0, 0 } }; int main ( int argc, char **argv ) { int userExited = 0; pid_t ppid = ::getpid ( ); if ( ::geteuid ( ) != 0 ) { ::fprintf ( stderr, "%s can only be executed by root. (or chmod +s)", argv [0] ); return 1; } if ( ::getuid ( ) != 0 ) // qt doesn't really like SUID and ::setuid ( 0 ); // messes up things like config files char *autolog = 0; int c; while (( c = ::getopt_long ( argc, argv, "a:", long_options, 0 )) != -1 ) { switch ( c ) { case 'a': autolog = optarg; break; default: ::fprintf ( stderr, "Usage: %s [-a|--autologin=<user>]\n", argv [0] ); return 2; } } // struct rlimit rl; // ::getrlimit ( RLIMIT_NOFILE, &rl ); // for ( unsigned int i = 0; i < rl. rlim_cur; i++ ) // ::close ( i ); ::setpgid ( 0, 0 ); ::setsid ( ); ::signal ( SIGTERM, sigterm ); ::signal ( SIGINT, sigterm ); ::openlog ( "opie-login", LOG_CONS, LOG_AUTHPRIV ); ::atexit ( exit_closelog ); while ( true ) { pid_t child = ::fork ( ); if ( child < 0 ) { ::syslog ( LOG_ERR, "Could not fork GUI process\n" ); break; } else if ( child > 0 ) { int status = 0; time_t started = ::time ( 0 ); while ( ::waitpid ( child, &status, 0 ) < 0 ) { } LoginApplication::logout ( ); if (( ::time ( 0 ) - started ) < 3 ) { if ( autolog ) { ::syslog ( LOG_ERR, "Respawning too fast -- disabling auto-login\n" ); autolog = 0; } else { ::syslog ( LOG_ERR, "Respawning too fast -- going down\n" ); break; } } int killedbysig = 0; userExited=0; if (WIFEXITED(status)!=0 ) { if (WEXITSTATUS(status)==137) { userExited=1; } } if ( WIFSIGNALED( status )) { switch ( WTERMSIG( status )) { case SIGTERM: case SIGINT : case SIGKILL: break; default : killedbysig = WTERMSIG( status ); break; } } if ( killedbysig ) { // qpe was killed by an uncaught signal qApp = 0; ::syslog ( LOG_ERR, "Opie was killed by a signal #%d", killedbysig ); QWSServer::setDesktopBackground ( QImage ( )); QApplication *app = new QApplication ( argc, argv, QApplication::GuiServer ); app-> setFont ( QFont ( "Helvetica", 10 )); app-> setStyle ( new QPEStyle ( )); const char *sig = ::strsignal ( killedbysig ); QLabel *l = new QLabel ( 0, "sig", Qt::WStyle_Customize | Qt::WStyle_NoBorder | Qt::WStyle_Tool ); l-> setText ( LoginWindowImpl::tr( "Opie was terminated\nby an uncaught signal\n(%1)\n" ). arg ( sig )); l-> setAlignment ( Qt::AlignCenter ); l-> move ( 0, 0 ); l-> resize ( app-> desktop ( )-> width ( ), app-> desktop ( )-> height ( )); l-> show ( ); - QTimer::singleShot ( 3000, app, SLOT( quit ( ))); + QTimer::singleShot ( 3000, app, SLOT( quit())); app-> exec ( ); delete app; qApp = 0; } } else { if ( !autolog ) { QString confFile=QPEApplication::qpeDir() + "/etc/opie-login.conf"; Config cfg ( confFile, Config::File ); cfg. setGroup ( "General" ); QString user = cfg. readEntry ( "AutoLogin" ); if ( !user. isEmpty ( )) autolog = ::strdup ( user. latin1 ( )); } if ( autolog && !userExited ) { QWSServer::setDesktopBackground( QImage() ); ODevice::inst ( )-> setDisplayStatus ( true ); ODevice::inst ( )-> setSoftSuspend ( false ); LoginApplication *app = new LoginApplication ( argc, argv, ppid ); LoginApplication::setLoginAs ( autolog ); if ( LoginApplication::changeIdentity ( )) ::exit ( LoginApplication::login ( )); else ::exit ( 0 ); } else { ::exit ( login_main ( argc, argv, ppid )); } } } return 0; } void sigterm ( int /*sig*/ ) { ::exit ( 0 ); } void exit_closelog ( ) { ::closelog ( ); } class LoginScreenSaver : public QWSScreenSaver { public: LoginScreenSaver ( ) { m_lcd_status = true; m_backlight_bright = -1; m_backlight_forcedoff = false; // Make sure the LCD is in fact on, (if opie was killed while the LCD is off it would still be off) ODevice::inst ( )-> setDisplayStatus ( true ); } void restore() { if ( !m_lcd_status ) // We must have turned it off ODevice::inst ( ) -> setDisplayStatus ( true ); setBacklight ( -3 ); } bool save( int level ) { switch ( level ) { case 0: if ( backlight() > 1 ) setBacklight( 1 ); // lowest non-off return true; break; case 1: setBacklight( 0 ); // off return true; break; case 2: // We're going to suspend the whole machine if ( PowerStatusManager::readStatus().acStatus() != PowerStatus::Online ) { QWSServer::sendKeyEvent( 0xffff, Qt::Key_F34, FALSE, TRUE, FALSE ); return true; } break; } return false; } private: public: void setIntervals( int i1 = 30, int i2 = 20, int i3 = 60 ) { int v [4]; v [ 0 ] = QMAX( 1000 * i1, 100 ); v [ 1 ] = QMAX( 1000 * i2, 100 ); v [ 2 ] = QMAX( 1000 * i3, 100 ); v [ 3 ] = 0; if ( !i1 && !i2 && !i3 ) QWSServer::setScreenSaverInterval ( 0 ); else QWSServer::setScreenSaverIntervals ( v ); } int backlight ( ) { if ( m_backlight_bright == -1 ) m_backlight_bright = 255; return m_backlight_bright; } void setBacklight ( int bright ) { if ( bright == -3 ) { // Forced on m_backlight_forcedoff = false; bright = -1; } if ( m_backlight_forcedoff && bright != -2 ) return ; if ( bright == -2 ) { // Toggle between off and on bright = m_backlight_bright ? 0 : -1; m_backlight_forcedoff = !bright; } m_backlight_bright = bright; bright = backlight ( ); ODevice::inst ( ) -> setDisplayBrightness ( bright ); m_backlight_bright = bright; } private: bool m_lcd_status; int m_backlight_bright; bool m_backlight_forcedoff; }; namespace Opie { extern int force_appearance; } // HACK to get around the force-style setting int login_main ( int argc, char **argv, pid_t ppid ) { QWSServer::setDesktopBackground( QImage() ); LoginApplication *app = new LoginApplication ( argc, argv, ppid ); Opie::force_appearance = 0; app-> setFont ( QFont ( "Helvetica", 10 )); app-> setStyle ( new QPEStyle ( )); ODevice::inst ( )-> setSoftSuspend ( true ); if ( QWSServer::mouseHandler() && QWSServer::mouseHandler() ->inherits("QCalibratedMouseHandler") ) { if ( !QFile::exists ( "/etc/pointercal" )) { // Make sure calibration widget starts on top. Calibrate *cal = new Calibrate; cal-> exec ( ); delete cal; } } LoginScreenSaver *saver = new LoginScreenSaver; saver-> setIntervals ( ); QWSServer::setScreenSaver ( saver ); saver-> restore ( ); LoginWindowImpl *lw = new LoginWindowImpl ( ); app-> setMainWidget ( lw ); lw-> setGeometry ( 0, 0, app-> desktop ( )-> width ( ), app-> desktop ( )-> height ( )); lw-> show ( ); int rc = app-> exec ( ); ODevice::inst ( )-> setSoftSuspend ( false ); if ( app-> loginAs ( )) { if ( app-> changeIdentity ( )) { diff --git a/core/pim/addressbook/abtable.cpp b/core/pim/addressbook/abtable.cpp index f7bff58..29f4383 100644 --- a/core/pim/addressbook/abtable.cpp +++ b/core/pim/addressbook/abtable.cpp @@ -1,322 +1,322 @@ /********************************************************************** ** Copyright (C) 2000 Trolltech AS. All rights reserved. ** Copyright (c) 2002 Stefan Eilers (eilers.stefan@epost.de) ** ** This file is part of Qt Palmtop Environment. ** ** This file may be distributed and/or modified under the terms of the ** GNU General Public License version 2 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. ** ** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE ** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. ** ** See http://www.trolltech.com/gpl/ for GPL licensing information. ** ** Contact info@trolltech.com if any conditions of this licensing are ** not clear to you. ** **********************************************************************/ #include <qpe/timestring.h> #include <qpe/resource.h> #include <opie/orecordlist.h> #include "abtable.h" #include <errno.h> #include <fcntl.h> #include <unistd.h> #include <stdlib.h> #include <ctype.h> //toupper() for key hack #if 0 /*! \class AbTableItem abtable.h \brief QTableItem based class for showing a field of an entry */ AbTableItem::AbTableItem( QTable *t, EditType et, const QString &s, const QString &secondSortKey) : QTableItem( t, et, s ) { // sortKey = s.lower() + QChar( '\0' ) + secondSortKey.lower(); sortKey = Qtopia::buildSortKey( s, secondSortKey ); } int AbTableItem::alignment() const { return AlignLeft|AlignVCenter; } QString AbTableItem::key() const { return sortKey; } // A way to reset the item, without out doing a delete or a new... void AbTableItem::setItem( const QString &txt, const QString &secondKey ) { setText( txt ); sortKey = Qtopia::buildSortKey( txt, secondKey ); // sortKey = txt.lower() + QChar( '\0' ) + secondKey.lower(); } /*! \class AbPickItem abtable.h \brief QTableItem based class for showing slection of an entry */ AbPickItem::AbPickItem( QTable *t ) : QTableItem(t, WhenCurrent, "?") { } QWidget *AbPickItem::createEditor() const { QComboBox* combo = new QComboBox( table()->viewport() ); ( (AbPickItem*)this )->cb = combo; AbTable* t = static_cast<AbTable*>(table()); QStringList c = t->choiceNames(); int cur = 0; for (QStringList::ConstIterator it = c.begin(); it!=c.end(); ++it) { if ( *it == text() ) cur = combo->count(); combo->insertItem(*it); } combo->setCurrentItem(cur); return combo; } void AbPickItem::setContentFromEditor( QWidget *w ) { if ( w->inherits("QComboBox") ) setText( ( (QComboBox*)w )->currentText() ); else QTableItem::setContentFromEditor( w ); } #endif /*! \class AbTable abtable.h \brief QTable based class for showing a list of entries */ AbTable::AbTable( const QValueList<int> order, QWidget *parent, const char *name ) : QTable( parent, name ), lastSortCol( -1 ), asc( TRUE ), intFields( order ), enablePainting( true ), columnVisible( true ), countNested( 0 ) { // qWarning("C'tor start"); setSelectionMode( NoSelection ); init(); setSorting( TRUE ); - connect( this, SIGNAL(clicked(int,int,int,const QPoint &)), + connect( this, SIGNAL(clicked(int,int,int,const QPoint&)), this, SLOT(itemClicked(int,int)) ); // contactList.clear(); // qWarning("C'tor end"); } AbTable::~AbTable() { } void AbTable::init() { // :SX showChar = '\0'; setNumRows( 0 ); setNumCols( 2 ); horizontalHeader()->setLabel( 0, tr( "Full Name" )); horizontalHeader()->setLabel( 1, tr( "Contact" )); setLeftMargin( 0 ); verticalHeader()->hide(); columnVisible = true; } void AbTable::setContacts( const OContactAccess::List& viewList ) { qWarning("AbTable::setContacts()"); clear(); m_viewList = viewList; setSorting( false ); setPaintingEnabled( FALSE ); OContactAccess::List::Iterator it; setNumRows( m_viewList.count() ); // int row = 0; // for ( it = m_viewList.begin(); it != m_viewList.end(); ++it ) // insertIntoTable( *it, row++ ); // setSorting( true ); // resort(); updateVisible(); setPaintingEnabled( TRUE ); } void AbTable::setOrderedList( const QValueList<int> ordered ) { intFields = ordered; } bool AbTable::selectContact( int UID ) { qWarning( "AbTable::selectContact( %d )", UID ); int rows = numRows(); OContact* foundContact = 0l; bool found = false; setPaintingEnabled( FALSE ); qWarning( "search start" ); for ( int r = 0; r < rows; ++r ) { if ( m_viewList.uidAt( r ) == UID ){ ensureCellVisible( r, 0 ); setCurrentCell( r, 0 ); found = true; break; } } qWarning( "search end" ); if ( !found ){ ensureCellVisible( 0,0 ); setCurrentCell( 0, 0 ); } setPaintingEnabled( TRUE ); return true; } #if 0 void AbTable::insertIntoTable( const OContact& cnt, int row ) { qWarning( "void AbTable::insertIntoTable( const OContact& cnt, %d )", row ); QString strName; ContactItem contactItem; strName = findContactName( cnt ); contactItem = findContactContact( cnt, row ); AbTableItem *ati; ati = new AbTableItem( this, QTableItem::Never, strName, contactItem.value ); contactList.insert( ati, cnt ); setItem( row, 0, ati ); ati = new AbTableItem( this, QTableItem::Never, contactItem.value, strName); if ( !contactItem.icon.isNull() ) ati->setPixmap( contactItem.icon ); setItem( row, 1, ati ); //### cannot do this; table only has two columns at this point // setItem( row, 2, new AbPickItem( this ) ); } #endif void AbTable::columnClicked( int col ) { if ( !sorting() ) return; if ( lastSortCol == -1 ) lastSortCol = col; if ( col == lastSortCol ) { asc = !asc; } else { lastSortCol = col; asc = TRUE; } //QMessageBox::information( this, "resort", "columnClicked" ); resort(); } void AbTable::resort() { qWarning( "void AbTable::resort() NOT POSSIBLE !!" ); #if 0 setPaintingEnabled( FALSE ); if ( sorting() ) { if ( lastSortCol == -1 ) lastSortCol = 0; sortColumn( lastSortCol, asc, TRUE ); //QMessageBox::information( this, "resort", "resort" ); updateVisible(); } setPaintingEnabled( TRUE ); #endif } OContact AbTable::currentEntry() { return m_viewList[currentRow()]; } int AbTable::currentEntry_UID() { return ( currentEntry().uid() ); } void AbTable::clear() { qWarning( "void AbTable::clear()" ); // contactList.clear(); setPaintingEnabled( FALSE ); for ( int r = 0; r < numRows(); ++r ) { for ( int c = 0; c < numCols(); ++c ) { if ( cellWidget( r, c ) ) clearCellWidget( r, c ); clearCell( r, c ); } } setNumRows( 0 ); setPaintingEnabled( TRUE ); } // Refresh updates column 2 if the contactsettings changed void AbTable::refresh() { qWarning( "void AbTable::refresh() NOT IMPLEMENTED !!" ); #if 0 int rows = numRows(); AbTableItem *abi; ContactItem contactItem; setPaintingEnabled( FALSE ); for ( int r = 0; r < rows; ++r ) { abi = static_cast<AbTableItem*>( item(r, 0) ); contactItem = findContactContact( contactList[abi], r ); static_cast<AbTableItem*>( item(r, 1) )->setItem( contactItem.value, abi->text() ); if ( !contactItem.icon.isNull() ){ static_cast<AbTableItem*>( item(r, 1) )-> setPixmap( contactItem.icon ); }else{ static_cast<AbTableItem*>( item(r, 1) )-> setPixmap( QPixmap() ); diff --git a/core/pim/addressbook/abview.cpp b/core/pim/addressbook/abview.cpp index 670cdb0..8d61582 100644 --- a/core/pim/addressbook/abview.cpp +++ b/core/pim/addressbook/abview.cpp @@ -1,275 +1,275 @@ /********************************************************************** ** Copyright (c) 2002 Stefan Eilers (eilers.stefan@epost.de) ** ** This file is part of Qt Palmtop Environment. ** ** This file may be distributed and/or modified under the terms of the ** GNU General Public License version 2 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. ** ** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE ** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. ** ** **********************************************************************/ #include "abview.h" #include <qlayout.h> #include <qpe/global.h> #include <opie/ocontactaccessbackend_vcard.h> #include <assert.h> // Is defined in LibQPE extern QString categoryFileName(); QString addressbookPersonalVCardName() { QString filename = Global::applicationFileName("addressbook", "businesscard.vcf"); return filename; } AbView::AbView ( QWidget* parent, const QValueList<int>& ordered ): QWidget(parent), mCat(0), m_inSearch( false ), m_inPersonal( false ), m_curr_category( -1 ), m_curr_View( TableView ), m_prev_View( TableView ), m_curr_Contact ( 0 ), m_contactdb ( 0l ), m_storedDB ( 0l ), m_viewStack( 0l ), m_abTable( 0l ), m_orderedFields( ordered ) { qWarning("AbView::c'tor"); // Load default database and handle syncing myself.. ! m_contactdb = new OContactAccess ( "addressbook", 0l, 0l, false ); m_contactdb -> setReadAhead( 16 ); // Use ReadAhead-Cache if available mCat.load( categoryFileName() ); // Create Layout and put WidgetStack into it. QVBoxLayout *vb = new QVBoxLayout( this ); m_viewStack = new QWidgetStack( this ); vb->addWidget( m_viewStack ); // Creat TableView QVBox* tableBox = new QVBox( m_viewStack ); m_abTable = new AbTable( m_orderedFields, tableBox, "table" ); m_abTable->setCurrentCell( 0, 0 ); m_abTable->setFocus(); // Add TableView to WidgetStack and raise it m_viewStack -> addWidget( tableBox , TableView ); // Create CardView and add it to WidgetStack QVBox* cardBox = new QVBox( m_viewStack ); m_ablabel = new AbLabel( cardBox, "CardView"); m_viewStack -> addWidget( cardBox , CardView ); // Connect views to me - connect ( m_abTable, SIGNAL( signalSwitch( void ) ), - this, SLOT( slotSwitch( void ) ) ); - connect ( m_ablabel, SIGNAL( signalOkPressed( void ) ), - this, SLOT( slotSwitch( void ) ) ); + connect ( m_abTable, SIGNAL( signalSwitch(void) ), + this, SLOT( slotSwitch(void) ) ); + connect ( m_ablabel, SIGNAL( signalOkPressed(void) ), + this, SLOT( slotSwitch(void) ) ); load(); } AbView::~AbView() { m_contactdb -> save(); delete m_contactdb; if ( m_storedDB ){ m_storedDB -> save(); delete m_storedDB; } } void AbView::setView( Views view ) { qWarning("AbView::setView( Views view )"); m_curr_View = view; load(); } void AbView::addEntry( const OContact &newContact ) { qWarning("abview:AddContact"); m_contactdb->add ( newContact ); load(); } void AbView::removeEntry( const int UID ) { qWarning("abview:RemoveContact"); m_contactdb->remove( UID ); load(); } void AbView::replaceEntry( const OContact &contact ) { qWarning("abview:ReplaceContact"); m_contactdb->replace( contact ); load(); } OContact AbView::currentEntry() { OContact currentContact; switch ( (int) m_curr_View ) { case TableView: currentContact = m_abTable -> currentEntry(); break; case CardView: currentContact = m_ablabel -> currentEntry(); break; } m_curr_Contact = currentContact.uid(); return currentContact; } bool AbView::save() { // qWarning("abView:Save data"); return m_contactdb->save(); } void AbView::load() { qWarning("abView:Load data"); // Letter Search is stopped at this place emit signalClearLetterPicker(); if ( m_inPersonal ) // VCard Backend does not sort.. m_list = m_contactdb->allRecords(); else{ m_list = m_contactdb->sorted( true, 0, 0, 0 ); if ( m_curr_category != -1 ) clearForCategory(); } qWarning ("Number of contacts: %d", m_list.count()); updateView( true ); } void AbView::reload() { qWarning( "void AbView::reload()" ); m_contactdb->reload(); load(); } void AbView::clear() { // :SX } void AbView::setShowByCategory( const QString& cat ) { qWarning("AbView::setShowCategory( const QString& cat )"); int intCat = 0; // All (cat == NULL) will be stored as -1 if ( cat.isNull() ) intCat = -1; else intCat = mCat.id("Contacts", cat ); // Just do anything if we really change the category if ( intCat != m_curr_category ){ // qWarning ("Categories: Selected %s.. Number: %d", cat.latin1(), m_curr_category); m_curr_category = intCat; emit signalClearLetterPicker(); load(); } } void AbView::setShowToView( Views view ) { qWarning("void AbView::setShowToView( View %d )", view); if ( m_curr_View != view ){ qWarning ("Change the View (Category is: %d)", m_curr_category); m_prev_View = m_curr_View; m_curr_View = view; updateView(); } } void AbView::setShowByLetter( char c, AbConfig::LPSearchMode mode ) { qWarning("void AbView::setShowByLetter( %c, %d )", c, mode ); assert( mode < AbConfig::LASTELEMENT ); OContact query; if ( c == 0 ){ load(); return; }else{ // If the current Backend is unable to solve the query, we will // ignore the request .. if ( ! m_contactdb->hasQuerySettings( OContactAccess::WildCards | OContactAccess::IgnoreCase ) ){ return; } switch( mode ){ case AbConfig::LastName: query.setLastName( QString("%1*").arg(c) ); break; case AbConfig::FileAs: query.setFileAs( QString("%1*").arg(c) ); break; default: qWarning( "Unknown Searchmode for AbView::setShowByLetter ! -> %d", mode ); qWarning( "I will ignore it.." ); return; } m_list = m_contactdb->queryByExample( query, OContactAccess::WildCards | OContactAccess::IgnoreCase ); if ( m_curr_category != -1 ) clearForCategory(); m_curr_Contact = 0; } updateView( true ); } void AbView::setListOrder( const QValueList<int>& ordered ) { m_orderedFields = ordered; if ( m_abTable ){ m_abTable->setOrderedList( ordered ); m_abTable->refresh(); } updateView(); } QString AbView::showCategory() const { return mCat.label( "Contacts", m_curr_category ); diff --git a/core/pim/addressbook/addressbook.cpp b/core/pim/addressbook/addressbook.cpp index 9cf55b3..8a5f9d5 100644 --- a/core/pim/addressbook/addressbook.cpp +++ b/core/pim/addressbook/addressbook.cpp @@ -1,868 +1,868 @@ /********************************************************************** ** Copyright (C) 2000 Trolltech AS. All rights reserved. ** Copyright (C) 2003 Stefan Eilers (eilers.stefan@epost.de) ** ** This file is part of the Open Palmtop Environment (see www.opie.info). ** ** This file may be distributed and/or modified under the terms of the ** GNU General Public License version 2 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. ** ** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE ** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. ** ** See http://www.trolltech.com/gpl/ for GPL licensing information. ** ** **********************************************************************/ #define QTOPIA_INTERNAL_FD // #include "addresssettings.h" #include "addressbook.h" #include <opie/ofileselector.h> #include <opie/ofiledialog.h> #include <opie/ocontact.h> #include <opie/ocontactaccessbackend_vcard.h> #include <qpe/resource.h> #include <qpe/ir.h> #include <qpe/qpemessagebox.h> #include <qmenubar.h> // #include <qtoolbar.h> // #include <qmenubar.h> #include <qpe/qpeapplication.h> #include <qaction.h> #include <qlayout.h> #include <qmessagebox.h> #include <qtoolbutton.h> #include <stdlib.h> #include <sys/stat.h> #include <sys/types.h> #include <fcntl.h> #include <unistd.h> #include "picker.h" #include "configdlg.h" extern QString addressbookPersonalVCardName(); AddressbookWindow::AddressbookWindow( QWidget *parent, const char *name, WFlags f ) : QMainWindow( parent, name, f ), catMenu (0l), abEditor(0l), syncing(FALSE), m_tableViewButton(0l), m_cardViewButton(0l) { isLoading = true; m_config.load(); setCaption( tr("Contacts") ); setIcon( Resource::loadPixmap( "AddressBook" ) ); // Settings for Main Menu // setToolBarsMovable( false ); setToolBarsMovable( !m_config.fixedBars() ); setRightJustification( true ); QToolBar *bar = new QToolBar( this ); bar->setHorizontalStretchable( TRUE ); QMenuBar *mbList = new QMenuBar( bar ); mbList->setMargin( 0 ); QPopupMenu *edit = new QPopupMenu( mbList ); mbList->insertItem( tr( "Contact" ), edit ); // Category Menu catMenu = new QPopupMenu( this ); catMenu->setCheckable( TRUE ); connect( catMenu, SIGNAL(activated(int)), this, SLOT(slotSetCategory(int)) ); mbList->insertItem( tr("View"), catMenu ); // Create Toolbar listTools = new QToolBar( this, "list operations" ); listTools->setHorizontalStretchable( true ); addToolBar( listTools ); moveToolBar( listTools, m_config.getToolBarPos() ); // View Icons m_tableViewButton = new QAction( tr( "List" ), Resource::loadPixmap( "addressbook/listview" ), QString::null, 0, this, 0 ); connect( m_tableViewButton, SIGNAL( activated() ), this, SLOT( slotListView() ) ); m_tableViewButton->setToggleAction( true ); m_tableViewButton->addTo( listTools ); m_cardViewButton = new QAction( tr( "Card" ), Resource::loadPixmap( "addressbook/cardview" ), QString::null, 0, this, 0 ); connect( m_cardViewButton, SIGNAL( activated() ), this, SLOT( slotCardView() ) ); m_cardViewButton->setToggleAction( true ); m_cardViewButton->addTo( listTools ); listTools->addSeparator(); // Other Buttons QAction *a = new QAction( tr( "New" ), Resource::loadPixmap( "new" ), QString::null, 0, this, 0 ); actionNew = a; connect( a, SIGNAL( activated() ), this, SLOT( slotListNew() ) ); a->addTo( edit ); a->addTo( listTools ); a = new QAction( tr( "Edit" ), Resource::loadPixmap( "edit" ), QString::null, 0, this, 0 ); actionEdit = a; connect( a, SIGNAL( activated() ), this, SLOT( slotViewEdit() ) ); a->addTo( edit ); a->addTo( listTools ); a = new QAction( tr( "Delete" ), Resource::loadPixmap( "trash" ), QString::null, 0, this, 0 ); actionTrash = a; connect( a, SIGNAL( activated() ), this, SLOT( slotListDelete() ) ); a->addTo( edit ); a->addTo( listTools ); // make it possible to go directly to businesscard via qcop call //#if defined(Q_WS_QWS) // Why this ? (se) #if !defined(QT_NO_COP) QCopChannel *addressChannel = new QCopChannel("QPE/Addressbook" , this ); - connect (addressChannel, SIGNAL( received(const QCString &, const QByteArray &)), - this, SLOT ( appMessage(const QCString &, const QByteArray &) ) ); + connect (addressChannel, SIGNAL( received(const QCString&,const QByteArray&)), + this, SLOT ( appMessage(const QCString&,const QByteArray&) ) ); #endif // #endif a = new QAction( tr( "Find" ), Resource::loadPixmap( "mag" ), QString::null, 0, this, 0 ); actionFind = a; connect( a, SIGNAL(activated()), this, SLOT( slotFindOpen()) ); a->addTo( edit ); a->addTo( listTools ); // Much better search widget, taken from QTReader.. (se) searchBar = new OFloatBar( "Search", this, QMainWindow::Top, TRUE ); searchBar->setHorizontalStretchable( TRUE ); searchBar->hide(); searchEdit = new QLineEdit( searchBar, "searchEdit" ); // QFont f("unifont", 16 /*, QFont::Bold*/); // searchEdit->setFont( f ); searchBar->setStretchableWidget( searchEdit ); - connect( searchEdit, SIGNAL( returnPressed( ) ), - this, SLOT( slotFind( ) ) ); + connect( searchEdit, SIGNAL( returnPressed() ), + this, SLOT( slotFind() ) ); a = new QAction( tr( "Start Search" ), Resource::loadPixmap( "enter" ), QString::null, 0, this, 0 ); connect( a, SIGNAL( activated() ), this, SLOT( slotFind() ) ); a->addTo( searchBar ); a = new QAction( tr( "Close Find" ), Resource::loadPixmap( "close" ), QString::null, 0, this, 0 ); connect( a, SIGNAL( activated() ), this, SLOT( slotFindClose() ) ); a->addTo( searchBar ); a = new QAction( tr( "Write Mail To" ), Resource::loadPixmap( "addressbook/sendmail" ), QString::null, 0, this, 0 ); //a->setEnabled( FALSE ); we got support for it now :) zecke actionMail = a; connect( a, SIGNAL( activated() ), this, SLOT( writeMail() ) ); a->addTo( edit ); a->addTo( listTools ); if ( Ir::supported() ) { a = new QAction( tr ("Beam Entry" ), Resource::loadPixmap( "beam" ), QString::null, 0, this, 0 ); actionBeam = a; connect( a, SIGNAL( activated() ), this, SLOT( slotBeam() ) ); a->addTo( edit ); a->addTo( listTools ); } edit->insertSeparator(); a = new QAction( tr("Import vCard"), Resource::loadPixmap( "addressbook/fileimport"), QString::null, 0, this, 0); actionPersonal = a; connect( a, SIGNAL( activated() ), this, SLOT( importvCard() ) ); a->addTo( edit ); a = new QAction( tr("Export vCard"), Resource::loadPixmap( "addressbook/fileexport"), QString::null, 0, this, 0); actionPersonal = a; connect( a, SIGNAL( activated() ), this, SLOT( exportvCard() ) ); a->addTo( edit ); edit->insertSeparator(); a = new QAction( tr("My Personal Details"), Resource::loadPixmap( "addressbook/identity" ), QString::null, 0, this, 0 , TRUE ); actionPersonal = a; connect( a, SIGNAL( activated() ), this, SLOT( slotPersonalView() ) ); a->addTo( edit ); #ifdef __DEBUG_RELEASE // Remove this function for public Release ! This is only // for debug purposes .. a = new QAction( tr( "Save all Data"), QString::null, 0, 0 ); connect( a, SIGNAL( activated() ), this , SLOT( slotSave() ) ); a->addTo( edit ); #endif a = new QAction( tr( "Config" ), Resource::loadPixmap( "SettingsIcon" ), QString::null, 0, this, 0 ); connect( a, SIGNAL( activated() ), this, SLOT( slotConfig() ) ); a->addTo( edit ); // Create Views listContainer = new QWidget( this ); QVBoxLayout *vb = new QVBoxLayout( listContainer ); m_abView = new AbView( listContainer, m_config.orderList() ); vb->addWidget( m_abView ); // abList->setHScrollBarMode( QScrollView::AlwaysOff ); - connect( m_abView, SIGNAL( signalViewSwitched ( int ) ), - this, SLOT( slotViewSwitched( int ) ) ); + connect( m_abView, SIGNAL( signalViewSwitched(int) ), + this, SLOT( slotViewSwitched(int) ) ); QObject::connect( m_abView, SIGNAL(signalNotFound()), this, SLOT(slotNotFound()) ); // m_abView->load(); // Already done by c'tor . // Letter Picker pLabel = new LetterPicker( listContainer ); connect(pLabel, SIGNAL(letterClicked(char)), this, SLOT(slotSetLetter(char))); connect(m_abView, SIGNAL( signalClearLetterPicker() ), pLabel, SLOT( clear() ) ); vb->addWidget( pLabel ); // All Categories into view-menu.. populateCategories(); // Fontsize defaultFont = new QFont( m_abView->font() ); slotSetFont(m_config.fontSize()); m_curFontSize = m_config.fontSize(); setCentralWidget(listContainer); // qDebug("adressbook contrsuction: t=%d", t.elapsed() ); connect( qApp, SIGNAL( flush() ), this, SLOT( flush() ) ); connect( qApp, SIGNAL( reload() ), this, SLOT( reload() ) ); - connect( qApp, SIGNAL( appMessage(const QCString &, const QByteArray &) ), - this, SLOT( appMessage(const QCString &, const QByteArray &) ) ); + connect( qApp, SIGNAL( appMessage(const QCString&,const QByteArray&) ), + this, SLOT( appMessage(const QCString&,const QByteArray&) ) ); isLoading = false; } void AddressbookWindow::slotConfig() { ConfigDlg* dlg = new ConfigDlg( this, "Config" ); dlg -> setConfig( m_config ); if ( QPEApplication::execDialog( dlg ) ) { qWarning ("Config Dialog accepted!"); m_config = dlg -> getConfig(); if ( m_curFontSize != m_config.fontSize() ){ qWarning("Font was changed!"); m_curFontSize = m_config.fontSize(); emit slotSetFont( m_curFontSize ); } m_abView -> setListOrder( m_config.orderList() ); } delete dlg; } void AddressbookWindow::slotSetFont( int size ) { qWarning("void AddressbookWindow::slotSetFont( %d )", size); if (size > 2 || size < 0) size = 1; m_config.setFontSize( size ); QFont *currentFont; switch (size) { case 0: m_abView->setFont( QFont( defaultFont->family(), defaultFont->pointSize() - 2 ) ); currentFont = new QFont (m_abView->font()); // abList->resizeRows(currentFont->pixelSize() + 7); :SX // abList->resizeRows(); break; case 1: m_abView->setFont( *defaultFont ); currentFont = new QFont (m_abView->font()); // // abList->resizeRows(currentFont->pixelSize() + 7); // abList->resizeRows(); break; case 2: m_abView->setFont( QFont( defaultFont->family(), defaultFont->pointSize() + 2 ) ); currentFont = new QFont (m_abView->font()); // //abList->resizeRows(currentFont->pixelSize() + 7); // abList->resizeRows(); break; } } void AddressbookWindow::importvCard() { QString str = OFileDialog::getOpenFileName( 1,"/");//,"", "*", this ); if(!str.isEmpty() ){ setDocument((const QString&) str ); } } void AddressbookWindow::exportvCard() { qWarning(" void AddressbookWindow::exportvCard()"); QString filename = OFileDialog::getSaveFileName( 1,"/home/"); //,"", "*", this ); if( !filename.isEmpty() && ( filename[filename.length()-1] != '/' ) ){ qWarning(" Save to file %s, (%d)", filename.latin1(), filename.length()-1 ); OContact curCont = m_abView->currentEntry(); if ( !curCont.isEmpty() ){ OContactAccessBackend* vcard_backend = new OContactAccessBackend_VCard( QString::null, filename ); OContactAccess* access = new OContactAccess ( "addressbook_exp", QString::null , vcard_backend, true ); if ( access ){ access->add( curCont ); access->save(); } delete access; }else QMessageBox::critical( 0, "Export VCard", QString( tr( "You have to select a contact !") ) ); }else QMessageBox::critical( 0, "Export VCard", QString( tr( "You have to set a filename !") ) ); } void AddressbookWindow::setDocument( const QString &filename ) { qWarning( "void AddressbookWindow::setDocument( %s )", filename.latin1() ); if ( filename.find(".vcf") != int(filename.length()) - 4 ){ switch( QMessageBox::information( this, tr ( "Right file type ?" ), tr( "The selected file \n does not end with \".vcf\".\n Do you really want to open it?" ), tr( "&Yes" ), tr( "&No" ), QString::null, 0, // Enter == button 0 2 ) ) { // Escape == button 2 case 0: qWarning("YES clicked"); break; case 1: qWarning("NO clicked"); return; break; } } OContactAccessBackend* vcard_backend = new OContactAccessBackend_VCard( QString::null, filename ); OContactAccess* access = new OContactAccess ( "addressbook", QString::null , vcard_backend, true ); OContactAccess::List allList = access->allRecords(); qWarning( "Found number of contacts in File: %d", allList.count() ); if ( !allList.count() ) { QMessageBox::information( this, "Import VCard", "It was impossible to import\nthe VCard.\n" "The VCard may be corrupted!" ); } bool doAsk = true; OContactAccess::List::Iterator it; for ( it = allList.begin(); it != allList.end(); ++it ){ qWarning("Adding Contact from: %s", (*it).fullName().latin1() ); if ( doAsk ){ switch( QMessageBox::information( this, tr ( "Add Contact?" ), tr( "Do you really want add contact for \n%1?" ) .arg( (*it).fullName().latin1() ), tr( "&Yes" ), tr( "&No" ), tr( "&All Yes"), 0, // Enter == button 0 2 ) ) { // Escape == button 2 case 0: qWarning("YES clicked"); m_abView->addEntry( *it ); break; case 1: qWarning("NO clicked"); break; case 2: qWarning("YesAll clicked"); doAsk = false; break; } }else m_abView->addEntry( *it ); } delete access; } void AddressbookWindow::resizeEvent( QResizeEvent *e ) { QMainWindow::resizeEvent( e ); } AddressbookWindow::~AddressbookWindow() { ToolBarDock dock; int dummy; bool bDummy; getLocation ( listTools, dock, dummy, bDummy, dummy ); m_config.setToolBarDock( dock ); m_config.save(); } void AddressbookWindow::slotUpdateToolbar() { OContact ce = m_abView->currentEntry(); actionMail->setEnabled( !ce.defaultEmail().isEmpty() ); } void AddressbookWindow::slotListNew() { OContact cnt; if( !syncing ) { editEntry( NewEntry ); } else { QMessageBox::warning(this, tr("Contacts"), tr("Can not edit data, currently syncing")); } } // void AddressbookWindow::slotListView() // { // m_abView -> init( abList->currentEntry() ); // // :SX mView->sync(); // //:SX showView(); // } void AddressbookWindow::slotListDelete() { if(!syncing) { OContact tmpEntry = m_abView ->currentEntry(); // get a name, do the best we can... QString strName = tmpEntry.fullName(); if ( strName.isEmpty() ) { strName = tmpEntry.company(); if ( strName.isEmpty() ) strName = "No Name"; } if ( QPEMessageBox::confirmDelete( this, tr( "Contacts" ), strName ) ) { m_abView->removeEntry( tmpEntry.uid() ); } } else { QMessageBox::warning( this, tr("Contacts"), tr("Can not edit data, currently syncing") ); } } void AddressbookWindow::slotFindOpen() { searchBar->show(); m_abView -> inSearch(); searchEdit->setFocus(); } void AddressbookWindow::slotFindClose() { searchBar->hide(); m_abView -> offSearch(); // m_abView->setFocus(); } void AddressbookWindow::slotFind() { m_abView->slotDoFind( searchEdit->text(), m_config.beCaseSensitive(), m_config.useRegExp(), false); searchEdit->clearFocus(); // m_abView->setFocus(); } void AddressbookWindow::slotViewBack() { // :SX showList(); } void AddressbookWindow::slotViewEdit() { if(!syncing) { if (actionPersonal->isOn()) { editPersonal(); } else { editEntry( EditEntry ); } } else { QMessageBox::warning( this, tr("Contacts"), tr("Can not edit data, currently syncing") ); } } void AddressbookWindow::writeMail() { OContact c = m_abView -> currentEntry(); QString name = c.fileAs(); QString email = c.defaultEmail(); // I prefer the OPIE-Environment variable before the // QPE-one.. QString basepath = QString::fromLatin1( getenv("OPIEDIR") ); if ( basepath.isEmpty() ) basepath = QString::fromLatin1( getenv("QPEDIR") ); // Try to access the preferred. If not possible, try to // switch to the other one.. if ( m_config.useQtMail() ){ qWarning ("Accessing: %s", (basepath + "/bin/qtmail").latin1()); if ( QFile::exists( basepath + "/bin/qtmail" ) ){ qWarning ("QCop"); QCopEnvelope e("QPE/Application/qtmail", "writeMail(QString,QString)"); e << name << email; return; } else m_config.setUseOpieMail( true ); } if ( m_config.useOpieMail() ){ qWarning ("Accessing: %s", (basepath + "/bin/opiemail").latin1()); if ( QFile::exists( basepath + "/bin/opiemail" ) ){ qWarning ("QCop"); QCopEnvelope e("QPE/Application/opiemail", "writeMail(QString,QString)"); e << name << email; return; } else m_config.setUseQtMail( true ); } } static const char * beamfile = "/tmp/obex/contact.vcf"; void AddressbookWindow::slotBeam() { QString beamFilename; OContact c; if ( actionPersonal->isOn() ) { beamFilename = addressbookPersonalVCardName(); if ( !QFile::exists( beamFilename ) ) return; // can't beam a non-existent file OContactAccessBackend* vcard_backend = new OContactAccessBackend_VCard( QString::null, beamFilename ); OContactAccess* access = new OContactAccess ( "addressbook", QString::null , vcard_backend, true ); OContactAccess::List allList = access->allRecords(); OContactAccess::List::Iterator it = allList.begin(); // Just take first c = *it; delete access; } else { unlink( beamfile ); // delete if exists mkdir("/tmp/obex/", 0755); c = m_abView -> currentEntry(); OContactAccessBackend* vcard_backend = new OContactAccessBackend_VCard( QString::null, beamfile ); OContactAccess* access = new OContactAccess ( "addressbook", QString::null , vcard_backend, true ); access->add( c ); access->save(); delete access; beamFilename = beamfile; } qWarning("Beaming: %s", beamFilename.latin1() ); Ir *ir = new Ir( this ); - connect( ir, SIGNAL( done( Ir * ) ), this, SLOT( beamDone( Ir * ) ) ); + connect( ir, SIGNAL( done(Ir*) ), this, SLOT( beamDone(Ir*) ) ); QString description = c.fullName(); ir->send( beamFilename, description, "text/x-vCard" ); } void AddressbookWindow::beamDone( Ir *ir ) { delete ir; unlink( beamfile ); } static void parseName( const QString& name, QString *first, QString *middle, QString * last ) { int comma = name.find ( "," ); QString rest; if ( comma > 0 ) { *last = name.left( comma ); comma++; while ( comma < int(name.length()) && name[comma] == ' ' ) comma++; rest = name.mid( comma ); } else { int space = name.findRev( ' ' ); *last = name.mid( space+1 ); rest = name.left( space ); } int space = rest.find( ' ' ); if ( space <= 0 ) { *first = rest; } else { *first = rest.left( space ); *middle = rest.mid( space+1 ); } } void AddressbookWindow::appMessage(const QCString &msg, const QByteArray &data) { bool needShow = FALSE; qWarning("Receiving QCop-Call with message %s", QString( msg ).latin1() ); if (msg == "editPersonal()") { editPersonal(); } else if (msg == "editPersonalAndClose()") { editPersonal(); close(); } else if ( msg == "addContact(QString,QString)" ) { QDataStream stream(data,IO_ReadOnly); QString name, email; stream >> name >> email; OContact cnt; QString fn, mn, ln; parseName( name, &fn, &mn, &ln ); // qDebug( " %s - %s - %s", fn.latin1(), mn.latin1(), ln.latin1() ); cnt.setFirstName( fn ); cnt.setMiddleName( mn ); cnt.setLastName( ln ); cnt.insertEmails( email ); cnt.setDefaultEmail( email ); cnt.setFileAs(); m_abView -> addEntry( cnt ); // :SXm_abView()->init( cnt ); editEntry( EditEntry ); } else if ( msg == "beamBusinessCard()" ) { QString beamFilename = addressbookPersonalVCardName(); if ( !QFile::exists( beamFilename ) ) return; // can't beam a non-existent file Ir *ir = new Ir( this ); - connect( ir, SIGNAL( done( Ir * ) ), this, SLOT( beamDone( Ir * ) ) ); + connect( ir, SIGNAL( done(Ir*) ), this, SLOT( beamDone(Ir*) ) ); QString description = "mycard.vcf"; ir->send( beamFilename, description, "text/x-vCard" ); } else if ( msg == "show(int)" ) { raise(); QDataStream stream(data,IO_ReadOnly); int uid; stream >> uid; qWarning( "Showing uid: %d" , uid ); // Deactivate Personal View.. if ( actionPersonal->isOn() ){ actionPersonal->setOn( false ); slotPersonalView(); } // Reset category and show as card.. m_abView -> setShowByCategory( QString::null ); m_abView -> setCurrentUid( uid ); slotViewSwitched ( AbView::CardView ); needShow = true; } else if ( msg == "edit(int)" ) { QDataStream stream(data,IO_ReadOnly); int uid; stream >> uid; // Deactivate Personal View.. if ( actionPersonal->isOn() ){ actionPersonal->setOn( false ); slotPersonalView(); } // Reset category and edit.. m_abView -> setShowByCategory( QString::null ); m_abView -> setCurrentUid( uid ); slotViewEdit(); } if (needShow) QPEApplication::setKeepRunning(); } void AddressbookWindow::editEntry( EntryMode entryMode ) { OContact entry; if ( !abEditor ) { abEditor = new ContactEditor( entry, this, "editor" ); } if ( entryMode == EditEntry ) abEditor->setEntry( m_abView -> currentEntry() ); else if ( entryMode == NewEntry ) abEditor->setEntry( entry ); // other things may change the caption. abEditor->setCaption( tr("Edit Address") ); // fix the foxus... abEditor->setNameFocus(); if ( QPEApplication::execDialog( abEditor ) ) { setFocus(); if ( entryMode == NewEntry ) { OContact insertEntry = abEditor->entry(); insertEntry.assignUid(); m_abView -> addEntry( insertEntry ); m_abView -> setCurrentUid( insertEntry.uid() ); } else { OContact replEntry = abEditor->entry(); if ( !replEntry.isValidUid() ) replEntry.assignUid(); m_abView -> replaceEntry( replEntry ); } } // populateCategories(); } void AddressbookWindow::editPersonal() { OContact entry; // Switch to personal view if not selected // but take care of the menu, too if ( ! actionPersonal->isOn() ){ qWarning("*** ++++"); actionPersonal->setOn( true ); slotPersonalView(); } if ( !abEditor ) { abEditor = new ContactEditor( entry, this, "editor" ); } abEditor->setCaption(tr("Edit My Personal Details")); abEditor->setPersonalView( true ); editEntry( EditEntry ); abEditor->setPersonalView( false ); } void AddressbookWindow::slotPersonalView() { qWarning("slotPersonalView()"); if (!actionPersonal->isOn()) { // we just turned it off qWarning("slotPersonalView()-> OFF"); setCaption( tr("Contacts") ); actionNew->setEnabled(TRUE); actionTrash->setEnabled(TRUE); actionFind->setEnabled(TRUE); actionMail->setEnabled(TRUE); // slotUpdateToolbar(); m_abView->showPersonal( false ); return; } qWarning("slotPersonalView()-> ON"); // XXX need to disable some QActions. actionNew->setEnabled(FALSE); actionTrash->setEnabled(FALSE); actionFind->setEnabled(FALSE); actionMail->setEnabled(FALSE); setCaption( tr("Contacts - My Personal Details") ); m_abView->showPersonal( true ); } void AddressbookWindow::listIsEmpty( bool empty ) { if ( !empty ) { deleteButton->setEnabled( TRUE ); } } void AddressbookWindow::reload() { syncing = FALSE; m_abView->clear(); m_abView->reload(); } void AddressbookWindow::flush() { syncing = TRUE; m_abView->save(); } void AddressbookWindow::closeEvent( QCloseEvent *e ) { if(active_view == AbView::CardView){ slotViewSwitched( AbView::TableView ); e->ignore(); return; } if(syncing) { /* shouldn't we save, I hear you say? well its already been set so that an edit can not occur during a sync, and we flushed at the start of the sync, so there is no need to save Saving however itself would cause problems. */ e->accept(); return; } //################## shouldn't always save // True, but the database handles this automatically ! (se) if ( save() ) e->accept(); else e->ignore(); } /* Returns TRUE if it is OK to exit */ bool AddressbookWindow::save() { if ( !m_abView->save() ) { if ( QMessageBox::critical( 0, tr( "Out of space" ), tr("Unable to save information.\n" "Free up some space\n" "and try again.\n" diff --git a/core/pim/addressbook/contacteditor.cpp b/core/pim/addressbook/contacteditor.cpp index b1eb042..8acf570 100644 --- a/core/pim/addressbook/contacteditor.cpp +++ b/core/pim/addressbook/contacteditor.cpp @@ -346,519 +346,519 @@ void ContactEditor::init() { cmbCountry->insertItem( tr ( "Greenland" ) ); cmbCountry->insertItem( tr ( "Grenada" ) ); cmbCountry->insertItem( tr ( "Guadeloupe" ) ); cmbCountry->insertItem( tr ( "Guam" ) ); cmbCountry->insertItem( tr ( "Guatemala" ) ); cmbCountry->insertItem( tr ( "Guinea" ) ); cmbCountry->insertItem( tr ( "Guinea-Bissau" ) ); cmbCountry->insertItem( tr ( "Guyana" ) ); cmbCountry->insertItem( tr ( "Haiti" ) ); cmbCountry->insertItem( tr ( "Holy See" ) ); cmbCountry->insertItem( tr ( "Honduras" ) ); cmbCountry->insertItem( tr ( "Hong Kong" ) ); cmbCountry->insertItem( tr ( "Hungary" ) ); cmbCountry->insertItem( tr ( "Iceland" ) ); cmbCountry->insertItem( tr ( "India" ) ); cmbCountry->insertItem( tr ( "Indonesia" ) ); cmbCountry->insertItem( tr ( "Ireland" ) ); cmbCountry->insertItem( tr ( "Israel" ) ); cmbCountry->insertItem( tr ( "Italy" ) ); cmbCountry->insertItem( tr ( "Jamaica" ) ); cmbCountry->insertItem( tr ( "Japan" ) ); cmbCountry->insertItem( tr ( "Jordan" ) ); cmbCountry->insertItem( tr ( "Kazakhstan" ) ); cmbCountry->insertItem( tr ( "Kenya" ) ); cmbCountry->insertItem( tr ( "Kiribati" ) ); cmbCountry->insertItem( tr ( "Korea" ) ); cmbCountry->insertItem( tr ( "Kuwait" ) ); cmbCountry->insertItem( tr ( "Kyrgyzstan" ) ); cmbCountry->insertItem( tr ( "Laos" ) ); cmbCountry->insertItem( tr ( "Latvia" ) ); cmbCountry->insertItem( tr ( "Lebanon" ) ); cmbCountry->insertItem( tr ( "Lesotho" ) ); cmbCountry->insertItem( tr ( "Liberia" ) ); cmbCountry->insertItem( tr ( "Liechtenstein" ) ); cmbCountry->insertItem( tr ( "Lithuania" ) ); cmbCountry->insertItem( tr ( "Luxembourg" ) ); cmbCountry->insertItem( tr ( "Macau" ) ); cmbCountry->insertItem( tr ( "Macedonia" ) ); cmbCountry->insertItem( tr ( "Madagascar" ) ); cmbCountry->insertItem( tr ( "Malawi" ) ); cmbCountry->insertItem( tr ( "Malaysia" ) ); cmbCountry->insertItem( tr ( "Maldives" ) ); cmbCountry->insertItem( tr ( "Mali" ) ); cmbCountry->insertItem( tr ( "Malta" ) ); cmbCountry->insertItem( tr ( "Martinique" ) ); cmbCountry->insertItem( tr ( "Mauritania" ) ); cmbCountry->insertItem( tr ( "Mauritius" ) ); cmbCountry->insertItem( tr ( "Mayotte" ) ); cmbCountry->insertItem( tr ( "Mexico" ) ); cmbCountry->insertItem( tr ( "Micronesia" ) ); cmbCountry->insertItem( tr ( "Moldova" ) ); cmbCountry->insertItem( tr ( "Monaco" ) ); cmbCountry->insertItem( tr ( "Mongolia" ) ); cmbCountry->insertItem( tr ( "Montserrat" ) ); cmbCountry->insertItem( tr ( "Morocco" ) ); cmbCountry->insertItem( tr ( "Mozambique" ) ); cmbCountry->insertItem( tr ( "Myanmar" ) ); cmbCountry->insertItem( tr ( "Namibia" ) ); cmbCountry->insertItem( tr ( "Nauru" ) ); cmbCountry->insertItem( tr ( "Nepal" ) ); cmbCountry->insertItem( tr ( "Netherlands" ) ); cmbCountry->insertItem( tr ( "New Caledonia" ) ); cmbCountry->insertItem( tr ( "New Zealand" ) ); cmbCountry->insertItem( tr ( "Nicaragua" ) ); cmbCountry->insertItem( tr ( "Niger" ) ); cmbCountry->insertItem( tr ( "Nigeria" ) ); cmbCountry->insertItem( tr ( "Niue" ) ); cmbCountry->insertItem( tr ( "Norway" ) ); cmbCountry->insertItem( tr ( "Oman" ) ); cmbCountry->insertItem( tr ( "Pakistan" ) ); cmbCountry->insertItem( tr ( "Palau" ) ); cmbCountry->insertItem( tr ( "Palestinian Sovereign Areas" ) ); cmbCountry->insertItem( tr ( "Panama" ) ); cmbCountry->insertItem( tr ( "Papua New Guinea" ) ); cmbCountry->insertItem( tr ( "Paraguay" ) ); cmbCountry->insertItem( tr ( "Peru" ) ); cmbCountry->insertItem( tr ( "Philippines" ) ); cmbCountry->insertItem( tr ( "Pitcairn Islands" ) ); cmbCountry->insertItem( tr ( "Poland" ) ); cmbCountry->insertItem( tr ( "Portugal" ) ); cmbCountry->insertItem( tr ( "Puerto Rico" ) ); cmbCountry->insertItem( tr ( "Qatar" ) ); cmbCountry->insertItem( tr ( "Reunion" ) ); cmbCountry->insertItem( tr ( "Romania" ) ); cmbCountry->insertItem( tr ( "Russia" ) ); cmbCountry->insertItem( tr ( "Rwanda" ) ); cmbCountry->insertItem( tr ( "Saint Lucia" ) ); cmbCountry->insertItem( tr ( "Samoa" ) ); cmbCountry->insertItem( tr ( "San Marino" ) ); cmbCountry->insertItem( tr ( "Saudi Arabia" ) ); cmbCountry->insertItem( tr ( "Senegal" ) ); cmbCountry->insertItem( tr ( "Seychelles" ) ); cmbCountry->insertItem( tr ( "Sierra Leone" ) ); cmbCountry->insertItem( tr ( "Singapore" ) ); cmbCountry->insertItem( tr ( "Slovakia" ) ); cmbCountry->insertItem( tr ( "Slovenia" ) ); cmbCountry->insertItem( tr ( "Solomon Islands" ) ); cmbCountry->insertItem( tr ( "Somalia" ) ); cmbCountry->insertItem( tr ( "South Africa" ) ); cmbCountry->insertItem( tr ( "Spain" ) ); cmbCountry->insertItem( tr ( "Sri Lanka" ) ); cmbCountry->insertItem( tr ( "St. Helena" ) ); cmbCountry->insertItem( tr ( "Sudan" ) ); cmbCountry->insertItem( tr ( "Suriname" ) ); cmbCountry->insertItem( tr ( "Swaziland" ) ); cmbCountry->insertItem( tr ( "Sweden" ) ); cmbCountry->insertItem( tr ( "Switzerland" ) ); cmbCountry->insertItem( tr ( "Taiwan" ) ); cmbCountry->insertItem( tr ( "Tajikistan" ) ); cmbCountry->insertItem( tr ( "Tanzania" ) ); cmbCountry->insertItem( tr ( "Thailand" ) ); cmbCountry->insertItem( tr ( "Togo" ) ); cmbCountry->insertItem( tr ( "Tokelau" ) ); cmbCountry->insertItem( tr ( "Tonga" ) ); cmbCountry->insertItem( tr ( "Tunisia" ) ); cmbCountry->insertItem( tr ( "Turkey" ) ); cmbCountry->insertItem( tr ( "Turkmenistan" ) ); cmbCountry->insertItem( tr ( "Tuvalu" ) ); cmbCountry->insertItem( tr ( "Uganda" ) ); cmbCountry->insertItem( tr ( "Ukraine" ) ); cmbCountry->insertItem( tr ( "Uruguay" ) ); cmbCountry->insertItem( tr ( "Uzbekistan" ) ); cmbCountry->insertItem( tr ( "Vanuatu" ) ); cmbCountry->insertItem( tr ( "Venezuela" ) ); cmbCountry->insertItem( tr ( "Vietnam" ) ); cmbCountry->insertItem( tr ( "Virgin Islands" ) ); cmbCountry->insertItem( tr ( "Western Sahara" ) ); cmbCountry->insertItem( tr ( "Yemen" ) ); cmbCountry->insertItem( tr ( "Yugoslavia" ) ); cmbCountry->insertItem( tr ( "Zambia" ) ); cmbCountry->insertItem( tr ( "Zimbabwe" ) ); if (cmbCountry->listBox()!=0) cmbCountry->listBox()->sort(); cmbCountry->setMaximumWidth( 135 ); gl->addMultiCellWidget( cmbCountry, 5, 5, 1, 2 ); // Chooser 4 cmbChooserField4 = new QComboBox( FALSE, container ); cmbChooserField4->setMaximumWidth( 90 ); gl->addWidget( cmbChooserField4, 6, 0 ); // Textfield for chooser 2 // Now use WidgetStack to contain the textfield and the default-email combo! m_widgetStack4 = new QWidgetStack( container ); txtChooserField4 = new QLineEdit( m_widgetStack4 ); m_widgetStack4 -> addWidget( txtChooserField4, TextField ); gl->addMultiCellWidget( m_widgetStack4, 6, 6, 1, 2 ); m_widgetStack4 -> raiseWidget( TextField ); QSpacerItem *space = new QSpacerItem(1,1, QSizePolicy::Maximum, QSizePolicy::MinimumExpanding ); gl->addItem( space, 7, 0 ); tabMain->insertTab( tabViewport, tr( "Address" ) ); tabViewport = new QWidget ( tabMain ); vb = new QVBoxLayout( tabViewport ); svDetails = new QScrollView( tabViewport ); vb->addWidget( svDetails, 0, 0 ); svDetails->setResizePolicy( QScrollView::AutoOneFit ); svDetails->setFrameStyle( QFrame::NoFrame ); container = new QWidget( svDetails->viewport() ); svDetails->addChild( container ); gl = new QGridLayout( container, 1, 2, 2, 4 ); int counter = 0; // Birthday QHBox* hBox = new QHBox( container ); l = new QLabel( tr("Birthday"), container ); gl->addWidget( l, counter, 0 ); QPopupMenu* m1 = new QPopupMenu( container ); birthdayPicker = new DateBookMonth( m1, 0, TRUE ); m1->insertItem( birthdayPicker ); birthdayButton= new QToolButton( hBox, "buttonStart" ); birthdayButton->setPopup( m1 ); birthdayButton->setPopupDelay(0); QPushButton* deleteButton = new QPushButton( QIconSet( Resource::loadPixmap( "trash" ) ), tr( "Delete" ), hBox, 0 ); gl->addWidget( hBox, counter , 1 ); - connect( birthdayPicker, SIGNAL( dateClicked( int, int, int ) ), - this, SLOT( slotBirthdayDateChanged( int, int, int ) ) ); + connect( birthdayPicker, SIGNAL( dateClicked(int,int,int) ), + this, SLOT( slotBirthdayDateChanged(int,int,int) ) ); connect( deleteButton, SIGNAL( clicked() ), this, SLOT( slotRemoveBirthday() ) ); ++counter; // Anniversary hBox = new QHBox( container ); l = new QLabel( tr("Anniversary"), container ); gl->addWidget( l, counter, 0 ); m1 = new QPopupMenu( container ); anniversaryPicker = new DateBookMonth( m1, 0, TRUE ); m1->insertItem( anniversaryPicker ); anniversaryButton= new QToolButton( hBox, "buttonStart" ); anniversaryButton->setPopup( m1 ); anniversaryButton->setPopupDelay(0); deleteButton = new QPushButton( QIconSet( Resource::loadPixmap( "trash" ) ), tr( "Delete" ), hBox, 0 ); gl->addWidget( hBox, counter , 1 ); - connect( anniversaryPicker, SIGNAL( dateClicked( int, int, int ) ), - this, SLOT( slotAnniversaryDateChanged( int, int, int ) ) ); + connect( anniversaryPicker, SIGNAL( dateClicked(int,int,int) ), + this, SLOT( slotAnniversaryDateChanged(int,int,int) ) ); connect( deleteButton, SIGNAL( clicked() ), this, SLOT( slotRemoveAnniversary() ) ); ++counter; // Gender l = new QLabel( tr("Gender"), container ); gl->addWidget( l, counter, 0 ); cmbGender = new QComboBox( container ); cmbGender->insertItem( "", 0 ); cmbGender->insertItem( tr("Male"), 1); cmbGender->insertItem( tr("Female"), 2); gl->addWidget( cmbGender, counter, 1 ); ++counter; // Create Labels and lineedit fields for every dynamic entry QStringList::ConstIterator it = slDynamicEntries.begin(); QMap<QString, int> mapStrToID = OContactFields::untrFieldsToId(); QMap<int, QString> mapIdToStr = OContactFields::idToTrFields(); for (i = counter; it != slDynamicEntries.end(); i++, ++it ) { if (((*it) == "Anniversary") || ((*it) == "Birthday")|| ((*it) == "Gender")) continue; l = new QLabel( mapIdToStr[mapStrToID[*it]], container ); listName.append( l ); gl->addWidget( l, i, 0 ); QLineEdit *e = new QLineEdit( container ); listValue.append( e ); gl->addWidget( e, i, 1); } // Fill labels with names.. // loadFields(); tabMain->insertTab( tabViewport, tr( "Details" ) ); dlgNote = new QDialog( this, "Note Dialog", TRUE ); dlgNote->setCaption( tr("Enter Note") ); QVBoxLayout *vbNote = new QVBoxLayout( dlgNote ); txtNote = new QMultiLineEdit( dlgNote ); vbNote->addWidget( txtNote ); connect( btnNote, SIGNAL(clicked()), this, SLOT(slotNote()) ); dlgName = new QDialog( this, "Name Dialog", TRUE ); dlgName->setCaption( tr("Edit Name") ); gl = new QGridLayout( dlgName, 5, 2, 2, 3 ); l = new QLabel( tr("First Name"), dlgName ); gl->addWidget( l, 0, 0 ); txtFirstName = new QLineEdit( dlgName ); gl->addWidget( txtFirstName, 0, 1 ); l = new QLabel( tr("Middle Name"), dlgName ); gl->addWidget( l, 1, 0 ); txtMiddleName = new QLineEdit( dlgName ); gl->addWidget( txtMiddleName, 1, 1 ); l = new QLabel( tr("Last Name"), dlgName ); gl->addWidget( l, 2, 0 ); txtLastName = new QLineEdit( dlgName ); gl->addWidget( txtLastName, 2, 1 ); // l = new QLabel( tr("Suffix"), dlgName ); // gl->addWidget( l, 3, 0 ); // txtSuffix = new QLineEdit( dlgName ); // gl->addWidget( txtSuffix, 3, 1 ); space = new QSpacerItem(1,1, QSizePolicy::Maximum, QSizePolicy::MinimumExpanding ); gl->addItem( space, 4, 0 ); cmbChooserField1->insertStringList( trlChooserNames ); cmbChooserField2->insertStringList( trlChooserNames ); cmbChooserField3->insertStringList( trlChooserNames ); cmbChooserField4->insertStringList( trlChooserNames ); cmbChooserField1->setCurrentItem( 0 ); cmbChooserField2->setCurrentItem( 1 ); cmbChooserField3->setCurrentItem( 2 ); connect( btnFullName, SIGNAL(clicked()), this, SLOT(slotName()) ); - connect( txtFullName, SIGNAL(textChanged(const QString &)), - this, SLOT(slotFullNameChange(const QString &)) ); - connect( txtSuffix, SIGNAL(textChanged(const QString &)), - this, SLOT(slotSuffixChange(const QString &)) ); - connect( txtOrganization, SIGNAL(textChanged(const QString &)), - this, SLOT(slotOrganizationChange(const QString &)) ); - connect( txtChooserField1, SIGNAL(textChanged(const QString &)), - this, SLOT(slotChooser1Change(const QString &)) ); - connect( txtChooserField2, SIGNAL(textChanged(const QString &)), - this, SLOT(slotChooser2Change(const QString &)) ); - connect( txtChooserField3, SIGNAL(textChanged(const QString &)), - this, SLOT(slotChooser3Change(const QString &)) ); - connect( txtChooserField4, SIGNAL(textChanged(const QString &)), - this, SLOT(slotChooser4Change(const QString &)) ); - connect( txtAddress, SIGNAL(textChanged(const QString &)), - this, SLOT(slotAddressChange(const QString &)) ); - connect( txtCity, SIGNAL(textChanged(const QString &)), - this, SLOT(slotCityChange(const QString &)) ); - connect( txtState, SIGNAL(textChanged(const QString &)), - this, SLOT(slotStateChange(const QString &)) ); - connect( txtZip, SIGNAL(textChanged(const QString &)), - this, SLOT(slotZipChange(const QString &)) ); - connect( cmbCountry, SIGNAL(textChanged(const QString &)), - this, SLOT(slotCountryChange(const QString &)) ); - connect( cmbCountry, SIGNAL(activated(const QString &)), - this, SLOT(slotCountryChange(const QString &)) ); + connect( txtFullName, SIGNAL(textChanged(const QString&)), + this, SLOT(slotFullNameChange(const QString&)) ); + connect( txtSuffix, SIGNAL(textChanged(const QString&)), + this, SLOT(slotSuffixChange(const QString&)) ); + connect( txtOrganization, SIGNAL(textChanged(const QString&)), + this, SLOT(slotOrganizationChange(const QString&)) ); + connect( txtChooserField1, SIGNAL(textChanged(const QString&)), + this, SLOT(slotChooser1Change(const QString&)) ); + connect( txtChooserField2, SIGNAL(textChanged(const QString&)), + this, SLOT(slotChooser2Change(const QString&)) ); + connect( txtChooserField3, SIGNAL(textChanged(const QString&)), + this, SLOT(slotChooser3Change(const QString&)) ); + connect( txtChooserField4, SIGNAL(textChanged(const QString&)), + this, SLOT(slotChooser4Change(const QString&)) ); + connect( txtAddress, SIGNAL(textChanged(const QString&)), + this, SLOT(slotAddressChange(const QString&)) ); + connect( txtCity, SIGNAL(textChanged(const QString&)), + this, SLOT(slotCityChange(const QString&)) ); + connect( txtState, SIGNAL(textChanged(const QString&)), + this, SLOT(slotStateChange(const QString&)) ); + connect( txtZip, SIGNAL(textChanged(const QString&)), + this, SLOT(slotZipChange(const QString&)) ); + connect( cmbCountry, SIGNAL(textChanged(const QString&)), + this, SLOT(slotCountryChange(const QString&)) ); + connect( cmbCountry, SIGNAL(activated(const QString&)), + this, SLOT(slotCountryChange(const QString&)) ); connect( cmbChooserField1, SIGNAL(activated(int)), this, SLOT(slotCmbChooser1Change(int)) ); connect( cmbChooserField2, SIGNAL(activated(int)), this, SLOT(slotCmbChooser2Change(int)) ); connect( cmbChooserField3, SIGNAL(activated(int)), this, SLOT(slotCmbChooser3Change(int)) ); connect( cmbChooserField4, SIGNAL(activated(int)), this, SLOT(slotCmbChooser4Change(int)) ); connect( cmbAddress, SIGNAL(activated(int)), this, SLOT(slotAddressTypeChange(int)) ); new QPEDialogListener(this); setPersonalView ( m_personalView ); qWarning("init() END"); } void ContactEditor::defaultEmailChanged(int i){ qDebug("defaultEmailChanged"); // was sollte das ? (se) // int index = cmbChooserField1->currentItem(); // slChooserValues[index] = cmbDefaultEmail->text(i); defaultEmail = cmbDefaultEmail->text(i); qDebug ("Changed to: %s", defaultEmail.latin1()); } void ContactEditor::populateDefaultEmailCmb(){ // if the default-email combo was not selected and therfore not created // we get a lot of trouble.. Therfore create an invisible one.. if ( !cmbDefaultEmail ){ cmbDefaultEmail = new QComboBox(this); cmbDefaultEmail -> hide(); } cmbDefaultEmail->clear(); cmbDefaultEmail->insertStringList( emails ); // cmbDefaultEmail->show(); // Select default email in combo.. bool found = false; for ( int i = 0; i < cmbDefaultEmail->count(); i++){ qDebug(" populateDefaultEmailCmb text >%s< defaultEmail >%s<", cmbDefaultEmail->text( i ).latin1(), defaultEmail.latin1()); if ( cmbDefaultEmail->text( i ).stripWhiteSpace() == defaultEmail.stripWhiteSpace() ){ cmbDefaultEmail->setCurrentItem( i ); qDebug("set"); found = true; } } // If the current default email is not found in the list, we choose the // first one.. if ( !found ) defaultEmail = cmbDefaultEmail->text(0); } // Called when any combobox was changed. // "true" returned if the change was chandled by this function, else it should // be handled by something else.. bool ContactEditor::cmbChooserChange( int index, QWidgetStack* inputStack, int widgetPos ) { QString type = slChooserNames[index]; qWarning("ContactEditor::cmbChooserChange -> Type: %s, WidgetPos: %d", type.latin1(), widgetPos ); if ( !initializing ) contactfields.setFieldOrder( widgetPos-1, index ); // Create and connect combobox for selecting the default email if ( type == "Default Email"){ qWarning("Choosing default-email (defaultEmailChooserPosition= %d) ", defaultEmailChooserPosition); // More than one default-email chooser is not allowed ! if ( ( defaultEmailChooserPosition != -1 ) && defaultEmailChooserPosition != widgetPos && !initializing){ chooserError( widgetPos ); return true; } QComboBox* cmbo = ( QComboBox* ) inputStack -> widget( Combo ); if ( cmbo ){ inputStack->raiseWidget( TextField ); inputStack -> removeWidget( cmbo ); delete cmbo; } cmbo = new QComboBox( inputStack ); cmbo -> insertStringList( emails ); inputStack -> addWidget( cmbo, Combo ); inputStack -> raiseWidget( Combo ); defaultEmailChooserPosition = widgetPos; cmbDefaultEmail = cmbo; connect( cmbo,SIGNAL( activated(int) ), SLOT( defaultEmailChanged(int) ) ); // Set current default email populateDefaultEmailCmb(); } else { // Something else was selected: Hide combo.. qWarning(" Hiding default-email combo" ); if ( defaultEmailChooserPosition == widgetPos ){ defaultEmailChooserPosition = -1; } QComboBox* cmbo = ( QComboBox* ) inputStack -> widget( Combo ); if ( cmbo ){ inputStack->raiseWidget( TextField ); inputStack -> removeWidget( cmbo ); cmbDefaultEmail = 0l; delete cmbo; } // Caller should initialize the responsible textfield, therefore // "false" is returned return false; } // Everything is worked off .. return true; } // Currently accessed when we select default-email more than once ! void ContactEditor::chooserError( int index ) { qWarning("ContactEditor::chooserError( %d )", index); QMessageBox::warning( this, "Chooser Error", "Multiple selection of this\n" "Item is not allowed !\n\n" "First deselect the previous one !", "&OK", 0, 0, 0, 0 ); // Reset the selected Chooser. Unfortunately the chooser // generates no signal, therfore we have to // call the cmbChooserChange function manually.. switch( index ){ case 1: cmbChooserField1 -> setCurrentItem( 0 ); slotCmbChooser1Change( 0 ); break; case 2: cmbChooserField2 -> setCurrentItem( 0 ); slotCmbChooser2Change( 0 ); break; case 3: cmbChooserField3 -> setCurrentItem( 0 ); slotCmbChooser3Change( 0 ); break; case 4: cmbChooserField4 -> setCurrentItem( 0 ); slotCmbChooser4Change( 0 ); break; } } // Called when something was changed in a textfield (shouldn't it called textchanged? (se)) void ContactEditor::chooserChange( const QString &textChanged, int index, QLineEdit* , int widgetPos ) { QString type = slChooserNames[index]; // :SX qDebug("ContactEditor::chooserChange( type=>%s<, textChanged=>%s< index=%i, widgetPos=%i", type.latin1(),textChanged.latin1(), index, widgetPos ); if ( type == "Default Email"){ qWarning ("??? Wozu??: %s", textChanged.latin1()); defaultEmail = textChanged; populateDefaultEmailCmb(); }else if (type == "Emails"){ qDebug("emails"); QString de; emails = QStringList::split (",", textChanged ); populateDefaultEmailCmb(); } slChooserValues[index] = textChanged; } void ContactEditor::slotChooser1Change( const QString &textChanged ) { qWarning("ContactEditor::slotChooser1Change( %s )", textChanged.latin1()); chooserChange( textChanged, cmbChooserField1->currentItem(), txtChooserField1, 1); diff --git a/core/pim/datebook/datebook.cpp b/core/pim/datebook/datebook.cpp index af26302..3934411 100644 --- a/core/pim/datebook/datebook.cpp +++ b/core/pim/datebook/datebook.cpp @@ -1,1072 +1,1070 @@ /********************************************************************** ** Copyright (C) 2000 Trolltech AS. All rights reserved. ** ** This file is part of Qtopia Environment. ** ** This file may be distributed and/or modified under the terms of the ** GNU General Public License version 2 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. ** ** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE ** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. ** ** See http://www.trolltech.com/gpl/ for GPL licensing information. ** ** Contact info@trolltech.com if any conditions of this licensing are ** not clear to you. ** ** $Id$ ** **********************************************************************/ #define QTOPIA_INTERNAL_FD #include "datebook.h" #include "datebookday.h" #include "datebooksettings.h" #include "datebookweek.h" #include "datebookweeklst.h" #include "dateentryimpl.h" #include <qpe/datebookmonth.h> #include <qpe/qpeapplication.h> #include <qpe/config.h> #include <qpe/finddialog.h> #include <qpe/ir.h> #include <qpe/qpemessagebox.h> #include <qpe/resource.h> #include <qpe/sound.h> #include <qtoolbar.h> #include <qpe/tzselect.h> #include <qaction.h> #include <qcopchannel_qws.h> #include <qlayout.h> #include <qmessagebox.h> #include <qtimer.h> #include <qtl.h> #include <qwidgetstack.h> #include <sys/stat.h> #include <sys/types.h> #include <fcntl.h> #include <unistd.h> #include <stdlib.h> DateBook::DateBook( QWidget *parent, const char *, WFlags f ) : QMainWindow( parent, "datebook", f ), aPreset( FALSE ), presetTime( -1 ), startTime( 8 ), // an acceptable default rowStyle( 0 ), bJumpToCurTime(FALSE), syncing(FALSE), inSearch(FALSE), alarmCounter(0) { bool needEvilHack= false; // if we need an Evil Hack QTime t; t.start(); db = new DateBookDBHack; qDebug("loading db t=%d", t.elapsed() ); loadSettings(); setCaption( tr("Calendar") ); setIcon( Resource::loadPixmap( "datebook_icon" ) ); setToolBarsMovable( FALSE ); views = new QWidgetStack( this ); setCentralWidget( views ); dayView = 0; weekView = 0; weekLstView = 0; monthView = 0; // QToolBar *bar = new QToolBar( this ); // bar->setHorizontalStretchable( TRUE ); // QMenuBar *mb = new QMenuBar( bar ); // mb->setMargin( 0 ); // QPopupMenu *view = new QPopupMenu( this ); // mb->insertItem( tr( "View" ), view ); QToolBar *sub_bar = new QToolBar(this); sub_bar->setHorizontalStretchable(TRUE); QActionGroup *g = new QActionGroup( this ); g->setExclusive( TRUE ); QAction *a = new QAction( tr( "New" ), Resource::loadPixmap( "new" ), QString::null, 0, this, 0 ); connect( a, SIGNAL( activated() ), this, SLOT( fileNew() ) ); a->addTo( sub_bar ); sub_bar->addSeparator(); a = new QAction( tr( "Today" ), Resource::loadPixmap( "datebook/to_day" ), QString::null, 0, g, 0 ); connect( a, SIGNAL( activated() ), this, SLOT( slotToday() ) ); a->addTo( sub_bar ); // a->addTo( view ); sub_bar->addSeparator(); a = new QAction( tr( "Day" ), Resource::loadPixmap( "day" ), QString::null, 0, g, 0 ); connect( a, SIGNAL( activated() ), this, SLOT( viewDay() ) ); a->addTo( sub_bar ); // a->addTo( view ); a->setToggleAction( TRUE ); a->setOn( TRUE ); dayAction = a; a = new QAction( tr( "Week" ), Resource::loadPixmap( "week" ), QString::null, 0, g, 0 ); connect( a, SIGNAL( activated() ), this, SLOT( viewWeek() ) ); a->addTo( sub_bar ); // a->addTo( view ); a->setToggleAction( TRUE ); weekAction = a; a = new QAction( tr( "WeekLst" ), Resource::loadPixmap( "datebook/weeklst" ), QString::null, 0, g, 0 ); connect( a, SIGNAL( activated() ), this, SLOT( viewWeekLst() ) ); a->addTo( sub_bar ); // a->addTo( view ); a->setToggleAction( TRUE ); weekLstAction = a; a = new QAction( tr( "Month" ), Resource::loadPixmap( "month" ), QString::null, 0, g, 0 ); connect( a, SIGNAL( activated() ), this, SLOT( viewMonth() ) ); a->addTo( sub_bar ); // a->addTo( view ); a->setToggleAction( TRUE ); monthAction = a; sub_bar->addSeparator(); a = new QAction( tr( "Find" ), Resource::loadPixmap( "mag" ), QString::null, 0, this, 0 ); connect( a, SIGNAL(activated()), this, SLOT(slotFind()) ); a->addTo( sub_bar ); a = new QAction( tr( "Edit..." ), Resource::loadPixmap("SettingsIcon"), QString::null, 0, this, 0 ); connect( a, SIGNAL( activated() ), this, SLOT( slotSettings() ) ); a->addTo( sub_bar ); if(defaultView==DAY) viewDay(); if(defaultView==WEEK) needEvilHack=true; // viewWeek(); if(defaultView==WEEKLST) viewWeekLst(); if(defaultView==MONTH) viewMonth(); connect( qApp, SIGNAL(clockChanged(bool)), this, SLOT(changeClock(bool)) ); connect( qApp, SIGNAL(weekChanged(bool)), this, SLOT(changeWeek(bool)) ); #if defined(Q_WS_QWS) && !defined(QT_NO_COP) - connect( qApp, SIGNAL(appMessage(const QCString&, const QByteArray&)), this, SLOT(appMessage(const QCString&, const QByteArray&)) ); + connect( qApp, SIGNAL(appMessage(const QCString&,const QByteArray&)), this, SLOT(appMessage(const QCString&,const QByteArray&)) ); #endif // listen on QPE/System #if defined(Q_WS_QWS) #if !defined(QT_NO_COP) QCopChannel *channel = new QCopChannel( "QPE/System", this ); - connect( channel, SIGNAL(received(const QCString&, const QByteArray&)), this, SLOT(receive(const QCString&, const QByteArray&)) ); + connect( channel, SIGNAL(received(const QCString&,const QByteArray&)), this, SLOT(receive(const QCString&,const QByteArray&)) ); channel = new QCopChannel( "QPE/Datebook", this ); - connect( channel, SIGNAL(received(const QCString&, const QByteArray&)), this, SLOT(receive(const QCString&, const QByteArray&)) ); + connect( channel, SIGNAL(received(const QCString&,const QByteArray&)), this, SLOT(receive(const QCString&,const QByteArray&)) ); #endif #endif qDebug("done t=%d", t.elapsed() ); connect( qApp, SIGNAL( flush() ), this, SLOT( flush() ) ); connect( qApp, SIGNAL( reload()), this, SLOT( reload() ) ); /* * Here is a problem description: * When Weekview is the default view * a DateBookWeekView get's created * redraw() get's called. So what? * Remember that we're still in the c'tor * and no final layout has happened? Ok * now all Events get arranged. Their x * position get's determined by a QHeader * position. But the QHeader isn't layouted or * at the right position. redraw() is a slot * so we'll call it then via a singleShot * from view() */ if( needEvilHack ){ QTimer::singleShot( 500, this, SLOT(viewWeek()) ); } } void DateBook::receive( const QCString &msg, const QByteArray &data ) { QDataStream stream( data, IO_ReadOnly ); if ( msg == "timeChange(QString)" ) { // update active view! if ( dayAction->isOn() ) viewDay(); else if ( weekAction->isOn() ) viewWeek(); else if ( monthAction->isOn() ) viewMonth(); } else if (msg == "editEvent(int)") { int uid; stream >> uid; Event e=db->eventByUID(uid); editEvent(e); }else if (msg == "viewDefault(QDate)"){ QDate day; stream >> day; viewDefault(day); } } DateBook::~DateBook() { } void DateBook::slotSettings() { DateBookSettings frmSettings( ampm, this ); frmSettings.setStartTime( startTime ); frmSettings.setAlarmPreset( aPreset, presetTime ); frmSettings.setJumpToCurTime( bJumpToCurTime ); frmSettings.setRowStyle( rowStyle ); frmSettings.comboDefaultView->setCurrentItem(defaultView-1); frmSettings.comboWeekListView->setCurrentItem(weeklistviewconfig); bool found=false; for (int i=0; i<(frmSettings.comboLocation->count()); i++) { if ( frmSettings.comboLocation->text(i) == defaultLocation ) { frmSettings.comboLocation->setCurrentItem(i); found=true; break; } } if(!found) { frmSettings.comboLocation->insertItem(defaultLocation); frmSettings.comboLocation->setCurrentItem(frmSettings.comboLocation->count()-1); } frmSettings.comboCategory->setCategories(defaultCategories,"Calendar", tr("Calendar")); if ( QPEApplication::execDialog( &frmSettings ) ) { aPreset = frmSettings.alarmPreset(); presetTime = frmSettings.presetTime(); startTime = frmSettings.startTime(); bJumpToCurTime = frmSettings.jumpToCurTime(); rowStyle = frmSettings.rowStyle(); defaultView=frmSettings.comboDefaultView->currentItem()+1; weeklistviewconfig=frmSettings.comboWeekListView->currentItem(); defaultLocation=frmSettings.comboLocation->currentText(); defaultCategories=frmSettings.comboCategory->currentCategories(); if ( dayView ) { dayView->setStartViewTime( startTime ); dayView->setJumpToCurTime( bJumpToCurTime ); dayView->setRowStyle( rowStyle ); } if ( weekView ) { weekView->setStartViewTime( startTime ); } saveSettings(); // make the change obvious if ( views->visibleWidget() ) { if ( views->visibleWidget() == dayView ) dayView->redraw(); else if ( views->visibleWidget() == weekView ) weekView->redraw(); else if ( views->visibleWidget() == weekLstView ) weekLstView->redraw(); } } } void DateBook::fileNew() { slotNewEventFromKey(""); } QString DateBook::checkEvent(const Event &e) { /* check if overlaps with itself */ bool checkFailed = FALSE; /* check the next 12 repeats. should catch most problems */ QDate current_date = e.start().date(); Event previous = e; for(int i = 0; i < 12; i++) { QDateTime next; if (!nextOccurance(previous, current_date.addDays(1), next)) { break; // no more repeats } if(next < previous.end()) { checkFailed = TRUE; break; } current_date = next.date(); } if(checkFailed) return tr("Event duration is potentially longer\n" "than interval between repeats."); return QString::null; } QDate DateBook::currentDate() { QDate d = QDate::currentDate(); if ( dayView && views->visibleWidget() == dayView ) { d = dayView->date(); } else if ( weekView && views->visibleWidget() == weekView ) { d = weekView->date(); } else if ( weekLstView && views->visibleWidget() == weekLstView ) { d = weekLstView->date(); } else if ( monthView && views->visibleWidget() == monthView ) { d = monthView->selectedDate(); } return d; } void DateBook::view(int v, const QDate &d) { if (v==DAY) { initDay(); dayAction->setOn( TRUE ); dayView->setDate( d ); views->raiseWidget( dayView ); dayView->redraw(); } else if (v==WEEK) { initWeek(); weekAction->setOn( TRUE ); weekView->setDate( d ); views->raiseWidget( weekView ); weekView->redraw(); } else if (v==WEEKLST) { initWeekLst(); weekLstAction->setOn( TRUE ); weekLstView->setDate(d); views->raiseWidget( weekLstView ); weekLstView->redraw(); } else if (v==MONTH) { initMonth(); monthAction->setOn( TRUE ); monthView->setDate( d.year(), d.month(), d.day() ); views->raiseWidget( monthView ); monthView->redraw(); } } void DateBook::viewDefault(const QDate &d) { view(defaultView,d); } void DateBook::viewDay() { view(DAY,currentDate()); } void DateBook::viewWeek() { view(WEEK,currentDate()); } void DateBook::viewWeekLst() { view(WEEKLST,currentDate()); } void DateBook::viewMonth() { view(MONTH,currentDate()); } void DateBook::insertEvent( const Event &e ) { Event dupEvent=e; if(!dupEvent.isValidUid() ) // tkcRom seems to be different dupEvent.assignUid(); dupEvent.setLocation(defaultLocation); dupEvent.setCategories(defaultCategories); db->addEvent(dupEvent); emit newEvent(); } void DateBook::duplicateEvent( const Event &e ) { // Alot of code duplication, as this is almost like editEvent(); if (syncing) { QMessageBox::warning( this, tr("Calendar"), tr( "Can not edit data, currently syncing") ); return; } Event dupevent(e); // Make a duplicate. // workaround added for text input. QDialog editDlg( this, 0, TRUE ); DateEntry *entry; editDlg.setCaption( tr("Duplicate Event") ); QVBoxLayout *vb = new QVBoxLayout( &editDlg ); QScrollView *sv = new QScrollView( &editDlg, "scrollview" ); sv->setResizePolicy( QScrollView::AutoOneFit ); // KLUDGE!!! sv->setHScrollBarMode( QScrollView::AlwaysOff ); vb->addWidget( sv ); entry = new DateEntry( onMonday, dupevent, ampm, &editDlg, "editor" ); entry->timezone->setEnabled( FALSE ); sv->addChild( entry ); while ( QPEApplication::execDialog( &editDlg ) ) { Event newEv = entry->event(); QString error = checkEvent(newEv); if (!error.isNull()) { if (QMessageBox::warning(this, tr("error box"), error, tr("Fix it"), tr("Continue"), 0, 0, 1) == 0) continue; } /* * The problem: * DateBookDB does remove repeating events not by uid but by the time * the recurrence was created * so we need to update that time as well */ Event::RepeatPattern rp = newEv.repeatPattern(); rp.createTime = ::time( NULL ); newEv.setRepeat( TRUE, rp ); // has repeat and repeatPattern... if( newEv.uid() == e.uid() || !newEv.isValidUid() ) newEv.assignUid(); db->addEvent(newEv); emit newEvent(); break; } } void DateBook::editEvent( const Event &e ) { if (syncing) { QMessageBox::warning( this, tr("Calendar"), tr( "Can not edit data, currently syncing") ); return; } // workaround added for text input. QDialog editDlg( this, 0, TRUE ); DateEntry *entry; editDlg.setCaption( tr("Edit Event") ); QVBoxLayout *vb = new QVBoxLayout( &editDlg ); QScrollView *sv = new QScrollView( &editDlg, "scrollview" ); sv->setResizePolicy( QScrollView::AutoOneFit ); // KLUDGE!!! sv->setHScrollBarMode( QScrollView::AlwaysOff ); vb->addWidget( sv ); entry = new DateEntry( onMonday, e, ampm, &editDlg, "editor" ); entry->timezone->setEnabled( FALSE ); sv->addChild( entry ); while ( QPEApplication::execDialog( &editDlg ) ) { Event newEv = entry->event(); if(newEv.description().isEmpty() && newEv.notes().isEmpty() ) break; newEv.setUid(e.uid()); // FIXME: Hack not to clear uid QString error = checkEvent(newEv); if (!error.isNull()) { if (QMessageBox::warning(this, tr("error box"), error, tr("Fix it"), tr("Continue"), 0, 0, 1) == 0) continue; } db->editEvent(e, newEv); emit newEvent(); break; } } void DateBook::removeEvent( const Event &e ) { if (syncing) { QMessageBox::warning( this, tr("Calendar"), tr( "Can not edit data, currently syncing") ); return; } QString strName = e.description(); if ( !QPEMessageBox::confirmDelete( this, tr( "Calendar" ),strName ) ) return; db->removeEvent( e ); if ( views->visibleWidget() == dayView && dayView ) dayView->redraw(); } void DateBook::addEvent( const Event &e ) { QDate d = e.start().date(); initDay(); dayView->setDate( d ); } void DateBook::showDay( int year, int month, int day ) { QDate d(year, month, day); view(DAY,d); } void DateBook::initDay() { if ( !dayView ) { dayView = new DateBookDay( ampm, onMonday, db, views, "day view" ); views->addWidget( dayView, DAY ); dayView->setJumpToCurTime( bJumpToCurTime ); dayView->setStartViewTime( startTime ); dayView->setRowStyle( rowStyle ); connect( this, SIGNAL( newEvent() ), dayView, SLOT( redraw() ) ); connect( dayView, SIGNAL( newEvent() ), this, SLOT( fileNew() ) ); - connect( dayView, SIGNAL( removeEvent( const Event & ) ), this, SLOT( removeEvent( const Event & ) ) ); - connect( dayView, SIGNAL( editEvent( const Event & ) ), this, SLOT( editEvent( const Event & ) ) ); - connect( dayView, SIGNAL( duplicateEvent( const Event & ) ), this, SLOT( duplicateEvent( const Event & ) ) ); - connect( dayView, SIGNAL( beamEvent( const Event & ) ), this, SLOT( beamEvent( const Event & ) ) ); - connect( dayView, SIGNAL(sigNewEvent(const QString &)), this, SLOT(slotNewEventFromKey(const QString &)) ); + connect( dayView, SIGNAL( removeEvent(const Event&) ), this, SLOT( removeEvent(const Event&) ) ); + connect( dayView, SIGNAL( editEvent(const Event&) ), this, SLOT( editEvent(const Event&) ) ); + connect( dayView, SIGNAL( duplicateEvent(const Event&) ), this, SLOT( duplicateEvent(const Event&) ) ); + connect( dayView, SIGNAL( beamEvent(const Event&) ), this, SLOT( beamEvent(const Event&) ) ); + connect( dayView, SIGNAL(sigNewEvent(const QString&)), this, SLOT(slotNewEventFromKey(const QString&)) ); } } void DateBook::initWeek() { if ( !weekView ) { weekView = new DateBookWeek( ampm, onMonday, db, views, "week view" ); weekView->setStartViewTime( startTime ); views->addWidget( weekView, WEEK ); - connect( weekView, SIGNAL( showDate( int, int, int ) ), this, SLOT( showDay( int, int, int ) ) ); + connect( weekView, SIGNAL( showDate(int,int,int) ), this, SLOT( showDay(int,int,int) ) ); connect( this, SIGNAL( newEvent() ), weekView, SLOT( redraw() ) ); } //But also get it right: the year that we display can be different //from the year of the current date. So, first find the year //number of the current week. int yearNumber, totWeeks; calcWeek( currentDate(), totWeeks, yearNumber, onMonday ); QDate d = QDate( yearNumber, 12, 31 ); calcWeek( d, totWeeks, yearNumber, onMonday ); while ( totWeeks == 1 ) { d = d.addDays( -1 ); calcWeek( d, totWeeks, yearNumber, onMonday ); } } void DateBook::initWeekLst() { if ( !weekLstView ) { weekLstView = new DateBookWeekLst( ampm, onMonday, db, views, "weeklst view" ); views->addWidget( weekLstView, WEEKLST ); //weekLstView->setStartViewTime( startTime ); - connect( weekLstView, SIGNAL( showDate( int, int, int ) ), this, SLOT( showDay( int, int, int ) ) ); - connect( weekLstView, SIGNAL( addEvent( const QDateTime &, const QDateTime &, const QString & , const QString &) ), - this, SLOT( slotNewEntry( const QDateTime &, const QDateTime &, const QString & , const QString &) ) ); + connect( weekLstView, SIGNAL( showDate(int,int,int) ), this, SLOT( showDay(int,int,int) ) ); + connect( weekLstView, SIGNAL( addEvent(const QDateTime&,const QDateTime&,const QString&, const QString&) ), + this, SLOT( slotNewEntry(const QDateTime&,const QDateTime&,const QString&, const QString&) ) ); connect( this, SIGNAL( newEvent() ), weekLstView, SLOT( redraw() ) ); - connect( weekLstView, SIGNAL( editEvent( const Event & ) ), this, SLOT( editEvent( const Event & ) ) ); + connect( weekLstView, SIGNAL( editEvent(const Event&) ), this, SLOT( editEvent(const Event&) ) ); } } void DateBook::initMonth() { if ( !monthView ) { monthView = new DateBookMonth( views, "month view", FALSE, db ); views->addWidget( monthView, MONTH ); - connect( monthView, SIGNAL( dateClicked( int, int, int ) ), this, SLOT( showDay( int, int, int ) ) ); + connect( monthView, SIGNAL( dateClicked(int,int,int) ), this, SLOT( showDay(int,int,int) ) ); connect( this, SIGNAL( newEvent() ), monthView, SLOT( redraw() ) ); qApp->processEvents(); } } void DateBook::loadSettings() { Config qpeconfig( "qpe" ); qpeconfig.setGroup("Time"); ampm = qpeconfig.readBoolEntry( "AMPM", TRUE ); onMonday = qpeconfig.readBoolEntry( "MONDAY" ); Config config("DateBook"); config.setGroup("Main"); startTime = config.readNumEntry("startviewtime", 8); aPreset = config.readBoolEntry("alarmpreset"); presetTime = config.readNumEntry("presettime"); bJumpToCurTime = config.readBoolEntry("jumptocurtime"); rowStyle = config.readNumEntry("rowstyle"); defaultView = config.readNumEntry("defaultview",DAY); weeklistviewconfig = config.readNumEntry("weeklistviewconfig",NORMAL); defaultLocation=config.readEntry("defaultLocation"); QString tmpString=config.readEntry("defaultCategories"); QStringList tmpStringList=QStringList::split(",",tmpString); defaultCategories.truncate(0); for( QStringList::Iterator i=tmpStringList.begin(); i!=tmpStringList.end(); i++) { defaultCategories.resize(defaultCategories.count()+1); defaultCategories[defaultCategories.count()-1]=(*i).toInt(); } } void DateBook::saveSettings() { Config config( "qpe" ); Config configDB( "DateBook" ); configDB.setGroup( "Main" ); configDB.writeEntry("startviewtime",startTime); configDB.writeEntry("alarmpreset",aPreset); configDB.writeEntry("presettime",presetTime); configDB.writeEntry("jumptocurtime", bJumpToCurTime); configDB.writeEntry("rowstyle", rowStyle); configDB.writeEntry("defaultview",defaultView); configDB.writeEntry("weeklistviewconfig",weeklistviewconfig); configDB.writeEntry("defaultLocation",defaultLocation); QStringList tmpStringList; for( uint i=0; i<defaultCategories.count(); i++) { tmpStringList << QString::number(defaultCategories[i]); } configDB.writeEntry("defaultCategories",tmpStringList.join(",")); } void DateBook::appMessage(const QCString& msg, const QByteArray& data) { bool needShow = FALSE; if ( msg == "alarm(QDateTime,int)" ) { QDataStream ds(data,IO_ReadOnly); QDateTime when; int warn; ds >> when >> warn; // check to make it's okay to continue, // this is the case that the time was set ahead, and // we are forced given a stale alarm... QDateTime current = QDateTime::currentDateTime(); if ( current.time().hour() != when.time().hour() && current.time().minute() != when.time().minute() ) return; QValueList<EffectiveEvent> list = db->getEffectiveEvents(when.addSecs(warn*60)); if ( list.count() > 0 ) { QString msg; bool bSound = FALSE; int stopTimer = 0; bool found = FALSE; for ( QValueList<EffectiveEvent>::ConstIterator it=list.begin(); it!=list.end(); ++it ) { if ( (*it).event().hasAlarm() ) { found = TRUE; msg += "<CENTER><B>" + (*it).description() + "</B>" + "<BR>" + (*it).location() + "<BR>" + TimeString::dateString((*it).event().start(),ampm) + (warn ? tr(" (in " + QString::number(warn) + tr(" minutes)")) : QString("")) + "<BR>" + (*it).notes() + "</CENTER>"; if ( (*it).event().alarmSound() != Event::Silent ) { bSound = TRUE; } } } if ( found ) { if ( bSound ) { Sound::soundAlarm(); alarmCounter = 0; stopTimer = startTimer( 5000 ); } QDialog dlg( this, 0, TRUE ); QVBoxLayout *vb = new QVBoxLayout( &dlg ); QScrollView *view = new QScrollView( &dlg, "scrollView"); view->setResizePolicy( QScrollView::AutoOneFit ); vb->addWidget( view ); QLabel *lblMsg = new QLabel( msg, &dlg ); view->addChild( lblMsg ); QPushButton *cmdOk = new QPushButton( tr("OK"), &dlg ); connect( cmdOk, SIGNAL(clicked()), &dlg, SLOT(accept()) ); vb->addWidget( cmdOk ); needShow = QPEApplication::execDialog( &dlg ); if ( bSound ) killTimer( stopTimer ); } } } else if ( msg == "nextView()" ) { needShow = true; if ( !qApp-> activeWindow ( )) { needShow = TRUE; } else { QWidget* cur = views->visibleWidget(); if ( cur ) { if ( cur == dayView ) viewWeek(); else if ( cur == weekView ) viewWeekLst(); else if ( cur == weekLstView ) viewMonth(); else if ( cur == monthView ) viewDay(); needShow = TRUE; } } } else if (msg == "editEvent(int)") { /* simple copy from receive */ QDataStream stream(data,IO_ReadOnly); int uid; stream >> uid; Event e=db->eventByUID(uid); editEvent(e); } else if (msg == "viewDefault(QDate)"){ /* simple copy from receive */ QDataStream stream(data,IO_ReadOnly); QDate day; stream >> day; viewDefault(day); needShow = true; } if ( needShow ) { #if defined(Q_WS_QWS) || defined(_WS_QWS_) // showMaximized(); #else // show(); #endif // raise(); QPEApplication::setKeepRunning(); // setActiveWindow(); } } void DateBook::reload() { db->reload(); if ( dayAction->isOn() ) viewDay(); else if ( weekAction->isOn() ) viewWeek(); else if ( monthAction->isOn() ) viewMonth(); syncing = FALSE; } void DateBook::flush() { syncing = TRUE; db->save(); } void DateBook::timerEvent( QTimerEvent *e ) { if ( alarmCounter < 10 ) { alarmCounter++; Sound::soundAlarm(); } else { killTimer( e->timerId() ); } } void DateBook::changeClock( bool newClock ) { ampm = newClock; // repaint the affected objects... if (dayView) dayView->redraw(); if (weekView) weekView->redraw(); if (weekLstView) weekLstView->redraw(); } void DateBook::changeWeek( bool m ) { /* no need to redraw, each widget catches. Do need to store though for widgets we haven't made yet */ onMonday = m; } void DateBook::slotToday() { // we need to view today using default view view(defaultView,QDate::currentDate()); } void DateBook::closeEvent( QCloseEvent *e ) { if(syncing) { /* no need to save, did that at flush */ e->accept(); return; } // save settings will generate it's own error messages, no // need to do checking ourselves. saveSettings(); if ( db->save() ) { e->accept(); } else { if ( QMessageBox::critical( this, tr( "Out of space" ), tr("Calendar was unable to save\n" "your changes.\n" "Free up some space and try again.\n" "\nQuit anyway?"), QMessageBox::Yes|QMessageBox::Escape, QMessageBox::No|QMessageBox::Default ) != QMessageBox::No ) e->accept(); else e->ignore(); } } // Entering directly from the "keyboard" void DateBook::slotNewEventFromKey( const QString &str ) { if (syncing) { QMessageBox::warning( this, tr("Calendar"), tr( "Can not edit data, currently syncing") ); return; } // We get to here from a key pressed in the Day View // So we can assume some things. We want the string // passed in to be part of the description. QDateTime start, end; if ( views->visibleWidget() == dayView ) { dayView->selectedDates( start, end ); } else if ( views->visibleWidget() == monthView ) { QDate d = monthView->selectedDate(); start = end = d; start.setTime( QTime( 10, 0 ) ); end.setTime( QTime( 12, 0 ) ); } else if ( views->visibleWidget() == weekView ) { QDate d = weekView->date(); start = end = d; start.setTime( QTime( 10, 0 ) ); end.setTime( QTime( 12, 0 ) ); } else if ( views->visibleWidget() == weekLstView ) { QDate d = weekLstView->date(); start = end = d; start.setTime( QTime( 10, 0 ) ); end.setTime( QTime( 12, 0 ) ); } slotNewEntry(start, end, str); } void DateBook::slotNewEntry(const QDateTime &start, const QDateTime &end, const QString &str, const QString &location) { // argh! This really needs to be encapsulated in a class // or function. QDialog newDlg( this, 0, TRUE ); newDlg.setCaption( DateEntryBase::tr("New Event") ); DateEntry *e; QVBoxLayout *vb = new QVBoxLayout( &newDlg ); QScrollView *sv = new QScrollView( &newDlg ); sv->setResizePolicy( QScrollView::AutoOneFit ); sv->setFrameStyle( QFrame::NoFrame ); sv->setHScrollBarMode( QScrollView::AlwaysOff ); vb->addWidget( sv ); Event ev; ev.setDescription( str ); // When the new gui comes in, change this... if(location==0) { if(defaultLocation.isEmpty()) { ev.setLocation(tr("(Unknown)")); } else { ev.setLocation( defaultLocation ); } } else { ev.setLocation(location); } ev.setCategories(defaultCategories); ev.setStart( start ); ev.setEnd( end ); e = new DateEntry( onMonday, ev, ampm, &newDlg ); e->setAlarmEnabled( aPreset, presetTime, Event::Loud ); sv->addChild( e ); while ( QPEApplication::execDialog( &newDlg ) ) { ev = e->event(); ev.assignUid(); QString error = checkEvent( ev ); if ( !error.isNull() ) { if ( QMessageBox::warning( this, tr("Error!"), error, tr("Fix it"), tr("Continue"), 0, 0, 1 ) == 0 ) continue; } db->addEvent( ev ); emit newEvent(); break; } } void DateBook::setDocument( const QString &filename ) { if ( filename.find(".vcs") != int(filename.length()) - 4 ) return; QValueList<Event> tl = Event::readVCalendar( filename ); for( QValueList<Event>::Iterator it = tl.begin(); it != tl.end(); ++it ) { db->addEvent( *it ); } } static const char * beamfile = "/tmp/obex/event.vcs"; void DateBook::beamEvent( const Event &e ) { qDebug("trying to beamn"); unlink( beamfile ); // delete if exists mkdir("/tmp/obex/", 0755); Event::writeVCalendar( beamfile, e ); Ir *ir = new Ir( this ); - connect( ir, SIGNAL( done( Ir * ) ), this, SLOT( beamDone( Ir * ) ) ); + connect( ir, SIGNAL( done(Ir*) ), this, SLOT( beamDone(Ir*) ) ); QString description = e.description(); ir->send( beamfile, description, "text/x-vCalendar" ); } void DateBook::beamDone( Ir *ir ) { delete ir; unlink( beamfile ); } void DateBook::slotFind() { // move it to the day view... viewDay(); FindDialog frmFind( "Calendar", this ); // no tr needed frmFind.setUseDate( true ); frmFind.setDate( currentDate() ); QObject::connect( &frmFind, - SIGNAL(signalFindClicked(const QString&, const QDate&, - bool, bool, int)), + SIGNAL(signalFindClicked(const QString&,const QDate&,bool,bool,int)), this, - SLOT(slotDoFind(const QString&, const QDate&, - bool, bool, int)) ); + SLOT(slotDoFind(const QString&,const QDate&,bool,bool,int)) ); QObject::connect( this, SIGNAL(signalNotFound()), &frmFind, SLOT(slotNotFound()) ); QObject::connect( this, SIGNAL(signalWrapAround()), &frmFind, SLOT(slotWrapAround()) ); frmFind.move(0,0); frmFind.exec(); inSearch = false; } bool catComp( QArray<int> cats, int category ) { bool returnMe; int i, count; count = int(cats.count()); returnMe = false; if ( (category == -1 && count == 0) || category == -2 ) returnMe = true; else { for ( i = 0; i < count; i++ ) { if ( category == cats[i] ) { returnMe = true; break; } } } return returnMe; } void DateBook::slotDoFind( const QString& txt, const QDate &dt, bool caseSensitive, bool /*backwards*/, int category ) { QDateTime dtEnd( QDate(3001, 1, 1), QTime(0, 0, 0) ), next; QRegExp r( txt ); r.setCaseSensitive( caseSensitive ); static Event rev, nonrev; if ( !inSearch ) { rev.setStart( QDateTime(QDate(1960, 1, 1), QTime(0, 0, 0)) ); nonrev.setStart( rev.start() ); inSearch = true; } static QDate searchDate = dt; // if true at the end we will start at the begin again and afterwards // we will emit string not found static bool wrapAround = true; bool candidtate; candidtate = false; QValueList<Event> repeats = db->getRawRepeats(); // find the candidate for the first repeat that matches... // first check if there can ever be a match and then compute // the next occurence from start. See if this event is closer // to the beginning (start. next < dtEnd) and not smaller then the last // result. If we find a canditate we set the dtEnd to the time // of the ocurrence and rev to this occurence. // set wrap around to true because there might be more events coming // and we're not at the end. QValueListConstIterator<Event> it; QDate start = dt; for ( it = repeats.begin(); it != repeats.end(); ++it ) { if ( catComp( (*it).categories(), category ) ) { if ( (*it).match( r ) ) { if ( nextOccurance( *it, start, next ) ) { if ( next < dtEnd && !(next <= rev.start() ) ) { rev = *it; dtEnd = next; rev.setStart( next ); candidtate = true; wrapAround = true; } } } } } // now the for first non repeat... // dtEnd is set by the previous iteration of repeatingEvents // check if we find a closer item. Also set dtEnd to find even // more close occurrence QValueList<Event> nonRepeats = db->getNonRepeatingEvents( dt, dtEnd.date() ); qHeapSort( nonRepeats.begin(), nonRepeats.end() ); for ( it = nonRepeats.begin(); it != nonRepeats.end(); ++it ) { if ( catComp( (*it).categories(), category ) ) { if ( (*it).start() < dtEnd ) { if ( (*it).match( r ) && !(*it <= nonrev) ) { nonrev = *it; dtEnd = nonrev.start(); candidtate = true; wrapAround = true; break; } } } } if ( candidtate ) { dayView->setStartViewTime( dtEnd.time().hour() ); dayView->setDate( dtEnd.date().year(), dtEnd.date().month(), dtEnd.date().day() ); } else { if ( wrapAround ) { emit signalWrapAround(); rev.setStart( QDateTime(QDate(1960, 1, 1), QTime(0, 0, 0)) ); nonrev.setStart( rev.start() ); } else emit signalNotFound(); wrapAround = !wrapAround; } } Event DateBookDBHack::eventByUID(int uid) { // FIXME: Dirty Hacks to get hold of the private event lists QDate start; QDate end=start.addDays(-1); QValueList<Event> myEventList=getNonRepeatingEvents(start,end); QValueList<Event> myRepeatEvents=getRawRepeats(); QValueList<Event>::ConstIterator it; for (it = myEventList.begin(); it != myEventList.end(); it++) { if ((*it).uid() == uid) return *it; } for (it = myRepeatEvents.begin(); it != myRepeatEvents.end(); it++) { if ((*it).uid() == uid) return *it; } Event ev; return ev; // return at least } diff --git a/core/pim/datebook/datebookday.cpp b/core/pim/datebook/datebookday.cpp index 751a1da..ca63dc5 100644 --- a/core/pim/datebook/datebookday.cpp +++ b/core/pim/datebook/datebookday.cpp @@ -19,553 +19,553 @@ **********************************************************************/ #include "datebookday.h" #include "datebookdayheaderimpl.h" #include "datebookdayallday.h" #include <qpe/resource.h> #include <qpe/qpeapplication.h> #include <qpe/ir.h> #include <qsimplerichtext.h> #include <qpopupmenu.h> #include <qtimer.h> DateBookDayView::DateBookDayView( bool whichClock, QWidget *parent, const char *name ) : QTable( 24, 1, parent, name ), ampm( whichClock ), currDate( QDate::currentDate() ) { enableClipper(TRUE); setTopMargin( 0 ); horizontalHeader()->hide(); setLeftMargin(38); setColumnStretchable( 0, TRUE ); setHScrollBarMode( QScrollView::AlwaysOff ); verticalHeader()->setPalette(white); verticalHeader()->setResizeEnabled(FALSE); setSelectionMode( Single ); // get rid of being able to edit things... QTableItem *tmp; int row; for ( row = 0; row < numRows(); row++ ) { tmp = new QTableItem( this, QTableItem::Never, QString::null); setItem( row, 0, tmp ); //setRowHeight( row, 40); } initHeader(); QObject::connect( qApp, SIGNAL(clockChanged(bool)), this, SLOT(slotChangeClock(bool)) ); } void DateBookDayView::initHeader() { QString strTmp; int preferredWidth = 0; for ( int i = 0; i < 24; ++i ) { if ( ampm ) { if ( i == 0 ) strTmp = QString::number(12) + ":00"; else if ( i == 12 ) strTmp = QString::number(12) + tr(":00p"); else if ( i > 12 ) strTmp = QString::number( i - 12 ) + tr(":00p"); else strTmp = QString::number(i) + ":00"; } else { if ( i < 10 ) strTmp = "0" + QString::number(i) + ":00"; else strTmp = QString::number(i) + ":00"; } strTmp = strTmp.rightJustify( 6, ' ' ); verticalHeader()->setLabel( i, strTmp ); // Compute correct width for current Font (Add some space right) int actWidth = QFontMetrics( QFont::defaultFont() ).width( strTmp + QString(" ") ); if ( preferredWidth < actWidth ) preferredWidth = actWidth; setRowStretchable( i, FALSE ); } // It seems as if the header has a bug. It does not resize // correct horizontally if it is used vertical.. // Thus, we do it manually.. setLeftMargin( preferredWidth ); } void DateBookDayView::slotDateChanged( int y, int m, int d ) { currDate.setYMD(y,m,d); } void DateBookDayView::slotChangeClock( bool newClock ) { ampm = newClock; initHeader(); } bool DateBookDayView::whichClock() const { return ampm; } void DateBookDayView::moveUp() { scrollBy(0, -20); } void DateBookDayView::moveDown() { scrollBy(0, 20); } void DateBookDayView::paintCell( QPainter *p, int, int, const QRect &cr, bool ) { int w = cr.width(); int h = cr.height(); p->fillRect( 0, 0, w, h, colorGroup().brush( QColorGroup::Base ) ); if ( showGrid() ) { // Draw our lines int x2 = w - 1; int y2 = h - 1; QPen pen( p->pen() ); p->setPen( colorGroup().dark() ); p->drawLine( x2, 0, x2, y2 ); p->drawLine( 0, y2, x2, y2 ); p->setPen( colorGroup().midlight() ); p->drawLine( 0, y2 - h/2, x2, y2 - h/2); p->setPen( pen ); } } void DateBookDayView::paintFocus( QPainter *, const QRect & ) { } void DateBookDayView::resizeEvent( QResizeEvent *e ) { QTable::resizeEvent( e ); columnWidthChanged( 0 ); emit sigColWidthChanged(); } void DateBookDayView::keyPressEvent( QKeyEvent *e ) { QString txt = e->text(); if ( !txt.isNull() && txt[0] > ' ' && e->key() < 0x1000 ) { // we this is some sort of thing we know about... e->accept(); emit sigCapturedKey( txt ); } else { // I don't know what this key is, do you? e->ignore(); } } void DateBookDayView::setRowStyle( int style ) { if (style<0) style = 0; for (int i=0; i<numRows(); i++) setRowHeight(i, style*10+20); } void DateBookDayView::contentsMouseReleaseEvent( QMouseEvent* /* e */ ) { int sh=99,eh=-1; for(int i=0;i<this->numSelections();i++) { QTableSelection sel = this->selection( i ); sh = QMIN(sh,sel.topRow()); eh = QMAX(sh,sel.bottomRow()+1); } if (sh > 23 || eh < 1) { sh=8; eh=9; } quickLineEdit=new DateBookDayViewQuickLineEdit(QDateTime(currDate,QTime(sh,0,0,0)),QDateTime(currDate,QTime(eh,0,0,0)),this->viewport(),"quickedit"); quickLineEdit->setGeometry(0,0,this->columnWidth(0)-1,this->rowHeight(0)); this->moveChild(quickLineEdit,0,sh*this->rowHeight(0)); quickLineEdit->setFocus(); quickLineEdit->show(); } //=========================================================================== DateBookDayViewQuickLineEdit::DateBookDayViewQuickLineEdit(const QDateTime &start, const QDateTime &end,QWidget * parent, const char *name) : QLineEdit(parent,name) { active=1; quickEvent.setStart(start); quickEvent.setEnd(end); connect(this,SIGNAL(returnPressed()),this,SLOT(slotReturnPressed())); } void DateBookDayViewQuickLineEdit::slotReturnPressed() { if(active && (!this->text().isEmpty())) { // Fix to avoid having this event beeing added multiple times. quickEvent.setDescription(this->text()); - connect(this,SIGNAL(insertEvent(const Event &)),this->topLevelWidget(),SLOT(insertEvent(const Event &))); + connect(this,SIGNAL(insertEvent(const Event&)),this->topLevelWidget(),SLOT(insertEvent(const Event&))); emit(insertEvent(quickEvent)); active=0; } /* we need to return to this object.. */ QTimer::singleShot(500, this, SLOT(finallyCallClose()) ); // Close and also delete this widget } void DateBookDayViewQuickLineEdit::finallyCallClose() { close(true); // also deletes this widget... } void DateBookDayViewQuickLineEdit::focusOutEvent ( QFocusEvent* /* e */) { slotReturnPressed(); // Reuse code to add event and close this widget. } //=========================================================================== DateBookDay::DateBookDay( bool ampm, bool startOnMonday, DateBookDB *newDb, QWidget *parent, const char *name ) : QVBox( parent, name ), currDate( QDate::currentDate() ), db( newDb ), startTime( 0 ) { widgetList.setAutoDelete( true ); header = new DateBookDayHeader( startOnMonday, this, "day header" ); header->setDate( currDate.year(), currDate.month(), currDate.day() ); m_allDays = new DatebookdayAllday(newDb, this, "all day event list" ); m_allDays->hide(); view = new DateBookDayView( ampm, this, "day view" ); - connect( header, SIGNAL( dateChanged( int, int, int ) ), this, SLOT( dateChanged( int, int, int ) ) ); - connect( header, SIGNAL( dateChanged( int, int, int ) ), view, SLOT( slotDateChanged( int, int, int ) ) ); + connect( header, SIGNAL( dateChanged(int,int,int) ), this, SLOT( dateChanged(int,int,int) ) ); + connect( header, SIGNAL( dateChanged(int,int,int) ), view, SLOT( slotDateChanged(int,int,int) ) ); connect( view, SIGNAL( sigColWidthChanged() ), this, SLOT( slotColWidthChanged() ) ); connect( qApp, SIGNAL(weekChanged(bool)), this, SLOT(slotWeekChanged(bool)) ); - connect( view, SIGNAL(sigCapturedKey(const QString &)), this, SIGNAL(sigNewEvent(const QString&)) ); + connect( view, SIGNAL(sigCapturedKey(const QString&)), this, SIGNAL(sigNewEvent(const QString&)) ); QTimer *timer = new QTimer( this ); connect( timer, SIGNAL(timeout()), this, SLOT(updateView()) ); //connect timer for updating timeMarker & daywidgetcolors timer->start( 1000*60*5, FALSE ); //update every 5min selectedWidget = 0; timeMarker = new DateBookDayTimeMarker( this ); timeMarker->setTime( QTime::currentTime() ); rowStyle = -1; // initialize with bogus values jumpToCurTime = false; } void DateBookDay::setJumpToCurTime( bool bJump ) { jumpToCurTime = bJump; } void DateBookDay::setRowStyle( int style ) { if (rowStyle != style) view->setRowStyle( style ); rowStyle = style; } void DateBookDay::updateView( void ) { timeMarker->setTime( QTime::currentTime() ); //need to find a way to update all DateBookDayWidgets } void DateBookDay::setSelectedWidget( DateBookDayWidget *w ) { selectedWidget = w; } DateBookDayWidget * DateBookDay::getSelectedWidget( void ) { return selectedWidget; } void DateBookDay::selectedDates( QDateTime &start, QDateTime &end ) { start.setDate( currDate ); end.setDate( currDate ); int sh=99,eh=-1; int n = dayView()->numSelections(); for (int i=0; i<n; i++) { QTableSelection sel = dayView()->selection( i ); sh = QMIN(sh,sel.topRow()); eh = QMAX(sh,sel.bottomRow()+1); } if (sh > 23 || eh < 1) { sh=8; eh=9; } start.setTime( QTime( sh, 0, 0 ) ); end.setTime( QTime( eh, 0, 0 ) ); } void DateBookDay::setDate( int y, int m, int d ) { header->setDate( y, m, d ); selectedWidget = 0; } void DateBookDay::setDate( QDate d) { header->setDate( d.year(), d.month(), d.day() ); selectedWidget = 0; } void DateBookDay::dateChanged( int y, int m, int d ) { QDate date( y, m, d ); if ( currDate == date ) return; currDate.setYMD( y, m, d ); relayoutPage(); dayView()->clearSelection(); QTableSelection ts; if (jumpToCurTime && this->date() == QDate::currentDate()) { ts.init( QTime::currentTime().hour(), 0); ts.expandTo( QTime::currentTime().hour(), 0); } else { ts.init( startTime, 0 ); ts.expandTo( startTime, 0 ); } dayView()->addSelection( ts ); selectedWidget = 0; } void DateBookDay::redraw() { if ( isUpdatesEnabled() ) relayoutPage(); } void DateBookDay::getEvents() { widgetList.clear(); /* clear the AllDay List */ m_allDays->hide(); // just in case m_allDays->removeAllEvents(); QValueList<EffectiveEvent> eventList = db->getEffectiveEvents( currDate, currDate ); QValueListIterator<EffectiveEvent> it; QObject* object = 0; for ( it = eventList.begin(); it != eventList.end(); ++it ) { EffectiveEvent ev=*it; if(!((ev.end().hour()==0) && (ev.end().minute()==0) && (ev.startDate()!=ev.date()))) { // Skip events ending at 00:00 starting at another day. if (ev.event().type() == Event::AllDay ) { object = m_allDays->addEvent( ev ); if (!object) continue; }else { DateBookDayWidget* w = new DateBookDayWidget( *it, this ); widgetList.append( w ); object = w; } - connect( object, SIGNAL( deleteMe( const Event & ) ), this, SIGNAL( removeEvent( const Event & ) ) ); - connect( object, SIGNAL( duplicateMe( const Event & ) ), this, SIGNAL( duplicateEvent( const Event & ) ) ); - connect( object, SIGNAL( editMe( const Event & ) ), this, SIGNAL( editEvent( const Event & ) ) ); - connect( object, SIGNAL( beamMe( const Event & ) ), this, SIGNAL( beamEvent( const Event & ) ) ); + connect( object, SIGNAL( deleteMe(const Event&) ), this, SIGNAL( removeEvent(const Event&) ) ); + connect( object, SIGNAL( duplicateMe(const Event&) ), this, SIGNAL( duplicateEvent(const Event&) ) ); + connect( object, SIGNAL( editMe(const Event&) ), this, SIGNAL( editEvent(const Event&) ) ); + connect( object, SIGNAL( beamMe(const Event&) ), this, SIGNAL( beamEvent(const Event&) ) ); } } } static int place( const DateBookDayWidget *item, bool *used, int maxn ) { int place = 0; int start = item->event().start().hour(); QTime e = item->event().end(); int end = e.hour(); if ( e.minute() < 5 ) end--; if ( end < start ) end = start; while ( place < maxn ) { bool free = TRUE; int s = start; while( s <= end ) { if ( used[10*s+place] ) { free = FALSE; break; } s++; } if ( free ) break; place++; } if ( place == maxn ) { return -1; } while( start <= end ) { used[10*start+place] = TRUE; start++; } return place; } void DateBookDay::relayoutPage( bool fromResize ) { setUpdatesEnabled( FALSE ); if ( !fromResize ) { getEvents(); // no need we already have them! if (m_allDays->items() > 0 ) m_allDays->show(); /* * else if ( m_allDays->items() == 0 ) already hide in getEvents */ } widgetList.sort(); //sorts the widgetList by the heights of the widget so that the tallest widgets are at the beginning //this is needed for the simple algo below to work correctly, otherwise some widgets would be drawn outside the view int wCount = widgetList.count(); int wid = view->columnWidth(0)-1; int wd; int n = 1; QArray<int> anzIntersect(wCount); //this stores the number of maximal intersections of each widget for (int i = 0; i<wCount; anzIntersect[i] = 1, i++); if ( wCount < 20 ) { QArray<QRect> geometries(wCount); for (int i = 0; i < wCount; geometries[i] = widgetList.at(i)->geometry(), i++); //stores geometry for each widget in vector for ( int i = 0; i < wCount; i++) { QValueList<int> intersectedWidgets; //find all widgets intersecting with widgetList.at(i) for ( int j = 0; j < wCount; j++) { if (i != j) if (geometries[j].intersects(geometries[i])) intersectedWidgets.append(j); } //for each of these intersecting widgets find out how many widgets are they intersecting with for ( uint j = 0; j < intersectedWidgets.count(); j++) { QArray<int> inter(wCount); inter[j]=1; if (intersectedWidgets[j] != -1) for ( uint k = j; k < intersectedWidgets.count(); k++) { if (j != k && intersectedWidgets[k] != -1) if (geometries[intersectedWidgets[k]].intersects(geometries[intersectedWidgets[j]])) { inter[j]++; intersectedWidgets[k] = -1; } if (inter[j] > anzIntersect[i]) anzIntersect[i] = inter[j] + 1; } } if (anzIntersect[i] == 1 && intersectedWidgets.count()) anzIntersect[i]++; } for ( int i = 0; i < wCount; i++) { DateBookDayWidget *w = widgetList.at(i); QRect geom = w->geometry(); geom.setX( 0 ); wd = (view->columnWidth(0)-1) / anzIntersect[i] - (anzIntersect[i]>1?2:0); geom.setWidth( wd ); while ( intersects( w, geom ) ) { geom.moveBy( wd + 2 + 1, 0 ); } w->setGeometry( geom ); } if (jumpToCurTime && this->date() == QDate::currentDate()) { view->setContentsPos( 0, QTime::currentTime().hour() * view->rowHeight(0) ); //set listview to current hour } else { view->setContentsPos( 0, startTime * view->rowHeight(0) ); } } else { int hours[24]; memset( hours, 0, 24*sizeof( int ) ); bool overFlow = FALSE; for ( int i = 0; i < wCount; i++ ) { DateBookDayWidget *w = widgetList.at(i); int start = w->event().start().hour(); QTime e = w->event().end(); int end = e.hour(); if ( e.minute() < 5 ) end--; if ( end < start ) end = start; while( start <= end ) { hours[start]++; if ( hours[start] >= 10 ) overFlow = TRUE; ++start; } if ( overFlow ) break; } for ( int i = 0; i < 24; i++ ) { n = QMAX( n, hours[i] ); } wid = ( view->columnWidth(0)-1 ) / n; bool used[24*10]; memset( used, FALSE, 24*10*sizeof( bool ) ); for ( int i = 0; i < wCount; i++ ) { DateBookDayWidget *w = widgetList.at(i); int xp = place( w, used, n ); if ( xp != -1 ) { QRect geom = w->geometry(); geom.setX( xp*(wid+2) ); geom.setWidth( wid ); w->setGeometry( geom ); } } if (jumpToCurTime && this->date() == QDate::currentDate()) { view->setContentsPos( 0, QTime::currentTime().hour() * view->rowHeight(0) ); //set listview to current hour } else { view->setContentsPos( 0, startTime * view->rowHeight(0) ); } } timeMarker->setTime( QTime::currentTime() ); //display timeMarker timeMarker->raise(); //on top of all widgets if (this->date() == QDate::currentDate()) { //only show timeMarker on current day timeMarker->show(); } else { timeMarker->hide(); } setUpdatesEnabled( TRUE ); return; } DateBookDayWidget *DateBookDay::intersects( const DateBookDayWidget *item, const QRect &geom ) { int i = 0; DateBookDayWidget *w = widgetList.at(i); int wCount = widgetList.count(); while ( i < wCount && w != item ) { if ( w->geometry().intersects( geom ) ) { return w; } w = widgetList.at(++i); } return 0; } diff --git a/core/pim/datebook/datebookdayallday.cpp b/core/pim/datebook/datebookdayallday.cpp index d43d31a..a0aefd3 100644 --- a/core/pim/datebook/datebookdayallday.cpp +++ b/core/pim/datebook/datebookdayallday.cpp @@ -1,226 +1,226 @@ /**************************************************************************** ** GPL by Rajko Albrecht ** ** ** ** ** ****************************************************************************/ #include "datebookdayallday.h" #include <qlayout.h> #include <qpe/ir.h> #include <qpopupmenu.h> #include <qtimer.h> #include "datebookday.h" /* * Constructs a DatebookdayAllday which is a child of 'parent', with the * name 'name' and widget flags set to 'f' */ DatebookdayAllday::DatebookdayAllday(DateBookDB* db, QWidget* parent, const char* name, WFlags ) : QScrollView( parent, name ),item_count(0),dateBook(db) { if ( !name ) setName( "DatebookdayAllday" ); setMinimumSize( QSize( 0, 0 ) ); setMaximumHeight(3* (QFontMetrics(font()).height()+4) ); m_MainFrame = new QFrame(viewport()); m_MainFrame->setFrameStyle(QFrame::NoFrame|QFrame::Plain); setFrameStyle(QFrame::NoFrame|QFrame::Plain); setResizePolicy( QScrollView::Default ); setHScrollBarMode( AlwaysOff ); addChild(m_MainFrame); datebookdayalldayLayout = new QVBoxLayout( m_MainFrame ); datebookdayalldayLayout->setSpacing( 0 ); datebookdayalldayLayout->setMargin( 0 ); lblDesc = new DatebookEventDesc(parent->parentWidget(),""); lblDesc->setBackgroundColor(Qt::yellow); lblDesc->hide(); subWidgets.setAutoDelete(true); } /* * Destroys the object and frees any allocated resources */ DatebookdayAllday::~DatebookdayAllday() { // no need to delete child widgets, Qt does it all for us } DatebookAlldayDisp* DatebookdayAllday::addEvent(const EffectiveEvent&ev) { DatebookAlldayDisp * lb; lb = new DatebookAlldayDisp(dateBook,ev,m_MainFrame,NULL); lb->show(); datebookdayalldayLayout->addWidget(lb); subWidgets.append(lb); - connect(lb,SIGNAL(displayMe(const Event &)),lblDesc,SLOT(disp_event(const Event&))); + connect(lb,SIGNAL(displayMe(const Event&)),lblDesc,SLOT(disp_event(const Event&))); ++item_count; return lb; } void DatebookdayAllday::removeAllEvents() { subWidgets.clear(); item_count = 0; } DatebookAlldayDisp::DatebookAlldayDisp(DateBookDB *db,const EffectiveEvent& ev, QWidget* parent,const char* name,WFlags f) : QLabel(parent,name,f),m_Ev(ev),dateBook(db) { QString strDesc = m_Ev.description(); strDesc = strDesc.replace(QRegExp("<"),"<"); setBackgroundColor(yellow); setText(strDesc); setFrameStyle(QFrame::Raised|QFrame::Panel); int s = QFontMetrics(font()).height()+4; setMaximumHeight( s ); setMinimumSize( QSize( 0, s ) ); } DatebookAlldayDisp::~DatebookAlldayDisp() { } void DatebookAlldayDisp::beam_single_event() { // create an Event and beam it... /* * Start with the easy stuff. If start and end date is the same we can just use * the values of effective m_Events * If it is a multi day m_Event we need to find the real start and end date... */ if ( m_Ev.event().start().date() == m_Ev.event().end().date() ) { Event m_Event( m_Ev.event() ); QDateTime dt( m_Ev.date(), m_Ev.start() ); m_Event.setStart( dt ); dt.setTime( m_Ev.end() ); m_Event.setEnd( dt ); emit beamMe( m_Event ); }else { /* * at least the the Times are right now */ QDateTime start( m_Ev.event().start() ); QDateTime end ( m_Ev.event().end () ); /* * ok we know the start date or we need to find it */ if ( m_Ev.start() != QTime( 0, 0, 0 ) ) { start.setDate( m_Ev.date() ); }else { QDate dt = DateBookDay::findRealStart( m_Ev.event().uid(), m_Ev.date(), dateBook ); start.setDate( dt ); } /* * ok we know now the end date... * else * get to know the offset btw the real start and real end * and then add it to the new start date... */ if ( m_Ev.end() != QTime(23, 59, 59 ) ) { end.setDate( m_Ev.date() ); }else{ int days = m_Ev.event().start().date().daysTo( m_Ev.event().end().date() ); end.setDate( start.date().addDays( days ) ); } Event m_Event( m_Ev.event() ); m_Event.setStart( start ); m_Event.setEnd ( end ); emit beamMe( m_Event ); } } void DatebookAlldayDisp::mousePressEvent(QMouseEvent*e) { Event ev = m_Ev.event(); QColor b = backgroundColor(); setBackgroundColor(green); update(); QPopupMenu m; m.insertItem( DateBookDayWidget::tr( "Edit" ), 1 ); m.insertItem( DateBookDayWidget::tr( "Duplicate" ), 4 ); m.insertItem( DateBookDayWidget::tr( "Delete" ), 2 ); if(Ir::supported()) m.insertItem( DateBookDayWidget::tr( "Beam" ), 3 ); if(Ir::supported() && m_Ev.event().doRepeat() ) m.insertItem( DateBookDayWidget::tr( "Beam this occurence"), 5 ); m.insertItem( tr( "Info"),6); int r = m.exec( e->globalPos() ); setBackgroundColor(b); update(); switch (r) { case 1: emit editMe( ev ); break; case 2: emit deleteMe( ev ); break; case 3: emit beamMe( ev ); break; case 4: emit duplicateMe( ev ); break; case 5: beam_single_event(); break; case 6: emit displayMe( ev ); break; default: break; } } DatebookEventDesc::DatebookEventDesc(QWidget*parent,const char*name) :QLabel(parent,name) { m_Timer=new QTimer(this); connect(m_Timer,SIGNAL(timeout()),this,SLOT(hide())); setFrameStyle(QFrame::Sunken|QFrame::Panel); setTextFormat(RichText); } DatebookEventDesc::~DatebookEventDesc() { } void DatebookEventDesc::mousePressEvent(QMouseEvent*) { hide(); if (m_Timer->isActive()) m_Timer->stop(); } void DatebookEventDesc::disp_event(const Event&e) { if (m_Timer->isActive()) m_Timer->stop(); QString text; text = "<b><i>"+e.description()+"</i></b><br>"; if (e.notes().length()>0) { text+="<b>"+e.notes()+"</b><br>"; } if (e.location().length()>0) { text+="<i>"+e.location()+"</i><br>"; } text = text.replace(QRegExp("\n"),"<br>"); setText(text); QSize s = sizeHint(); s+=QSize(10,10); resize(s); move( QMAX(0,(parentWidget()->width()-width()) / 2), (parentWidget()->height()-height())/2 ); show(); m_Timer->start(2000,true); } diff --git a/core/pim/datebook/datebookdayheaderimpl.cpp b/core/pim/datebook/datebookdayheaderimpl.cpp index 213c843..51b78ca 100644 --- a/core/pim/datebook/datebookdayheaderimpl.cpp +++ b/core/pim/datebook/datebookdayheaderimpl.cpp @@ -1,200 +1,200 @@ /********************************************************************** ** Copyright (C) 2000 Trolltech AS. All rights reserved. ** ** This file is part of Qtopia Environment. ** ** This file may be distributed and/or modified under the terms of the ** GNU General Public License version 2 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. ** ** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE ** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. ** ** See http://www.trolltech.com/gpl/ for GPL licensing information. ** ** Contact info@trolltech.com if any conditions of this licensing are ** not clear to you. ** **********************************************************************/ #include "datebookdayheaderimpl.h" #include <qpe/datebookmonth.h> #include <qpe/resource.h> #include <qbuttongroup.h> #include <qtoolbutton.h> /* * Constructs a DateBookDayHeader which is a child of 'parent', with the * name 'name' and widget flags set to 'f' * * The dialog will by default be modeless, unless you set 'modal' to * TRUE to construct a modal dialog. */ DateBookDayHeader::DateBookDayHeader( bool useMonday, QWidget* parent, const char* name ) : DateBookDayHeaderBase( parent, name ), bUseMonday( useMonday ) { connect(date,SIGNAL(pressed()),this,SLOT(pickDate())); setupNames(); forward->setPixmap( Resource::loadPixmap( "forward" ) ); back->setPixmap( Resource::loadPixmap( "back" ) ); forwardweek->setPixmap( Resource::loadPixmap( "fastforward" ) ); backweek->setPixmap( Resource::loadPixmap( "fastback" ) ); setBackgroundMode( PaletteButton ); grpDays->setBackgroundMode( PaletteButton ); } /* * Destroys the object and frees any allocated resources */ DateBookDayHeader::~DateBookDayHeader() { // no need to delete child widgets, Qt does it all for us } void DateBookDayHeader::setStartOfWeek( bool onMonday ) { bUseMonday = onMonday; setupNames(); setDate( currDate.year(), currDate.month(), currDate.day() ); } void DateBookDayHeader::setupNames() { if ( bUseMonday ) { cmdDay1->setText( DateBookDayHeaderBase::tr("Monday").left(1) ); cmdDay2->setText( DateBookDayHeaderBase::tr("Tuesday").left(1) ); cmdDay3->setText( DateBookDayHeaderBase::tr("Wednesday").left(1) ); cmdDay4->setText( DateBookDayHeaderBase::tr("Thursday").left(1) ); cmdDay5->setText( DateBookDayHeaderBase::tr("Friday").left(1) ); cmdDay6->setText( DateBookDayHeaderBase::tr("Saturday").left(1) ); cmdDay7->setText( DateBookDayHeaderBase::tr("Sunday").left(1) ); } else { cmdDay1->setText( DateBookDayHeaderBase::tr("Sunday").left(1) ); cmdDay2->setText( DateBookDayHeaderBase::tr("Monday").left(1) ); cmdDay3->setText( DateBookDayHeaderBase::tr("Tuesday").left(1) ); cmdDay4->setText( DateBookDayHeaderBase::tr("Wednesday").left(1) ); cmdDay5->setText( DateBookDayHeaderBase::tr("Thursday").left(1) ); cmdDay6->setText( DateBookDayHeaderBase::tr("Friday").left(1) ); cmdDay7->setText( DateBookDayHeaderBase::tr("Saturday").left(1) ); } } void DateBookDayHeader::pickDate() { static QPopupMenu *m1 = 0; static DateBookMonth *picker = 0; if ( !m1 ) { m1 = new QPopupMenu( this ); picker = new DateBookMonth( m1, 0, TRUE ); m1->insertItem( picker ); - connect( picker, SIGNAL( dateClicked( int, int, int ) ), - this, SLOT( setDate( int, int, int ) ) ); + connect( picker, SIGNAL( dateClicked(int,int,int) ), + this, SLOT( setDate(int,int,int) ) ); connect( m1, SIGNAL( aboutToHide() ), this, SLOT( gotHide() ) ); } picker->setDate( currDate.year(), currDate.month(), currDate.day() ); m1->popup(mapToGlobal(date->pos()+QPoint(0,date->height()))); picker->setFocus(); } void DateBookDayHeader::gotHide() { // we have to redo the button... date->setDown( false ); } /* * public slot */ void DateBookDayHeader::goBack() { currDate = currDate.addDays( -1 ); setDate( currDate.year(), currDate.month(), currDate.day() ); } /* * public slot */ void DateBookDayHeader::goForward() { currDate = currDate.addDays( 1 ); setDate( currDate.year(), currDate.month(), currDate.day() ); } /* * public slot */ void DateBookDayHeader::goBackWeek() { currDate = currDate.addDays( -7 ); setDate( currDate.year(), currDate.month(), currDate.day() ); } /* * public slot */ void DateBookDayHeader::goForwardWeek() { currDate = currDate.addDays( 7 ); setDate( currDate.year(), currDate.month(), currDate.day() ); } /* * public slot */ void DateBookDayHeader::setDate( int y, int m, int d ) { currDate.setYMD( y, m, d ); date->setText( TimeString::shortDate( currDate ) ); int iDayOfWeek = currDate.dayOfWeek(); // cleverly adjust the day depending on how we start the week if ( bUseMonday ) iDayOfWeek--; else { if ( iDayOfWeek == 7 ) // Sunday iDayOfWeek = 0; } grpDays->setButton( iDayOfWeek ); emit dateChanged( y, m, d ); } /* * public slot */ void DateBookDayHeader::setDay( int day ) { int realDay; int dayOfWeek = currDate.dayOfWeek(); // a little adjustment is needed... if ( bUseMonday ) realDay = day + 1 ; else if ( !bUseMonday && day == 0 ) // sunday realDay = 7; else realDay = day; // special cases first... if ( realDay == 7 && !bUseMonday ) { while ( currDate.dayOfWeek() != realDay ) currDate = currDate.addDays( -1 ); } else if ( !bUseMonday && dayOfWeek == 7 && dayOfWeek > realDay ) { while ( currDate.dayOfWeek() != realDay ) currDate = currDate.addDays( 1 ); } else if ( dayOfWeek < realDay ) { while ( currDate.dayOfWeek() < realDay ) currDate = currDate.addDays( 1 ); } else if ( dayOfWeek > realDay ) { while ( currDate.dayOfWeek() > realDay ) currDate = currDate.addDays( -1 ); } // update the date... setDate( currDate.year(), currDate.month(), currDate.day() ); } diff --git a/core/pim/datebook/datebooksettings.cpp b/core/pim/datebook/datebooksettings.cpp index a6d04ba..cb4b73b 100644 --- a/core/pim/datebook/datebooksettings.cpp +++ b/core/pim/datebook/datebooksettings.cpp @@ -1,155 +1,155 @@ /********************************************************************** ** Copyright (C) 2000 Trolltech AS. All rights reserved. ** ** This file is part of Qtopia Environment. ** ** This file may be distributed and/or modified under the terms of the ** GNU General Public License version 2 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. ** ** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE ** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. ** ** See http://www.trolltech.com/gpl/ for GPL licensing information. ** ** Contact info@trolltech.com if any conditions of this licensing are ** not clear to you. ** **********************************************************************/ #include "datebooksettings.h" #include <qpe/qpeapplication.h> #include <qspinbox.h> #include <qcheckbox.h> DateBookSettings::DateBookSettings( bool whichClock, QWidget *parent, const char *name, bool modal, WFlags fl ) : DateBookSettingsBase( parent, name, modal, fl ), ampm( whichClock ) { init(); - QObject::connect( qApp, SIGNAL( clockChanged( bool ) ), this, SLOT( slotChangeClock( bool ) ) ); + QObject::connect( qApp, SIGNAL( clockChanged(bool) ), this, SLOT( slotChangeClock(bool) ) ); QArray<int> categories; comboCategory->setCategories( categories, "Calendar", tr("Calendar") ); } DateBookSettings::~DateBookSettings() { } void DateBookSettings::setStartTime( int newStartViewTime ) { if ( ampm ) { if ( newStartViewTime >= 12 ) { newStartViewTime %= 12; if ( newStartViewTime == 0 ) newStartViewTime = 12; spinStart->setSuffix( tr(":00 PM") ); } else if ( newStartViewTime == 0 ) { newStartViewTime = 12; spinStart->setSuffix( tr(":00 AM") ); } oldtime = newStartViewTime; } spinStart->setValue( newStartViewTime ); } int DateBookSettings::startTime() const { int returnMe = spinStart->value(); if ( ampm ) { if ( returnMe != 12 && spinStart->suffix().contains(tr("PM"), FALSE) ) returnMe += 12; else if (returnMe == 12 && spinStart->suffix().contains(tr("AM"), TRUE)) returnMe = 0; } return returnMe; } void DateBookSettings::setAlarmPreset( bool bAlarm, int presetTime ) { chkAlarmPreset->setChecked( bAlarm ); if ( presetTime >=5 ) spinPreset->setValue( presetTime ); } bool DateBookSettings::alarmPreset() const { return chkAlarmPreset->isChecked(); } int DateBookSettings::presetTime() const { return spinPreset->value(); } void DateBookSettings::slot12Hour( int i ) { if ( ampm ) { if ( spinStart->suffix().contains( tr("AM"), FALSE ) ) { if ( oldtime == 12 && i == 11 || oldtime == 11 && i == 12 ) spinStart->setSuffix( tr(":00 PM") ); } else { if ( oldtime == 12 && i == 11 || oldtime == 11 && i == 12 ) spinStart->setSuffix( tr(":00 AM") ); } oldtime = i; } } void DateBookSettings::init() { if ( ampm ) { spinStart->setMinValue( 1 ); spinStart->setMaxValue( 12 ); spinStart->setValue( 12 ); spinStart->setSuffix( tr(":00 AM") ); oldtime = 12; } else { spinStart->setMinValue( 0 ); spinStart->setMaxValue( 23 ); spinStart->setSuffix( tr(":00") ); } } void DateBookSettings::slotChangeClock( bool whichClock ) { int saveMe; saveMe = spinStart->value(); if ( ampm && spinStart->suffix().contains( tr("AM"), FALSE ) ) { if ( saveMe == 12 ) saveMe = 0; } else if ( ampm && spinStart->suffix().contains( tr("PM"), FALSE ) ) { if ( saveMe != 12 ) saveMe += 12; } ampm = whichClock; init(); setStartTime( saveMe ); } void DateBookSettings::setJumpToCurTime( bool bJump ) { chkJumpToCurTime->setChecked( bJump ); } bool DateBookSettings::jumpToCurTime() const { return chkJumpToCurTime->isChecked(); } void DateBookSettings::setRowStyle( int style ) { comboRowStyle->setCurrentItem( style ); } int DateBookSettings::rowStyle() const { return comboRowStyle->currentItem(); } diff --git a/core/pim/datebook/datebookweek.cpp b/core/pim/datebook/datebookweek.cpp index 933e191..7503751 100644 --- a/core/pim/datebook/datebookweek.cpp +++ b/core/pim/datebook/datebookweek.cpp @@ -173,388 +173,388 @@ void DateBookWeekView::positionItem( DateBookWeekItem *i ) const EffectiveEvent ev = i->event(); // 30 minute intervals int y = ev.start().hour() * 2; y += db_round30min( ev.start().minute() ); int y2 = ev.end().hour() * 2; y2 += db_round30min( ev.end().minute() ); if ( y > 47 ) y = 47; if ( y2 > 48 ) y2 = 48; y = (y * rowHeight) / 2; y2 = (y2 * rowHeight) / 2; int h; if ( ev.event().type() == Event::AllDay ) { h = (48 * rowHeight) / 2; y = 0; } else { h=y2-y; if ( h < (1*rowHeight)/2 ) h = (1*rowHeight)/2; } int dow = ev.date().dayOfWeek(); if ( !bOnMonday ) { if ( dow == 7 ) dow = 1; else dow++; } int x = header->sectionPos( dow ) - 1; int xlim = header->sectionPos( dow ) + header->sectionSize( dow ); DateBookWeekItem *isect = 0; do { i->setGeometry( x, y, Width, h ); isect = intersects( i ); x += Width - 1; } while ( isect && x < xlim ); } DateBookWeekItem *DateBookWeekView::intersects( const DateBookWeekItem *item ) { QRect geom = item->geometry(); // We allow the edges to overlap geom.moveBy( 1, 1 ); geom.setSize( geom.size()-QSize(2,2) ); QListIterator<DateBookWeekItem> it(items); for ( ; it.current(); ++it ) { DateBookWeekItem *i = it.current(); if ( i != item ) { if ( i->geometry().intersects( geom ) ) { return i; } } } return 0; } void DateBookWeekView::contentsMousePressEvent( QMouseEvent *e ) { QListIterator<DateBookWeekItem> it(items); for ( ; it.current(); ++it ) { DateBookWeekItem *i = it.current(); if ( i->geometry().contains( e->pos() ) ) { showingEvent = true; emit signalShowEvent( i->event() ); break; } } } void DateBookWeekView::contentsMouseReleaseEvent( QMouseEvent *e ) { if ( showingEvent ) { showingEvent = false; emit signalHideEvent(); } else { int d = header->sectionAt( e->pos().x() ); if ( d > 0 ) { // if ( !bOnMonday ) // d--; emit showDay( d ); } } } void DateBookWeekView::drawContents( QPainter *p, int cx, int cy, int cw, int ch ) { QRect ur( cx, cy, cw, ch ); p->setPen( lightGray ); for ( int i = 1; i <= 7; i++ ) p->drawLine( header->sectionPos(i)-2, cy, header->sectionPos(i)-2, cy+ch ); p->setPen( black ); for ( int t = 0; t < 24; t++ ) { int y = t*rowHeight; if ( QRect( 1, y, 20, rowHeight ).intersects( ur ) ) { QString s; if ( ampm ) { if ( t == 0 ) s = QString::number( 12 ); else if ( t == 12 ) s = QString::number(12) + tr( "p" ); else if ( t > 12 ) { if ( t - 12 < 10 ) s = " "; else s = ""; s += QString::number( t - 12 ) + tr("p"); } else { if ( 12 - t < 3 ) s = ""; else s = " "; s += QString::number( t ); } } else { s = QString::number( t ); if ( s.length() == 1 ) s.prepend( "0" ); } p->drawText( 1, y+p->fontMetrics().ascent()+1, s ); } } QListIterator<DateBookWeekItem> it(items); for ( ; it.current(); ++it ) { DateBookWeekItem *i = it.current(); if ( i->geometry().intersects( ur ) ) { p->setBrush( i->color() ); p->drawRect( i->geometry() ); } } } void DateBookWeekView::resizeEvent( QResizeEvent *e ) { const int hourWidth = 20; QScrollView::resizeEvent( e ); //HEAD /* int avail = visibleWidth(); header->setGeometry( leftMargin()+frameWidth()+frameRect().left() , frameWidth(), visibleWidth(), header->sizeHint().height() ); setMargins( 0, header->sizeHint().height(), 0, 0 ); */ //BRANCH_1_0 int avail = width()-qApp->style().scrollBarExtent().width()-1; header->setGeometry( 0, 0, avail, header->sizeHint().height() ); setMargins( 0, header->height(), 0, 0 ); header->resizeSection( 0, hourWidth ); int sw = (avail - hourWidth) / 7; for ( int i = 1; i < 7; i++ ) header->resizeSection( i, sw ); header->resizeSection( 7, avail - hourWidth - sw*6 ); } void DateBookWeekView::setStartOfWeek( bool bStartOnMonday ) { bOnMonday = bStartOnMonday; initNames(); } //------------------------------------------------------------------- DateBookWeek::DateBookWeek( bool ap, bool startOnMonday, DateBookDB *newDB, QWidget *parent, const char *name ) : QWidget( parent, name ), db( newDB ), startTime( 0 ), ampm( ap ), bStartOnMonday( startOnMonday ) { setFocusPolicy(StrongFocus); QVBoxLayout *vb = new QVBoxLayout( this ); header = new DateBookWeekHeader( bStartOnMonday, this ); view = new DateBookWeekView( ampm, startOnMonday, this ); vb->addWidget( header ); vb->addWidget( view ); lblDesc = new QLabel( this, "event label" ); lblDesc->setFrameStyle( QFrame::Plain | QFrame::Box ); lblDesc->setBackgroundColor( yellow ); lblDesc->hide(); tHide = new QTimer( this ); - connect( view, SIGNAL( showDay( int ) ), this, SLOT( showDay( int ) ) ); + connect( view, SIGNAL( showDay(int) ), this, SLOT( showDay(int) ) ); connect( view, SIGNAL(signalShowEvent(const EffectiveEvent&)), this, SLOT(slotShowEvent(const EffectiveEvent&)) ); connect( view, SIGNAL(signalHideEvent()), this, SLOT(slotHideEvent()) ); - connect( header, SIGNAL( dateChanged( QDate &) ), this, SLOT( dateChanged( QDate &) ) ); + connect( header, SIGNAL( dateChanged(QDate&) ), this, SLOT( dateChanged(QDate&) ) ); connect( tHide, SIGNAL( timeout() ), lblDesc, SLOT( hide() ) ); connect( qApp, SIGNAL(weekChanged(bool)), this, SLOT(slotWeekChanged(bool)) ); connect( qApp, SIGNAL(clockChanged(bool)), this, SLOT(slotClockChanged(bool))); setDate(QDate::currentDate()); } void DateBookWeek::keyPressEvent(QKeyEvent *e) { switch(e->key()) { case Key_Up: view->scrollBy(0, -20); break; case Key_Down: view->scrollBy(0, 20); break; case Key_Left: setDate(date().addDays(-7)); break; case Key_Right: setDate(date().addDays(7)); break; default: e->ignore(); } } void DateBookWeek::showDay( int day ) { QDate d=bdate; // Calculate offset to first day of week. int dayoffset=d.dayOfWeek() % 7; if(bStartOnMonday) dayoffset--; day--; d=d.addDays(day-dayoffset); emit showDate( d.year(), d.month(), d.day() ); } void DateBookWeek::setDate( int y, int m, int d ) { setDate(QDate(y, m, d)); } void DateBookWeek::setDate(QDate newdate) { bdate=newdate; dow = newdate.dayOfWeek(); header->setDate( newdate ); } void DateBookWeek::dateChanged( QDate &newdate ) { bdate=newdate; getEvents(); } QDate DateBookWeek::date() const { return bdate; } void DateBookWeek::getEvents() { QDate startWeek = weekDate(); QDate endWeek = startWeek.addDays( 6 ); QValueList<EffectiveEvent> eventList = db->getEffectiveEvents(startWeek, endWeek); view->showEvents( eventList ); view->moveToHour( startTime ); } void DateBookWeek::generateAllDayTooltext( QString& text ) { text += "<b>" + tr("This is an all day event.") + "</b><br>"; } void DateBookWeek::generateNormalTooltext( QString& str, const EffectiveEvent &ev ) { str += "<b>" + QObject::tr("Start") + "</b>: "; str += TimeString::timeString( ev.event().start().time(), ampm, FALSE ); if( ev.startDate()!=ev.endDate() ) { str += " <i>" + TimeString::longDateString( ev.startDate() )+"</i>"; } str += "<br>"; str += "<b>" + QObject::tr("End") + "</b>: "; str += TimeString::timeString( ev.event().end().time(), ampm, FALSE ); if( ev.startDate()!=ev.endDate() ) { str += " <i>" + TimeString::longDateString( ev.endDate() ) + "</i>"; } } void DateBookWeek::slotShowEvent( const EffectiveEvent &ev ) { if ( tHide->isActive() ) tHide->stop(); // why would someone use "<"? Oh well, fix it up... // I wonder what other things may be messed up... QString strDesc = ev.description(); int where = strDesc.find( "<" ); while ( where != -1 ) { strDesc.remove( where, 1 ); strDesc.insert( where, "<" ); where = strDesc.find( "<", where ); } QString strCat; // ### FIX later... // QString strCat = ev.category(); // where = strCat.find( "<" ); // while ( where != -1 ) { // strCat.remove( where, 1 ); // strCat.insert( where, "<" ); // where = strCat.find( "<", where ); // } QString strLocation = ev.location(); while ( where != -1 ) { strLocation.remove( where, 1 ); strLocation.insert( where, "<" ); where = strLocation.find( "<", where ); } QString strNote = ev.notes(); where = strNote.find( "<" ); while ( where != -1 ) { strNote.remove( where, 1 ); strNote.insert( where, "<" ); where = strNote.find( "<", where ); } QString str = "<b>" + strDesc + "</b><br>" + strLocation + "<br>" + "<i>" + strCat + "</i>" + "<br>" + TimeString::longDateString( ev.date() ) + "<br>"; if (ev.event().type() == Event::Normal ) generateNormalTooltext( str, ev ); else generateAllDayTooltext( str ); str += "<br><br>" + strNote; lblDesc->setText( str ); lblDesc->resize( lblDesc->sizeHint() ); // move the label so it is "centerd" horizontally... lblDesc->move( QMAX(0,(width() - lblDesc->width()) / 2), 0 ); lblDesc->show(); } void DateBookWeek::slotHideEvent() { tHide->start( 2000, true ); } void DateBookWeek::setStartViewTime( int startHere ) { startTime = startHere; view->moveToHour( startTime ); } int DateBookWeek::startViewTime() const { return startTime; } void DateBookWeek::redraw() { getEvents(); } void DateBookWeek::slotYearChanged( int y ) { int totWeek; QDate d( y, 12, 31 ); int throwAway; calcWeek( d, totWeek, throwAway, bStartOnMonday ); while ( totWeek == 1 ) { d = d.addDays( -1 ); calcWeek( d, totWeek, throwAway, bStartOnMonday ); } } void DateBookWeek::slotWeekChanged( bool onMonday ) { bStartOnMonday = onMonday; view->setStartOfWeek( bStartOnMonday ); header->setStartOfWeek( bStartOnMonday ); redraw(); } diff --git a/core/pim/datebook/datebookweekheaderimpl.cpp b/core/pim/datebook/datebookweekheaderimpl.cpp index eaa9730..c237b2d 100644 --- a/core/pim/datebook/datebookweekheaderimpl.cpp +++ b/core/pim/datebook/datebookweekheaderimpl.cpp @@ -1,120 +1,120 @@ /********************************************************************** ** Copyright (C) 2000 Trolltech AS. All rights reserved. ** ** This file is part of Qtopia Environment. ** ** This file may be distributed and/or modified under the terms of the ** GNU General Public License version 2 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. ** ** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE ** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. ** ** See http://www.trolltech.com/gpl/ for GPL licensing information. ** ** Contact info@trolltech.com if any conditions of this licensing are ** not clear to you. ** **********************************************************************/ #include "datebookweekheaderimpl.h" #include "datebookweek.h" #include <qpe/resource.h> #include <qpe/datebookmonth.h> #include <qtoolbutton.h> /* * Constructs a DateBookWeekHeader which is a child of 'parent', with the * name 'name' and widget flags set to 'f' */ DateBookWeekHeader::DateBookWeekHeader( bool startOnMonday, QWidget* parent, const char* name, WFlags fl ) : DateBookWeekHeaderBase( parent, name, fl ), bStartOnMonday( startOnMonday ) { setBackgroundMode( PaletteButton ); labelDate->setBackgroundMode( PaletteButton ); backmonth->setPixmap( Resource::loadPixmap("fastback") ); backweek->setPixmap( Resource::loadPixmap("back") ); forwardweek->setPixmap( Resource::loadPixmap("forward") ); forwardmonth->setPixmap( Resource::loadPixmap("fastforward") ); } /* * Destroys the object and frees any allocated resources */ DateBookWeekHeader::~DateBookWeekHeader() { // no need to delete child widgets, Qt does it all for us } void DateBookWeekHeader::pickDate() { static QPopupMenu *m1 = 0; static DateBookMonth *picker = 0; if ( !m1 ) { m1 = new QPopupMenu( this ); picker = new DateBookMonth( m1, 0, TRUE ); m1->insertItem( picker ); - connect( picker, SIGNAL( dateClicked( int, int, int ) ), this, SLOT( setDate( int, int, int ) ) ); + connect( picker, SIGNAL( dateClicked(int,int,int) ), this, SLOT( setDate(int,int,int) ) ); // connect( m1, SIGNAL( aboutToHide() ), this, SLOT( gotHide() ) ); } picker->setDate( date.year(), date.month(), date.day() ); m1->popup(mapToGlobal(labelDate->pos()+QPoint(0,labelDate->height()))); picker->setFocus(); } void DateBookWeekHeader::nextMonth() { qWarning("nextMonth() " ); setDate(date.addDays(28)); } void DateBookWeekHeader::prevMonth() { qWarning("prevMonth() " ); setDate(date.addDays(-28)); } void DateBookWeekHeader::nextWeek() { qWarning("nextWeek() " ); setDate(date.addDays(7)); } void DateBookWeekHeader::prevWeek() { qWarning("prevWeek() "); setDate(date.addDays(-7)); } void DateBookWeekHeader::setDate( int y, int m, int d ) { setDate(QDate(y,m,d)); } void DateBookWeekHeader::setDate(const QDate &d) { int year,week,dayofweek; date=d; dayofweek=d.dayOfWeek(); if(bStartOnMonday) dayofweek--; else if( dayofweek == 7 ) // we already have the right day -7 would lead to the current week.. dayofweek = 0; date=date.addDays(-dayofweek); calcWeek(date,week,year,bStartOnMonday); QDate start=date; QDate stop=start.addDays(6); labelDate->setText( QString::number(start.day()) + "." + Calendar::nameOfMonth( start.month()) + "-" + QString::number(stop.day()) + "." + Calendar::nameOfMonth( stop.month()) +" ("+ tr("w")+":"+QString::number( week ) +")"); date = d; // bugfix: 0001126 - date has to be the selected date, not monday! emit dateChanged(date); } void DateBookWeekHeader::setStartOfWeek( bool onMonday ) { bStartOnMonday = onMonday; setDate( date ); } diff --git a/core/pim/datebook/datebookweeklst.cpp b/core/pim/datebook/datebookweeklst.cpp index 42a1753..af40143 100644 --- a/core/pim/datebook/datebookweeklst.cpp +++ b/core/pim/datebook/datebookweeklst.cpp @@ -1,394 +1,394 @@ #include "datebookweeklst.h" #include "datebook.h" #include <qpe/datebookmonth.h> #include <qpe/config.h> #include <qpe/resource.h> #include <qlayout.h> #include <qtoolbutton.h> #include <qtl.h> bool calcWeek(const QDate &d, int &week, int &year,bool startOnMonday = false); DateBookWeekLstHeader::DateBookWeekLstHeader(bool onM, QWidget* parent, const char* name, WFlags fl) : DateBookWeekLstHeaderBase(parent, name, fl) { setBackgroundMode( PaletteButton ); labelDate->setBackgroundMode( PaletteButton ); forwardweek->setBackgroundMode( PaletteButton ); forwardweek->setPixmap( Resource::loadPixmap("forward") ); forwardmonth->setBackgroundMode( PaletteButton ); forwardmonth->setPixmap( Resource::loadPixmap("fastforward") ); backweek->setBackgroundMode( PaletteButton ); backweek->setPixmap( Resource::loadPixmap("back") ); backmonth->setBackgroundMode( PaletteButton ); backmonth->setPixmap( Resource::loadPixmap("fastback") ); DateBookWeekLstHeaderBaseLayout->setSpacing(0); DateBookWeekLstHeaderBaseLayout->setMargin(0); //setSizePolicy(QSizePolicy(QSizePolicy::Fixed,QSizePolicy::Expanding)); setSizePolicy(QSizePolicy(QSizePolicy::Expanding,QSizePolicy::Fixed)); connect(backmonth, SIGNAL(clicked()), this, SLOT(prevMonth())); connect(backweek, SIGNAL(clicked()), this, SLOT(prevWeek())); connect(forwardweek, SIGNAL(clicked()), this, SLOT(nextWeek())); connect(forwardmonth, SIGNAL(clicked()), this, SLOT(nextMonth())); connect(labelDate, SIGNAL(clicked()), this, SLOT(pickDate())); connect(dbl, SIGNAL(toggled(bool)), this, SIGNAL(setDbl(bool))); bStartOnMonday=onM; } DateBookWeekLstHeader::~DateBookWeekLstHeader(){} void DateBookWeekLstHeader::setDate(const QDate &d) { int year,week,dayofweek; date=d; dayofweek=d.dayOfWeek(); if(bStartOnMonday) dayofweek--; else if( dayofweek == 7 ) /* we already have the right day -7 would lead to the same week */ dayofweek = 0; date=date.addDays(-dayofweek); calcWeek(date,week,year,bStartOnMonday); QDate start=date; QDate stop=start.addDays(6); labelDate->setText( QString::number(start.day()) + "." + Calendar::nameOfMonth( start.month() ) + "-" + QString::number(stop.day()) + "." + Calendar::nameOfMonth( stop.month()) +" ("+ tr("w")+":"+QString::number( week ) +")"); date = d; // bugfix: 0001126 - date has to be the selected date, not monday! emit dateChanged(date); } void DateBookWeekLstHeader::pickDate() { static QPopupMenu *m1 = 0; static DateBookMonth *picker = 0; if ( !m1 ) { m1 = new QPopupMenu( this ); picker = new DateBookMonth( m1, 0, TRUE ); m1->insertItem( picker ); - connect( picker, SIGNAL( dateClicked( int, int, int ) ),this, SLOT( setDate( int, int, int ) ) ); + connect( picker, SIGNAL( dateClicked(int,int,int) ),this, SLOT( setDate(int,int,int) ) ); //connect( m1, SIGNAL( aboutToHide() ), //this, SLOT( gotHide() ) ); } picker->setDate( date.year(), date.month(), date.day() ); m1->popup(mapToGlobal(labelDate->pos()+QPoint(0,labelDate->height()))); picker->setFocus(); } void DateBookWeekLstHeader::setDate(int y, int m, int d) { setDate(QDate(y,m,d)); } void DateBookWeekLstHeader::nextWeek() { setDate(date.addDays(7)); } void DateBookWeekLstHeader::prevWeek() { setDate(date.addDays(-7)); } void DateBookWeekLstHeader::nextMonth() { setDate(date.addDays(28)); } void DateBookWeekLstHeader::prevMonth() { setDate(date.addDays(-28)); } DateBookWeekLstDayHdr::DateBookWeekLstDayHdr(const QDate &d, bool /* onM */, QWidget* parent, const char* name, WFlags fl ) : DateBookWeekLstDayHdrBase(parent, name, fl) { date=d; static const QString wdays=tr("MTWTFSSM", "Week days"); char day=wdays[d.dayOfWeek()-1]; //dont use dayOfWeek() to save space ! label->setText( QString(QObject::tr(QString(QChar(day)))) + " " +QString::number(d.day()) ); add->setText("+"); if (d == QDate::currentDate()) { QPalette pal=label->palette(); pal.setColor(QColorGroup::Foreground, QColor(0,0,255)); label->setPalette(pal); /* QFont f=label->font(); f.setItalic(true); label->setFont(f); label->setPalette(QPalette(QColor(0,0,255),label->backgroundColor())); */ } else if (d.dayOfWeek() == 7) { // FIXME: Match any holiday QPalette pal=label->palette(); pal.setColor(QColorGroup::Foreground, QColor(255,0,0)); label->setPalette(pal); } connect (label, SIGNAL(clicked()), this, SLOT(showDay())); connect (add, SIGNAL(clicked()), this, SLOT(newEvent())); } void DateBookWeekLstDayHdr::showDay() { emit showDate(date.year(), date.month(), date.day()); } void DateBookWeekLstDayHdr::newEvent() { QDateTime start, stop; start=stop=date; start.setTime(QTime(10,0)); stop.setTime(QTime(12,0)); emit addEvent(start,stop,"",0); } DateBookWeekLstEvent::DateBookWeekLstEvent(const EffectiveEvent &ev, int weeklistviewconfig, QWidget* parent, const char* name, WFlags fl ) : OClickableLabel(parent,name,fl), event(ev) { // old values... lastday = "__|__", middle=" |---", Firstday="00:00", QString s,start,middle,end,day; qDebug("weeklistviewconfig=%d",weeklistviewconfig); if(weeklistviewconfig==NONE) { // No times displayed. // start.sprintf("%.2d:%.2d-",ev.start().hour(),ev.start().minute()); // middle.sprintf("<--->"); // end.sprintf("-%.2d:%.2d",ev.end().hour(),ev.end().minute()); // day.sprintf("%.2d:%.2d-%.2d:%.2d",ev.start().hour(),ev.start().minute(),ev.end().hour(),ev.end().minute()); } else if(weeklistviewconfig==NORMAL) { // "Normal", only display start time. start.sprintf("%.2d:%.2d",ev.start().hour(),ev.start().minute()); middle.sprintf(" |---"); end.sprintf("__|__"); day.sprintf("%.2d:%.2d",ev.start().hour(),ev.start().minute()); } else if(weeklistviewconfig==EXTENDED) { // Extended mode, display start and end times. start.sprintf("%.2d:%.2d-",ev.start().hour(),ev.start().minute()); middle.sprintf("<--->"); end.sprintf("-%.2d:%.2d",ev.end().hour(),ev.end().minute()); day.sprintf("%.2d:%.2d-%.2d:%.2d",ev.start().hour(),ev.start().minute(),ev.end().hour(),ev.end().minute()); } if(ev.event().type() == Event::Normal) { if(ev.startDate()==ev.date() && ev.endDate()==ev.date()) { // day event. s=day; } else if(ev.startDate()==ev.date()) { // start event. s=start; } else if(ev.endDate()==ev.date()) { // end event. s=end; } else { // middle day. s=middle; } } else { s=""; } setText(QString(s) + " " + ev.description()); connect(this, SIGNAL(clicked()), this, SLOT(editMe())); setAlignment( int( QLabel::WordBreak | QLabel::AlignLeft ) ); } void DateBookWeekLstEvent::editMe() { emit editEvent(event.event()); } DateBookWeekLstView::DateBookWeekLstView(QValueList<EffectiveEvent> &ev, const QDate &d, bool onM, QWidget* parent, const char* name, WFlags fl) : QWidget( parent, name, fl ) { Config config("DateBook"); config.setGroup("Main"); int weeklistviewconfig=config.readNumEntry("weeklistviewconfig", NORMAL); qDebug("Read weeklistviewconfig: %d",weeklistviewconfig); bStartOnMonday=onM; setPalette(white); setSizePolicy(QSizePolicy(QSizePolicy::Expanding,QSizePolicy::Expanding)); QVBoxLayout *layout = new QVBoxLayout( this ); qBubbleSort(ev); QValueListIterator<EffectiveEvent> it; it=ev.begin(); int dayOrder[7]; if (bStartOnMonday) { for (int d=0; d<7; d++) dayOrder[d]=d+1; } else { for (int d=0; d<7; d++) dayOrder[d]=d; dayOrder[0]=7; } // Calculate offset to first day of week. int dayoffset=d.dayOfWeek(); if(bStartOnMonday) dayoffset--; else if( dayoffset == 7 ) dayoffset = 0; for (int i=0; i<7; i++) { // Header DateBookWeekLstDayHdr *hdr=new DateBookWeekLstDayHdr(d.addDays(i-dayoffset), bStartOnMonday,this); connect(hdr, SIGNAL(showDate(int,int,int)), this, SIGNAL(showDate(int,int,int))); - connect(hdr, SIGNAL(addEvent(const QDateTime &, const QDateTime &, const QString &, const QString &)), - this, SIGNAL(addEvent(const QDateTime &, const QDateTime &, const QString &, const QString &))); + connect(hdr, SIGNAL(addEvent(const QDateTime&,const QDateTime&,const QString&,const QString&)), + this, SIGNAL(addEvent(const QDateTime&,const QDateTime&,const QString&,const QString&))); layout->addWidget(hdr); // Events while ( (*it).date().dayOfWeek() == dayOrder[i] && it!=ev.end() ) { if(!(((*it).end().hour()==0) && ((*it).end().minute()==0) && ((*it).startDate()!=(*it).date()))) { // Skip events ending at 00:00 starting at another day. DateBookWeekLstEvent *l=new DateBookWeekLstEvent(*it,weeklistviewconfig,this); layout->addWidget(l); - connect (l, SIGNAL(editEvent(const Event &)), this, SIGNAL(editEvent(const Event &))); + connect (l, SIGNAL(editEvent(const Event&)), this, SIGNAL(editEvent(const Event&))); } it++; } layout->addItem(new QSpacerItem(1,1, QSizePolicy::Minimum, QSizePolicy::Expanding)); } } DateBookWeekLstView::~DateBookWeekLstView(){} void DateBookWeekLstView::keyPressEvent(QKeyEvent *e) {e->ignore();} DateBookWeekLstDblView::DateBookWeekLstDblView(QValueList<EffectiveEvent> &ev1, QValueList<EffectiveEvent> &ev2, QDate &d, bool onM, QWidget* parent, const char* name, WFlags fl) : QWidget( parent, name, fl ) { QHBoxLayout *layout = new QHBoxLayout( this ); DateBookWeekLstView *w=new DateBookWeekLstView(ev1,d,onM,this); layout->addWidget(w); - connect (w, SIGNAL(editEvent(const Event &)), this, SIGNAL(editEvent(const Event &))); + connect (w, SIGNAL(editEvent(const Event&)), this, SIGNAL(editEvent(const Event&))); connect (w, SIGNAL(showDate(int,int,int)), this, SIGNAL(showDate(int,int,int))); - connect (w, SIGNAL(addEvent(const QDateTime &, const QDateTime &, const QString &,const QString &)), - this, SIGNAL(addEvent(const QDateTime &, const QDateTime &, const QString &, const QString &))); + connect (w, SIGNAL(addEvent(const QDateTime&,const QDateTime&,const QString&,const QString&)), + this, SIGNAL(addEvent(const QDateTime&,const QDateTime&,const QString&,const QString&))); w=new DateBookWeekLstView(ev2,d.addDays(7),onM,this); layout->addWidget(w); - connect (w, SIGNAL(editEvent(const Event &)), this, SIGNAL(editEvent(const Event &))); + connect (w, SIGNAL(editEvent(const Event&)), this, SIGNAL(editEvent(const Event&))); connect (w, SIGNAL(showDate(int,int,int)), this, SIGNAL(showDate(int,int,int))); - connect (w, SIGNAL(addEvent(const QDateTime &, const QDateTime &, const QString &, const QString &)), - this, SIGNAL(addEvent(const QDateTime &, const QDateTime &, const QString &, const QString &))); + connect (w, SIGNAL(addEvent(const QDateTime&,const QDateTime&,const QString&,const QString&)), + this, SIGNAL(addEvent(const QDateTime&,const QDateTime&,const QString&,const QString&))); } DateBookWeekLst::DateBookWeekLst( bool ap, bool onM, DateBookDB *newDB, QWidget *parent, const char *name ) : QWidget( parent, name ), db( newDB ), startTime( 0 ), ampm( ap ), bStartOnMonday(onM) { setFocusPolicy(StrongFocus); layout = new QVBoxLayout( this ); layout->setMargin(0); header=new DateBookWeekLstHeader(onM, this); layout->addWidget( header ); - connect(header, SIGNAL(dateChanged(QDate &)), this, SLOT(dateChanged(QDate &))); + connect(header, SIGNAL(dateChanged(QDate&)), this, SLOT(dateChanged(QDate&))); connect(header, SIGNAL(setDbl(bool)), this, SLOT(setDbl(bool))); scroll=new QScrollView(this); scroll->setResizePolicy(QScrollView::AutoOneFit); layout->addWidget(scroll); view=NULL; Config config("DateBook"); config.setGroup("Main"); dbl=config.readBoolEntry("weeklst_dbl", false); header->dbl->setOn(dbl); } DateBookWeekLst::~DateBookWeekLst(){ Config config("DateBook"); config.setGroup("Main"); config.writeEntry("weeklst_dbl", dbl); } void DateBookWeekLst::setDate(const QDate &d) { bdate=d; header->setDate(d); } void DateBookWeekLst::setDbl(bool on) { dbl=on; redraw(); } void DateBookWeekLst::redraw() {getEvents();} QDate DateBookWeekLst::date() { return bdate; } // return the date at the beginning of the week... // copied from DateBookWeek QDate DateBookWeekLst::weekDate() const { QDate d=bdate; // Calculate offset to first day of week. int dayoffset=d.dayOfWeek(); if(bStartOnMonday) dayoffset--; else if( dayoffset == 7 ) dayoffset = 0; return d.addDays(-dayoffset); } void DateBookWeekLst::getEvents() { QDate start = weekDate(); //date(); QDate stop = start.addDays(6); QValueList<EffectiveEvent> el = db->getEffectiveEvents(start, stop); if (view) delete view; if (dbl) { QDate start2=start.addDays(7); stop=start2.addDays(6); QValueList<EffectiveEvent> el2 = db->getEffectiveEvents(start2, stop); view=new DateBookWeekLstDblView(el,el2,start,bStartOnMonday,scroll); } else { view=new DateBookWeekLstView(el,start,bStartOnMonday,scroll); } - connect (view, SIGNAL(editEvent(const Event &)), this, SIGNAL(editEvent(const Event &))); + connect (view, SIGNAL(editEvent(const Event&)), this, SIGNAL(editEvent(const Event&))); connect (view, SIGNAL(showDate(int,int,int)), this, SIGNAL(showDate(int,int,int))); - connect (view, SIGNAL(addEvent(const QDateTime &, const QDateTime &, const QString &, const QString &)), - this, SIGNAL(addEvent(const QDateTime &, const QDateTime &, const QString &, const QString &))); + connect (view, SIGNAL(addEvent(const QDateTime&,const QDateTime&,const QString&,const QString&)), + this, SIGNAL(addEvent(const QDateTime&,const QDateTime&,const QString&,const QString&))); scroll->addChild(view); view->show(); scroll->updateScrollBars(); } void DateBookWeekLst::dateChanged(QDate &newdate) { bdate=newdate; getEvents(); } void DateBookWeekLst::keyPressEvent(QKeyEvent *e) { switch(e->key()) { case Key_Up: scroll->scrollBy(0, -20); break; case Key_Down: scroll->scrollBy(0, 20); break; case Key_Left: header->prevWeek(); break; case Key_Right: header->nextWeek(); break; default: e->ignore(); } } diff --git a/core/pim/datebook/dateentryimpl.cpp b/core/pim/datebook/dateentryimpl.cpp index 018bb5a..57bcd89 100644 --- a/core/pim/datebook/dateentryimpl.cpp +++ b/core/pim/datebook/dateentryimpl.cpp @@ -1,407 +1,407 @@ /********************************************************************** ** Copyright (C) 2000 Trolltech AS. All rights reserved. ** ** This file is part of Qtopia Environment. ** ** This file may be distributed and/or modified under the terms of the ** GNU General Public License version 2 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. ** ** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE ** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. ** ** See http://www.trolltech.com/gpl/ for GPL licensing information. ** ** Contact info@trolltech.com if any conditions of this licensing are ** not clear to you. ** **********************************************************************/ #include "dateentryimpl.h" #include "repeatentry.h" #include <qpe/qpeapplication.h> #include <qpe/categoryselect.h> #include <qpe/datebookmonth.h> #include <qpe/tzselect.h> #include <qlineedit.h> #include <qspinbox.h> #include <opie/otimepicker.h> #include "onoteedit.h" #include <stdlib.h> #include <stdio.h> /* * Constructs a DateEntry which is a child of 'parent', with the * name 'name' and widget flags set to 'f' * * The dialog will by default be modeless, unless you set 'modal' to * TRUE to construct a modal dialog. */ DateEntry::DateEntry( bool startOnMonday, const QDateTime &start, const QDateTime &end, bool whichClock, QWidget* parent, const char* name ) : DateEntryBase( parent, name ), ampm( whichClock ), startWeekOnMonday( startOnMonday ), m_showStart(true) { init(); setDates(start,end); setFocusProxy(comboDescription); } bool DateEntry::eventFilter(QObject *obj, QEvent *ev ) { if( ev->type() == QEvent::FocusIn ){ if( obj == comboStart ){ timePickerStart->setHour(startTime.hour()); timePickerStart->setMinute(startTime.minute()); TimePickerLabel->setText( tr("Start Time" ) ); m_showStart= true; }else if( obj == comboEnd ){ timePickerStart->setHour(endTime.hour()); timePickerStart->setMinute(endTime.minute()); TimePickerLabel->setText( tr("End Time") ); m_showStart = false; } } else if( ev->type() == QEvent::FocusOut ){ // if( obj == comboEnd ){ // QString s; // s.sprintf("%.2d:%.2d",endTime.hour(), endTime.minute()); // comboEnd->setText(s); // } // else if( obj == comboStart ){ // QString s; // s.sprintf("%.2d:%.2d",startTime.hour(), startTime.minute()); // comboStart->setText(s); // } } return false; } static void addOrPick( QComboBox* combo, const QString& t ) { // Pick an item if one excists for (int i=0; i<combo->count(); i++) { if ( combo->text(i) == t ) { combo->setCurrentItem(i); return; } } // Else add one combo->insertItem(t); combo->setCurrentItem(combo->count()-1); } DateEntry::DateEntry( bool startOnMonday, const Event &event, bool whichClock, QWidget* parent, const char* name ) : DateEntryBase( parent, name ), ampm( whichClock ), startWeekOnMonday( startOnMonday ), m_showStart(true) { init(); setDates(event.start(),event.end()); comboCategory->setCategories( event.categories(), "Calendar", tr("Calendar") ); if(!event.description().isEmpty()) addOrPick( comboDescription, event.description() ); if(!event.location().isEmpty()) addOrPick( comboLocation, event.location() ); checkAlarm->setChecked( event.hasAlarm() ); checkAllDay->setChecked( event.type() == Event::AllDay ); if(!event.notes().isEmpty()) noteStr=event.notes(); else noteStr=""; spinAlarm->setValue(event.alarmTime()); if ( event.alarmSound() != Event::Silent ) comboSound->setCurrentItem( 1 ); if ( event.hasRepeat() ) { rp = event.repeatPattern(); cmdRepeat->setText( tr("Repeat...") ); } setRepeatLabel(); } void DateEntry::setDates( const QDateTime& s, const QDateTime& e ) { startDate = s.date(); endDate = e.date(); startTime = s.time(); endTime = e.time(); startDateChanged( s.date().year(), s.date().month(), s.date().day() ); endDateChanged( e.date().year(), e.date().month(), e.date().day() ); updateTimeEdit(true,true); } void DateEntry::updateTimeEdit(bool s, bool e) { // Comboboxes QString strStart, strEnd; int shour, ehour; if ( ampm ) { shour = startTime.hour(); ehour = endTime.hour(); if ( shour >= 12 ) { if ( shour > 12 ) shour -= 12; strStart.sprintf( "%d:%02d PM", shour, startTime.minute() ); } else { if ( shour == 0 ) shour = 12; strStart.sprintf( "%d:%02d AM", shour, startTime.minute() ); } if ( ehour == 24 && endTime.minute() == 0 ) { strEnd = "11:59 PM"; // or "midnight" } else if ( ehour >= 12 ) { if ( ehour > 12 ) ehour -= 12; strEnd.sprintf( "%d:%02d PM", ehour, endTime.minute() ); } else { if ( ehour == 0 ) ehour = 12; strEnd.sprintf( "%d:%02d AM", ehour, endTime.minute() ); } } else { strStart.sprintf( "%02d:%02d", startTime.hour(), startTime.minute() ); strEnd.sprintf( "%02d:%02d", endTime.hour(), endTime.minute() ); } if (s) comboStart->setText(strStart); if (e) comboEnd->setText(strEnd); } void DateEntry::init() { comboDescription->setInsertionPolicy(QComboBox::AtCurrent); comboLocation->setInsertionPolicy(QComboBox::AtCurrent); initCombos(); QPopupMenu *m1 = new QPopupMenu( this ); startPicker = new DateBookMonth( m1, 0, TRUE ); m1->insertItem( startPicker ); buttonStart->setPopup( m1 ); - connect( startPicker, SIGNAL( dateClicked( int, int, int ) ), - this, SLOT( startDateChanged( int, int, int ) ) ); + connect( startPicker, SIGNAL( dateClicked(int,int,int) ), + this, SLOT( startDateChanged(int,int,int) ) ); //Let start button change both start and end dates - connect( startPicker, SIGNAL( dateClicked( int, int, int ) ), - this, SLOT( endDateChanged( int, int, int ) ) ); - connect( qApp, SIGNAL( clockChanged( bool ) ), - this, SLOT( slotChangeClock( bool ) ) ); + connect( startPicker, SIGNAL( dateClicked(int,int,int) ), + this, SLOT( endDateChanged(int,int,int) ) ); + connect( qApp, SIGNAL( clockChanged(bool) ), + this, SLOT( slotChangeClock(bool) ) ); connect( qApp, SIGNAL(weekChanged(bool)), this, SLOT(slotChangeStartOfWeek(bool)) ); connect( editNote, SIGNAL(clicked()), this, SLOT(slotEditNote()) ); QPopupMenu *m2 = new QPopupMenu( this ); endPicker = new DateBookMonth( m2, 0, TRUE ); m2->insertItem( endPicker ); buttonEnd->setPopup( m2 ); - connect( endPicker, SIGNAL( dateClicked( int, int, int ) ), - this, SLOT( endDateChanged( int, int, int ) ) ); + connect( endPicker, SIGNAL( dateClicked(int,int,int) ), + this, SLOT( endDateChanged(int,int,int) ) ); - connect(timePickerStart, SIGNAL( timeChanged(const QTime &) ), - this, SLOT( startTimePicked(const QTime &) )); + connect(timePickerStart, SIGNAL( timeChanged(const QTime&) ), + this, SLOT( startTimePicked(const QTime&) )); // install eventFilters comboEnd->installEventFilter( this ); comboStart->installEventFilter( this ); } /* * Destroys the object and frees any allocated resources */ DateEntry::~DateEntry() { // no need to delete child widgets, Qt does it all for us //cout << "Del: " << comboStart->currentText() << endl; } /* * public slot */ void DateEntry::slotEditNote() { QString s; s = "<B>"+ TimeString::longDateString( startDate ) + "</B>"; // s.sprintf("<B>%d/%d</B> ", startDate.day(), startDate.month()); NoteEntry noteDlg(s+comboDescription->currentText(), noteStr, this,0,TRUE); if ( QPEApplication::execDialog( ¬eDlg ) ) { noteStr=noteDlg.note->text(); } } void DateEntry::endDateChanged( int y, int m, int d ) { endDate.setYMD( y, m, d ); if ( endDate < startDate ) { endDate = startDate; } buttonEnd->setText( TimeString::shortDate( endDate ) ); endPicker->setDate( endDate.year(), endDate.month(), endDate.day() ); } static QTime parseTime( const QString& s, bool ampm ) { QTime tmpTime; QStringList l = QStringList::split( ':', s ); int hour = l[0].toInt(); if ( ampm ) { int i=0; while (i<int(l[1].length()) && l[1][i]>='0' && l[1][i]<='9') i++; QString digits = l[1].left(i); if ( l[1].contains( "PM", FALSE ) ) { if ( hour != 12 ) hour += 12; } else { if ( hour == 12 ) hour = 0; } l[1] = digits; } int minute = l[1].toInt(); if ( minute > 59 ) minute = 59; else if ( minute < 0 ) minute = 0; if ( hour > 23 ) { hour = 23; minute = 59; } else if ( hour < 0 ) hour = 0; tmpTime.setHMS( hour, minute, 0 ); return tmpTime; } /* * public slot */ void DateEntry::endTimeChanged( const QString &s ) { endTimeChanged( parseTime(s,ampm) ); } void DateEntry::endTimeChanged( const QTime &t ) { if ( endDate > startDate || t >= startTime ) { endTime = t; } else { endTime = startTime; //comboEnd->setCurrentItem( comboStart->currentItem() ); } timePickerStart->setHour(endTime.hour()); timePickerStart->setMinute(endTime.minute()); } /* * public slot */ void DateEntry::startDateChanged( int y, int m, int d ) { QDate prev = startDate; startDate.setYMD( y, m, d ); if ( rp.type == Event::Weekly && startDate.dayOfWeek() != prev.dayOfWeek() ) { // if we change the start of a weekly repeating event // set the repeating day appropriately char mask = 1 << (prev.dayOfWeek()-1); rp.days &= (~mask); rp.days |= 1 << (startDate.dayOfWeek()-1); } buttonStart->setText( TimeString::shortDate( startDate ) ); // our pickers must be reset... startPicker->setDate( y, m, d ); endPicker->setDate( y, m, d ); } /* * public slot */ void DateEntry::startTimeEdited( const QString &s ) { startTimeChanged(parseTime(s,ampm)); updateTimeEdit(false,true); timePickerStart->setHour(startTime.hour()); timePickerStart->setMinute(startTime.minute()); } void DateEntry::startTimeChanged( const QTime &t ) { int duration=startTime.secsTo(endTime); startTime = t; endTime=t.addSecs(duration); } void DateEntry::startTimePicked( const QTime &t ) { if(m_showStart ){ startTimeChanged(t); updateTimeEdit(true,true); }else{ endTimeChanged(t); updateTimeEdit(false, true ); } } /* * public slot */ void DateEntry::typeChanged( const QString &s ) { bool b = s != "All Day"; buttonStart->setEnabled( b ); comboStart->setEnabled( b ); comboEnd->setEnabled( b ); } void DateEntry::slotRepeat() { // Work around for compiler Bug.. RepeatEntry *e; // it is better in my opinion to just grab this from the mother, // since, this dialog doesn't need to keep track of it... if ( rp.type != Event::NoRepeat ) e = new RepeatEntry( startWeekOnMonday, rp, startDate, this); else e = new RepeatEntry( startWeekOnMonday, startDate, this ); if ( QPEApplication::execDialog( e ) ) { rp = e->repeatPattern(); setRepeatLabel(); } // deleting sounds like a nice idea... delete e; } void DateEntry::slotChangeStartOfWeek( bool onMonday ) { startWeekOnMonday = onMonday; } Event DateEntry::event() { Event ev; Event::SoundTypeChoice st; ev.setDescription( comboDescription->currentText() ); ev.setLocation( comboLocation->currentText() ); ev.setCategories( comboCategory->currentCategories() ); ev.setType( checkAllDay->isChecked() ? Event::AllDay : Event::Normal ); if ( startDate > endDate ) { QDate tmp = endDate; endDate = startDate; diff --git a/core/pim/datebook/repeatentry.cpp b/core/pim/datebook/repeatentry.cpp index 7cf36da..04c3cf3 100644 --- a/core/pim/datebook/repeatentry.cpp +++ b/core/pim/datebook/repeatentry.cpp @@ -170,386 +170,386 @@ Event::RepeatPattern RepeatEntry::repeatPattern() break; case WEEK: rpTmp.type = Event::Weekly; rpTmp.days = 0; int day; for ( day = 1; *itExtra; ++itExtra, day = day << 1 ) { if ( (*itExtra)->isOn() ) { if ( startWeekOnMonday ) rpTmp.days |= day; else { if ( day == 1 ) rpTmp.days |= Event::SUN; else rpTmp.days |= day >> 1; } } } break; case MONTH: if ( cmdExtra1->isOn() ) rpTmp.type = Event::MonthlyDay; else if ( cmdExtra2->isOn() ) rpTmp.type = Event::MonthlyDate; // figure out the montly day... rpTmp.position = week( start ); break; case YEAR: rpTmp.type = Event::Yearly; break; } break; // no need to keep looking! } } rpTmp.frequency = spinFreq->value(); rpTmp.hasEndDate = !chkNoEnd->isChecked(); if ( rpTmp.hasEndDate ) { rpTmp.setEndDate( end ); } // timestamp it... rpTmp.createTime = time( NULL ); return rpTmp; } void RepeatEntry::slotSetRType( int rtype ) { // now call the right function based on the type... currInterval = static_cast<repeatButtons>(rtype); switch ( currInterval ) { case NONE: setupNone(); break; case DAY: setupDaily(); break; case WEEK: setupWeekly(); slotWeekLabel(); break; case MONTH: setupMonthly(); cmdExtra2->setOn( TRUE ); slotMonthLabel( 1 ); break; case YEAR: setupYearly(); break; } } void RepeatEntry::setupNone() { lblRepeat->setText( tr("No Repeat") ); lblVar1->hide(); lblVar2->hide(); hideExtras(); cmdEnd->hide(); lblFreq->hide(); lblEvery->hide(); lblFreq->hide(); spinFreq->hide(); lblEnd->hide(); lblWeekVar->hide(); } void RepeatEntry::setupDaily() { hideExtras(); lblWeekVar->hide(); spinFreq->setValue( 1 ); lblFreq->setText( tr("day(s)") ); lblVar2->show(); showRepeatStuff(); lblRepeat->setText( strDayTemplate ); setupRepeatLabel( 1 ); } void RepeatEntry::setupWeekly() { // reshow the buttons... fraExtra->setTitle( RepeatEntryBase::tr("Repeat On") ); fraExtra->setExclusive( FALSE ); fraExtra->show(); if ( startWeekOnMonday ) { cmdExtra1->setText( RepeatEntryBase::tr("Mon") ); cmdExtra2->setText( RepeatEntryBase::tr("Tue") ); cmdExtra3->setText( RepeatEntryBase::tr("Wed") ); cmdExtra4->setText( RepeatEntryBase::tr("Thu") ); cmdExtra5->setText( RepeatEntryBase::tr("Fri") ); cmdExtra6->setText( RepeatEntryBase::tr("Sat") ); cmdExtra7->setText( RepeatEntryBase::tr("Sun") ); } else { cmdExtra1->setText( RepeatEntryBase::tr("Sun") ); cmdExtra2->setText( RepeatEntryBase::tr("Mon") ); cmdExtra3->setText( RepeatEntryBase::tr("Tue") ); cmdExtra4->setText( RepeatEntryBase::tr("Wed") ); cmdExtra5->setText( RepeatEntryBase::tr("Thu") ); cmdExtra6->setText( RepeatEntryBase::tr("Fri") ); cmdExtra7->setText( RepeatEntryBase::tr("Sat") ); } // I hope clustering these improve performance.... cmdExtra1->setOn( FALSE ); cmdExtra2->setOn( FALSE ); cmdExtra3->setOn( FALSE ); cmdExtra4->setOn( FALSE ); cmdExtra5->setOn( FALSE ); cmdExtra6->setOn( FALSE ); cmdExtra7->setOn( FALSE ); cmdExtra1->show(); cmdExtra2->show(); cmdExtra3->show(); cmdExtra4->show(); cmdExtra5->show(); cmdExtra6->show(); cmdExtra7->show(); lblWeekVar->show(); spinFreq->setValue( 1 ); // might as well set the day too... if ( startWeekOnMonday ) { fraExtra->setButton( start.dayOfWeek() - 1 ); } else { fraExtra->setButton( start.dayOfWeek() % 7 ); } lblFreq->setText( tr("week(s)") ); lblVar2->show(); showRepeatStuff(); setupRepeatLabel( 1 ); } void RepeatEntry::setupMonthly() { hideExtras(); lblWeekVar->hide(); fraExtra->setTitle( tr("Repeat By") ); fraExtra->setExclusive( TRUE ); fraExtra->show(); cmdExtra1->setText( tr("Day") ); cmdExtra1->show(); cmdExtra2->setText( tr("Date") ); cmdExtra2->show(); spinFreq->setValue( 1 ); lblFreq->setText( tr("month(s)") ); lblVar2->show(); showRepeatStuff(); setupRepeatLabel( 1 ); } void RepeatEntry::setupYearly() { hideExtras(); lblWeekVar->hide(); spinFreq->setValue( 1 ); lblFreq->setText( tr("year(s)") ); lblFreq->show(); lblFreq->show(); showRepeatStuff(); lblVar2->show(); QString strEvery = strYearTemplate.arg( start.monthName(start.month()) ).arg( numberPlacing(start.day()) ); lblRepeat->setText( strEvery ); setupRepeatLabel( 1 ); } void RepeatEntry::init() { QPopupMenu *m1 = new QPopupMenu( this ); repeatPicker = new DateBookMonth( m1, 0, TRUE ); m1->insertItem( repeatPicker ); cmdEnd->setPopup( m1 ); cmdEnd->setPopupDelay( 0 ); - QObject::connect( repeatPicker, SIGNAL(dateClicked(int, int, int)), - this, SLOT(endDateChanged(int, int, int)) ); + QObject::connect( repeatPicker, SIGNAL(dateClicked(int,int,int)), + this, SLOT(endDateChanged(int,int,int)) ); QObject::connect( qApp, SIGNAL(weekChanged(bool)), this, SLOT(slotChangeStartOfWeek(bool)) ); listRTypeButtons.setAutoDelete( TRUE ); listRTypeButtons.append( cmdNone ); listRTypeButtons.append( cmdDay ); listRTypeButtons.append( cmdWeek ); listRTypeButtons.append( cmdMonth ); listRTypeButtons.append( cmdYear ); listExtra.setAutoDelete( TRUE ); listExtra.append( cmdExtra1 ); listExtra.append( cmdExtra2 ); listExtra.append( cmdExtra3 ); listExtra.append( cmdExtra4 ); listExtra.append( cmdExtra5 ); listExtra.append( cmdExtra6 ); listExtra.append( cmdExtra7 ); } void RepeatEntry::slotNoEnd( bool unused ) { // if the item was toggled, then go ahead and set it to the maximum date if ( unused ) { end.setYMD( 3000, 12, 31 ); cmdEnd->setText( RepeatEntryBase::tr("No End Date") ); } else { end = start; cmdEnd->setText( TimeString::shortDate(end) ); } } void RepeatEntry::endDateChanged( int y, int m, int d ) { end.setYMD( y, m, d ); if ( end < start ) end = start; cmdEnd->setText( TimeString::shortDate( end ) ); repeatPicker->setDate( end.year(), end.month(), end.day() ); } void RepeatEntry::setupRepeatLabel( const QString &s ) { lblVar1->setText( s ); } void RepeatEntry::setupRepeatLabel( int x ) { // change the spelling based on the value of x QString strVar2; if ( x > 1 ) lblVar1->show(); else lblVar1->hide(); switch ( currInterval ) { case NONE: break; case DAY: if ( x > 1 ) strVar2 = tr( "days" ); else strVar2 = tr( "day" ); break; case WEEK: if ( x > 1 ) strVar2 = tr( "weeks" ); else strVar2 = tr( "week" ); break; case MONTH: if ( x > 1 ) strVar2 = RepeatEntryBase::tr( "months" ); else strVar2 = tr( "month" ); break; case YEAR: if ( x > 1 ) strVar2 = RepeatEntryBase::tr( "years" ); else strVar2 = tr( "year" ); break; } if ( !strVar2.isNull() ) lblVar2->setText( strVar2 ); } void RepeatEntry::showRepeatStuff() { cmdEnd->show(); chkNoEnd->show(); lblFreq->show(); lblEvery->show(); lblFreq->show(); spinFreq->show(); lblEnd->show(); lblRepeat->setText( RepeatEntryBase::tr("Every") ); } void RepeatEntry::slotWeekLabel() { QString str; QListIterator<QToolButton> it( listExtra ); unsigned int i; unsigned int keepMe; bool bNeedCarriage = FALSE; // don't do something we'll regret!!! if ( currInterval != WEEK ) return; if ( startWeekOnMonday ) keepMe = start.dayOfWeek() - 1; else keepMe = start.dayOfWeek() % 7; QStringList list; for ( i = 0; *it; ++it, i++ ) { // a crazy check, if you are repeating weekly, the current day // must be selected!!! if ( i == keepMe && !( (*it)->isOn() ) ) (*it)->setOn( TRUE ); if ( (*it)->isOn() ) { if ( startWeekOnMonday ) list.append( dayLabel[i] ); else { if ( i == 0 ) list.append( dayLabel[6] ); else list.append( dayLabel[i - 1] ); } } } QStringList::Iterator itStr; for ( i = 0, itStr = list.begin(); itStr != list.end(); ++itStr, i++ ) { if ( i == 3 ) bNeedCarriage = TRUE; else bNeedCarriage = FALSE; if ( str.isNull() ) str = *itStr; else if ( i == list.count() - 1 ) { if ( i < 2 ) str += tr(" and ") + *itStr; else { if ( bNeedCarriage ) str += tr( ",\nand " ) + *itStr; else str += tr( ", and " ) + *itStr; } } else { if ( bNeedCarriage ) str += ",\n" + *itStr; else str += ", " + *itStr; } } str = str.prepend( tr("on ") ); lblWeekVar->setText( str ); } void RepeatEntry::slotMonthLabel( int type ) { QString str; if ( currInterval != MONTH || type > 1 ) return; if ( type == 1 ) str = strMonthDateTemplate.arg( numberPlacing(start.day()) ); else str = strMonthDayTemplate.arg( numberPlacing(week(start))) .arg( dayLabel[start.dayOfWeek() - 1] ); lblRepeat->setText( str ); } void RepeatEntry::slotChangeStartOfWeek( bool onMonday ) { startWeekOnMonday = onMonday; // we need to make this unintrusive as possible... int saveSpin = spinFreq->value(); char days = 0; int day; QListIterator<QToolButton> itExtra( listExtra ); for ( day = 1; *itExtra; ++itExtra, day = day << 1 ) { if ( (*itExtra)->isOn() ) { if ( !startWeekOnMonday ) days |= day; else { if ( day == 1 ) days |= Event::SUN; else days |= day >> 1; } diff --git a/core/pim/datebook2/mainwindow.cpp b/core/pim/datebook2/mainwindow.cpp index 7ff2204..3937796 100644 --- a/core/pim/datebook2/mainwindow.cpp +++ b/core/pim/datebook2/mainwindow.cpp @@ -1,302 +1,302 @@ #include <qcopchannel_qws.h> #include <qwidgetstack.h> #include <qlabel.h> #include <qaction.h> #include <qpopupmenu.h> #include <qtimer.h> #include <qpe/qpeapplication.h> #include <qpe/ir.h> #include <qmenubar.h> #include <qtoolbar.h> #include <qpe/qpemessagebox.h> #include <qpe/resource.h> #include "editor.h" #include "show.h" #include "templatemanager.h" #include "bookmanager.h" #include "mainwindow.h" using namespace Datebook; MainWindow::MainWindow() : OPimMainWindow( "Datebook", 0, 0 ), m_descMan( "Descriptions" ), m_locMan( "Locations" ) { setIcon( Resource::loadPixmap( "datebook_icon" ) ); initUI(); initManagers(); initView(); initConfig(); QTimer::singleShot(0, this, SLOT(populate() ) ); QCopChannel* chan = new QCopChannel( "QPE/System", this ); - connect( chan, SIGNAL( received(const QCString&, const QByteArray& ) ), - this, SLOT( slotReceive( const QCString&, const QByteArray& ) ) ); + connect( chan, SIGNAL( received(const QCString&,const QByteArray&) ), + this, SLOT( slotReceive(const QCString&,const QByteArray&) ) ); chan = new QCopChannel( "QPE/Datebook", this ); - connect( chan, SIGNAL( received(const QCString&, const QByteArray& ) ), - this, SLOT( slotReceive( const QCString&, const QByteArray& ) ) ); + connect( chan, SIGNAL( received(const QCString&,const QByteArray&) ), + this, SLOT( slotReceive(const QCString&,const QByteArray&) ) ); } MainWindow::~MainWindow() { m_tempMan.save(); m_locMan.save(); m_descMan.save(); manager()->save(); delete m_manager; } void MainWindow::doSetDocument( const QString& str ) { } void MainWindow::flush() { manager()->save(); } void MainWindow::reload() { manager()->reload(); } int MainWindow::create() { return 0; } bool MainWindow::remove( int uid ) { manager()->remove( uid ); return true; } void MainWindow::beam( int uid ) { } void MainWindow::show( int uid ) { eventShow()->show( manager()->event( uid ) ); } void MainWindow::add( const OPimRecord& ad) { manager()->add( ad ); } void MainWindow::edit() { edit ( currentView()->currentItem() ); } void MainWindow::edit( int uid ) { } /* * init tool bars layout and so on */ void MainWindow::initUI() { setToolBarsMovable( false ); m_stack = new QWidgetStack( this ); setCentralWidget( m_stack ); m_toolBar = new QToolBar( this ); m_toolBar->setHorizontalStretchable( TRUE ); QMenuBar* mb = new QMenuBar( m_toolBar ); m_popView = new QPopupMenu( this ); m_popSetting = new QPopupMenu( this ); mb->insertItem( tr("View"), m_popView ); mb->insertItem( tr("Settings" ), m_popSetting ); m_popTemplate = new QPopupMenu( this ); m_popTemplate->setCheckable( TRUE ); connect( m_popTemplate, SIGNAL(activated(int) ), this, SLOT(slotNewFromTemplate(int) ) ); m_popView->insertItem(tr("New from template"), m_popTemplate, -1, 0); QAction* a = new QAction( tr("New Event"), Resource::loadPixmap("new"), QString::null, 0, this, 0 ); a->addTo( m_toolBar ); a->addTo( m_popView ); connect(a, SIGNAL( activated() ), this, SLOT( create() ) ); a = new QAction( tr("Edit Event"), Resource::loadPixmap("edit"), QString::null, 0, this, 0 ); a->addTo( m_popView ); connect(a, SIGNAL( activated() ), this, SLOT( edit() ) ); a = new QAction( tr("Today" ), Resource::loadPixmap( "datebook/to_day"), QString::null, 0, this, 0 ); a->addTo( m_toolBar ); connect(a, SIGNAL( activated() ), this, SLOT( slotGoToNow() ) ); a = new QAction( tr("Find"), Resource::loadPixmap( "mag" ), QString::null, 0, this, 0 ); a->addTo( m_toolBar ); connect(a, SIGNAL( activated() ), this, SLOT( slotFind() ) ); a = new QAction( tr("Configure"), QString::null, 0, 0 ); a->addTo( m_popSetting ); connect(a, SIGNAL( activated() ), this, SLOT( slotConfigure() ) ); a = new QAction( tr("Configure Locations"), QString::null, 0, 0 ); a->addTo( m_popSetting ); connect(a, SIGNAL( activated() ), this, SLOT( slotConfigureLocs() ) ); a = new QAction( tr("Configure Descriptions"), QString::null, 0, 0 ); a->addTo( m_popSetting ); connect(a, SIGNAL( activated() ), this, SLOT(slotConfigureDesc() ) ); a = new QAction( tr("Configure Templates"), QString::null, 0, 0 ); a->addTo( m_popSetting ); connect(a, SIGNAL( activated() ), this, SLOT(slotConfigureTemp() ) ); connect( qApp, SIGNAL(clockChanged(bool) ), this, SLOT(slotClockChanged(bool) ) ); connect( qApp, SIGNAL(weekChanged(bool) ), this, SLOT(slotWeekChanged(bool) ) ); - connect( qApp, SIGNAL(appMessage(const QCString&, const QByteArray& ) ), - this, SLOT(slotAppMessage( const QCString&, const QByteArray& ) ) ); + connect( qApp, SIGNAL(appMessage(const QCString&,const QByteArray&) ), + this, SLOT(slotAppMessage(const QCString&,const QByteArray&) ) ); } void MainWindow::initConfig() { } void MainWindow::initView() { } void MainWindow::initManagers() { m_manager = new BookManager; m_tempMan.load(); m_locMan.load(); m_descMan.load(); setTemplateMenu(); } void MainWindow::raiseCurrentView() { } /* * populate the view */ void MainWindow::populate() { if (!manager()->isLoaded() ) manager()->load(); } void MainWindow::slotGoToNow() { } View* MainWindow::currentView() { } void MainWindow::slotFind() { } void MainWindow::slotConfigure() { } void MainWindow::slotClockChanged( bool ) { } void MainWindow::slotWeekChanged(bool ) { } void MainWindow::slotAppMessage( const QCString&, const QByteArray& ) { } void MainWindow::slotReceive( const QCString&, const QByteArray& ) { } BookManager* MainWindow::manager() { return m_manager; } TemplateManager MainWindow::templateManager() { return m_tempMan; } LocationManager MainWindow::locationManager() { return m_locMan; } DescriptionManager MainWindow::descriptionManager() { return m_descMan; } void MainWindow::setLocationManager( const LocationManager& loc) { m_locMan = loc; } void MainWindow::setDescriptionManager( const DescriptionManager& dsc ) { m_descMan = dsc; } Show* MainWindow::eventShow() { return m_show; } void MainWindow::slotAction( QAction* act ) { } void MainWindow::slotConfigureLocs() { LocationManagerDialog dlg( locationManager() ); dlg.setCaption( tr("Configure Locations") ); if ( QPEApplication::execDialog( &dlg ) == QDialog::Accepted ) { setLocationManager( dlg.manager() ); } } void MainWindow::slotConfigureDesc() { DescriptionManagerDialog dlg( descriptionManager() ); dlg.setCaption( tr("Configure Descriptions") ); if ( QPEApplication::execDialog( &dlg ) == QDialog::Accepted ) { setDescriptionManager( dlg.manager() ); } } void MainWindow::slotConfigureTemp() { TemplateDialog dlg( templateManager(), editor() ); dlg.setCaption( tr("Configure Templates") ); if ( QPEApplication::execDialog( &dlg ) == QDialog::Accepted ) { m_tempMan = dlg.manager(); setTemplateMenu(); } } void MainWindow::hideShow() { } void MainWindow::viewPopup(int ) { } void MainWindow::viewAdd(const QDate& ) { } void MainWindow::viewAdd( const QDateTime&, const QDateTime& ) { } bool MainWindow::viewAP()const{ } bool MainWindow::viewStartMonday()const { } void MainWindow::setTemplateMenu() { m_popTemplate->clear(); QStringList list = templateManager().names(); for ( QStringList::Iterator it = list.begin(); it != list.end(); ++it ) { m_popTemplate->insertItem( (*it) ); } } /* * get the name of the item with the id id * then ask for an OEvent from the manager */ void MainWindow::slotNewFromTemplate(int id ) { QString name = m_popTemplate->text( id ); OEvent ev = templateManager().value( name ); if ( editor()->edit( ev ) ) { ev = editor()->event(); ev.setUid( -1 ); manager()->add( ev ); /* * no we'll find out if the current view * should show the new event * and then we will ask it to refresh * FIXME for now we'll call a refresh */ currentView()->reschedule(); raiseCurrentView(); } } Editor* MainWindow::editor() { return m_edit; } diff --git a/core/pim/osearch/mainwindow.cpp b/core/pim/osearch/mainwindow.cpp index bfe95b0..8b6a5df 100644 --- a/core/pim/osearch/mainwindow.cpp +++ b/core/pim/osearch/mainwindow.cpp @@ -12,306 +12,306 @@ #include "olistview.h" #include "olistviewitem.h" #include "resultitem.h" #include "adresssearch.h" #include "todosearch.h" #include "datebooksearch.h" #include "applnksearch.h" #include "doclnksearch.h" #include "mainwindow.h" #include <opie2/owait.h> #include <qpe/qpemessagebox.h> #include <qpe/resource.h> #include <qpe/config.h> #include <qpe/qpeapplication.h> #include <qpe/global.h> #include <qtoolbar.h> #include <qaction.h> #include <qmessagebox.h> #include <qpopupmenu.h> #include <qtoolbutton.h> #include <qstring.h> #include <qlabel.h> #include <qfile.h> #include <qhbuttongroup.h> #include <qhbox.h> #include <qpushbutton.h> #include <qintdict.h> #include <qlayout.h> #include <qlineedit.h> #include <qsignalmapper.h> #include <qtextbrowser.h> #include <qregexp.h> #include <qwhatsthis.h> #include <qmenubar.h> static const char* const image1_data[] = { "14 14 3 1", ". c None", "# c #000000", "a c #ff0000", "..............", "..##.......###", ".#aa#....##aa#", "#aaaa#.##aaaa#", ".##aaa#aaaaa##", "...#aaaaaaa#..", "....#aaaaa#...", "...#aaaaa#....", "..#aaaaaaa#...", ".#aaaaaaaaa#..", "#aaaa###aaaa#.", "#aaa#..##aaa#.", "#aaa#...#aa#..", ".###.....##..."}; MainWindow::MainWindow( QWidget *parent, const char *name, WFlags f ) : QMainWindow( parent, name, f ), _currentItem(0) { setCaption( tr("OSearch") ); setSizePolicy( QSizePolicy( QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding)); QFrame *mainFrame = new QFrame( this, "mainFrame" ); mainFrame->setSizePolicy( QSizePolicy( QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding)); mainLayout = new QVBoxLayout( mainFrame ); mainLayout->setSpacing( 0 ); mainLayout->setMargin( 3 ); resultsList = new OListView( mainFrame ); resultsList->setSizePolicy( QSizePolicy( QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding)); mainLayout->addWidget( resultsList ); detailsFrame = new QFrame( mainFrame, "detailsFrame" ); QVBoxLayout *detailsLayout = new QVBoxLayout( detailsFrame ); richEdit = new QTextView( detailsFrame ); QWhatsThis::add( richEdit, tr("The details of the current result") ); richEdit->setSizePolicy( QSizePolicy( QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding)); detailsLayout->addWidget( richEdit ); buttonBox = new QHBox( mainFrame, "Button Box" ); _buttonCount = 0; mainLayout->addWidget( detailsFrame ); mainLayout->addWidget( buttonBox ); detailsFrame->hide(); buttonBox->hide(); searches.append( new AppLnkSearch( resultsList, tr("Applications") ) ); searches.append( new DocLnkSearch( resultsList, tr("Documents") ) ); searches.append( new TodoSearch( resultsList, tr("Todo List") ) ); searches.append( new DatebookSearch( resultsList, tr("Calendar") ) ); searches.append( new AdressSearch( resultsList, tr("Contacts") ) ); setCentralWidget( mainFrame ); popupTimer = new QTimer(); searchTimer = new QTimer(); connect(popupTimer, SIGNAL(timeout()), SLOT(showPopup())); connect(searchTimer, SIGNAL(timeout()), SLOT(searchStringChanged())); connect(resultsList, SIGNAL(pressed(QListViewItem*)), SLOT(setCurrent(QListViewItem*))); connect(resultsList, SIGNAL(clicked(QListViewItem*)), SLOT(stopTimer(QListViewItem*))); signalMapper = new QSignalMapper( this ); connect(signalMapper, SIGNAL(mapped(int)), SLOT( slotAction(int) ) ); makeMenu(); Config cfg( "osearch", Config::User ); cfg.setGroup( "search_settings" ); actionCaseSensitiv->setOn( cfg.readBoolEntry( "caseSensitiv", false ) ); actionWildcards->setOn( cfg.readBoolEntry( "wildcards", false ) ); // actionWholeWordsOnly->setOn( cfg.readBoolEntry( "whole_words_only", false ) ); } void MainWindow::makeMenu() { QToolBar *toolBar = new QToolBar( this ); QToolBar *searchBar = new QToolBar(this); QMenuBar *menuBar = new QMenuBar( toolBar ); QPopupMenu *searchMenu = new QPopupMenu( menuBar ); // QPopupMenu *viewMenu = new QPopupMenu( menuBar ); QPopupMenu *cfgMenu = new QPopupMenu( menuBar ); QPopupMenu *searchOptions = new QPopupMenu( cfgMenu ); setToolBarsMovable( false ); toolBar->setHorizontalStretchable( true ); menuBar->insertItem( tr( "Search" ), searchMenu ); menuBar->insertItem( tr( "Settings" ), cfgMenu ); //SETTINGS MENU cfgMenu->insertItem( tr( "Search" ), searchOptions ); QPopupMenu *pop; for (SearchGroup *s = searches.first(); s != 0; s = searches.next() ){ pop = s->popupMenu(); if (pop){ cfgMenu->insertItem( s->text(0), pop ); } } //SEARCH SearchAllAction = new QAction( tr("Search all"),QString::null, 0, this, 0 ); SearchAllAction->setIconSet( Resource::loadIconSet( "find" ) ); // QWhatsThis::add( SearchAllAction, tr("Search everything...") ); connect( SearchAllAction, SIGNAL(activated()), this, SLOT(searchAll()) ); SearchAllAction->addTo( searchMenu ); searchMenu->insertItem( tr( "Options" ), searchOptions ); //SEARCH OPTIONS //actionWholeWordsOnly = new QAction( tr("Whole words only"),QString::null, 0, this, 0, true ); //actionWholeWordsOnly->addTo( searchOptions ); actionCaseSensitiv = new QAction( tr("Case sensitiv"),QString::null, 0, this, 0, true ); actionCaseSensitiv->addTo( searchOptions ); actionWildcards = new QAction( tr("Use wildcards"),QString::null, 0, this, 0, true ); actionWildcards->addTo( searchOptions ); //SEARCH BAR LabelEnterText = new QLabel( searchBar, "Label" ); LabelEnterText->setAutoMask( FALSE ); LabelEnterText->setText( tr( "Search for: " ) ); addToolBar( searchBar, "Search", QMainWindow::Top, TRUE ); QLineEdit *searchEdit = new QLineEdit( searchBar, "seachEdit" ); QWhatsThis::add( searchEdit, tr("Enter your search terms here") ); searchEdit->setFocus(); searchBar->setHorizontalStretchable( TRUE ); searchBar->setStretchableWidget( searchEdit ); //Search button SearchAllAction->addTo( searchBar ); //image ripped of off opie-login/loginwindow.cpp QPixmap image1( ( const char** ) image1_data ); //Clear text ClearSearchText = new QToolButton( searchBar, "ClearSearchText"); ClearSearchText->setText( tr( "" ) ); ClearSearchText->setPixmap( image1 ); - connect( searchEdit, SIGNAL( textChanged( const QString & ) ),this, SLOT( setSearch( const QString & ) ) ); + connect( searchEdit, SIGNAL( textChanged(const QString&) ),this, SLOT( setSearch(const QString&) ) ); connect( ClearSearchText, SIGNAL( clicked() ), searchEdit, SLOT( clear() ) ); } MainWindow::~MainWindow() { Config cfg( "osearch", Config::User ); cfg.setGroup( "search_settings" ); cfg.writeEntry( "caseSensitiv", actionCaseSensitiv->isOn() ); cfg.writeEntry( "wildcards", actionWildcards->isOn() ); //cfg.writeEntry( "whole_words_only", actionWholeWordsOnly->isOn() ); } void MainWindow::setCurrent(QListViewItem *item) { if (!item) return; _currentItem = (OListViewItem*)item; // _currentItem = dynamic_cast<OListViewItem*>(item); if (_currentItem->rtti() == OListViewItem::Result){ ResultItem *res = (ResultItem*)item; // ResultItem *res = dynamic_cast<ResultItem*>(item); richEdit->setText( res->toRichText() ); QIntDict<QString> acts = res->actions(); QButton *button; for (uint i = 0; i < acts.count(); i++){ button = buttonMap[i]; if (!button) { qWarning(" no button for %s", (*acts[i]).latin1() ); button = new QPushButton( buttonBox ); buttonMap.insert( i, button ); signalMapper->setMapping(button, i ); connect(button, SIGNAL(clicked() ), signalMapper, SLOT(map() ) ); } button->setText( *acts[i] ); button->show(); } for (uint i = acts.count(); i < _buttonCount; i++){ button = buttonMap[i]; if (button) button->hide(); } _buttonCount = acts.count(); detailsFrame->show(); buttonBox->show(); }else { detailsFrame->hide(); buttonBox->hide(); } popupTimer->start( 300, true ); } void MainWindow::stopTimer(QListViewItem*) { popupTimer->stop(); } void MainWindow::showPopup() { popupTimer->stop(); if (!_currentItem) return; QPopupMenu *pop = _currentItem->popupMenu(); if (pop) pop->popup( QCursor::pos() ); } void MainWindow::setSearch( const QString &key ) { searchTimer->stop(); _searchString = key; searchTimer->start( 300 ); } void MainWindow::searchStringChanged() { #ifdef NEW_OWAIT OWait("setting search string"); #endif searchTimer->stop(); QString ss = _searchString; //ss = Global::stringQuote( _searchString ); // if (actionWholeWordsOnly->isOn()) // ss = "\\s"+_searchString+"\\s"; // qDebug(" set searchString >%s<",ss.latin1()); QRegExp re( ss ); re.setCaseSensitive( actionCaseSensitiv->isOn() ); re.setWildcard( actionWildcards->isOn() ); for (SearchGroup *s = searches.first(); s != 0; s = searches.next() ) s->setSearch( re ); } void MainWindow::searchAll() { #ifdef NEW_OWAIT OWait("searching..."); #endif for (SearchGroup *s = searches.first(); s != 0; s = searches.next() ){ s->doSearch(); //resultsList->repaint(); } } void MainWindow::slotAction( int act ) { if ( _currentItem && _currentItem->rtti() == OListViewItem::Result){ ResultItem *res = (ResultItem*)_currentItem; // ResultItem *res = dynamic_cast<ResultItem*>(item); res->action(act); } } void MainWindow::optionChanged(int ) { searchStringChanged(); } diff --git a/core/pim/today/plugins/addressbook/addresspluginwidget.cpp b/core/pim/today/plugins/addressbook/addresspluginwidget.cpp index c8652f3..b0d456d 100644 --- a/core/pim/today/plugins/addressbook/addresspluginwidget.cpp +++ b/core/pim/today/plugins/addressbook/addresspluginwidget.cpp @@ -1,221 +1,221 @@ /* * addresspluginwidget.cpp * * copyright : (c) 2003 by Stefan Eilers * email : eilers.stefan@epost.de * * This implementation was derived from the todolist plugin implementation * */ /*************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #include "addresspluginwidget.h" #include <qpe/config.h> #include <opie/ocontact.h> AddressBookPluginWidget::AddressBookPluginWidget( QWidget *parent, const char* name ) : QWidget( parent, name ) { addressLabel = 0l; m_contactdb = 0l; layoutTodo = 0l; // Hä ? Nonsense ! (se) if ( m_contactdb ) { delete m_contactdb; } m_contactdb = new OContactAccess("addressplugin"); - connect( m_contactdb, SIGNAL( signalChanged( const OContactAccess * ) ), - this, SLOT( refresh( const OContactAccess * ) ) ); + connect( m_contactdb, SIGNAL( signalChanged(const OContactAccess*) ), + this, SLOT( refresh(const OContactAccess*) ) ); readConfig(); getAddress(); } AddressBookPluginWidget::~AddressBookPluginWidget() { delete m_contactdb; } void AddressBookPluginWidget::refresh( const OContactAccess* ) { qWarning(" AddressBookPluginWidget::Database was changed externally ! "); m_contactdb->reload(); getAddress(); } void AddressBookPluginWidget::reinitialize() { readConfig(); getAddress(); } void AddressBookPluginWidget::readConfig() { Config cfg( "todayaddressplugin" ); cfg.setGroup( "config" ); m_maxLinesTask = cfg.readNumEntry( "maxlinestask", 5 ); m_maxCharClip = cfg.readNumEntry( "maxcharclip", 38 ); m_daysLookAhead = cfg.readNumEntry( "dayslookahead", 14 ); m_urgentDays = cfg.readNumEntry( "urgentdays", 7 ); m_entryColor = cfg.readEntry("entrycolor", Qt::black.name() ); m_headlineColor = cfg.readEntry( "headlinecolor", Qt::black.name() ); m_urgentColor = cfg.readEntry( "urgentcolor", Qt::red.name() ); m_showBirthdays = cfg.readBoolEntry( "showBirthdays", true ); m_showAnniversaries = cfg.readBoolEntry( "showAnniversaries", true ); } /** * Get the addresss */ void AddressBookPluginWidget::getAddress() { if ( ! layoutTodo ){ layoutTodo = new QVBoxLayout( this ); } if ( ! addressLabel ) { addressLabel = new OClickableLabel( this ); connect( addressLabel, SIGNAL( clicked() ), this, SLOT( startAddressBook() ) ); layoutTodo->addWidget( addressLabel ); } QString output; // Check whether the database provide the search option.. if ( !m_contactdb->hasQuerySettings( OContactAccess::DateDiff ) ){ // Libopie seems to be old.. output = QObject::tr( "Database does not provide this search query ! Please upgrade libOpie !<br>" ); addressLabel->setText( output ); return; } // Define the query for birthdays and start search.. QDate lookAheadDate = QDate::currentDate().addDays( m_daysLookAhead ); int ammount = 0; if ( m_showBirthdays ){ qWarning("Searching from now (%s) until %s ! ", QDate::currentDate().toString().latin1(), lookAheadDate.toString().latin1() ); } if ( m_contactdb->hasQuerySettings( OContactAccess::DateDiff ) ){ OContact querybirthdays; querybirthdays.setBirthday( lookAheadDate ); m_list = m_contactdb->queryByExample( querybirthdays, OContactAccess::DateDiff ); if ( m_list.count() > 0 ){ output = "<font color=" + m_headlineColor + ">" + QObject::tr( "Next birthdays in <b> %1 </b> days:" ) .arg( m_daysLookAhead ) + "</font> <br>"; for ( m_it = m_list.begin(); m_it != m_list.end(); ++m_it ) { if ( ammount++ < m_maxLinesTask ){ // Now we want to calculate how many days //until birthday. We have to set // the correct year to calculate the day diff... QDate destdate = (*m_it).birthday(); destdate.setYMD( QDate::currentDate().year(), destdate.month(), destdate.day() ); if ( QDate::currentDate().daysTo(destdate) < 0 ) destdate.setYMD( QDate::currentDate().year()+1, destdate.month(), destdate.day() ); if ( QDate::currentDate().daysTo(destdate) < m_urgentDays ) output += "<font color=" + m_urgentColor + "><b>-" + (*m_it).fullName() + " (" + QString::number(QDate::currentDate() .daysTo(destdate)) + " Days) </b></font><br>"; else output += "<font color=" + m_entryColor + "><b>-" + (*m_it).fullName() + " (" + QString::number(QDate::currentDate() .daysTo(destdate)) + " Days) </b></font><br>"; } } } else { output = "<font color=" + m_headlineColor + ">" + QObject::tr( "No birthdays in <b> %1 </b> days!" ) .arg( m_daysLookAhead ) + "</font> <br>"; } } if ( m_showAnniversaries ){ // Define the query for anniversaries and start search.. OContact queryanniversaries; queryanniversaries.setAnniversary( lookAheadDate ); m_list = m_contactdb->queryByExample( queryanniversaries, OContactAccess::DateDiff ); ammount = 0; if ( m_list.count() > 0 ){ output += "<font color=" + m_headlineColor + ">" + QObject::tr( "Next anniversaries in <b> %1 </b> days:" ) .arg( m_daysLookAhead ) + "</font> <br>"; for ( m_it = m_list.begin(); m_it != m_list.end(); ++m_it ) { if ( ammount++ < m_maxLinesTask ){ // Now we want to calculate how many days until anniversary. // We have to set the correct year to calculate the day diff... QDate destdate = (*m_it).anniversary(); destdate.setYMD( QDate::currentDate().year(), destdate.month(), destdate.day() ); if ( QDate::currentDate().daysTo(destdate) < 0 ) destdate.setYMD( QDate::currentDate().year()+1, destdate.month(), destdate.day() ); if ( QDate::currentDate().daysTo(destdate) < m_urgentDays ) output += "<font color=" + m_urgentColor + "><b>-" + (*m_it).fullName() + " (" + QString::number(QDate::currentDate() .daysTo( destdate ) ) + " Days) </b></font><br>"; else output += "<font color=" + m_entryColor + "><b>-" + (*m_it).fullName() + " (" + QString::number(QDate::currentDate() .daysTo( destdate ) ) + " Days) </b></font><br>"; } } } else { output += "<font color=" + m_headlineColor + ">" + QObject::tr( "No anniversaries in <b> %1 </b> days!" ) .arg( m_daysLookAhead ) + "</font> <br>"; } } addressLabel->setText( output ); } /** * start the todolist */ void AddressBookPluginWidget::startAddressBook() { QCopEnvelope e( "QPE/System", "execute(QString)" ); e << QString( "addressbook" ); } diff --git a/core/pim/today/plugins/datebook/datebookpluginwidget.cpp b/core/pim/today/plugins/datebook/datebookpluginwidget.cpp index b6707df..0820802 100644 --- a/core/pim/today/plugins/datebook/datebookpluginwidget.cpp +++ b/core/pim/today/plugins/datebook/datebookpluginwidget.cpp @@ -1,140 +1,140 @@ /* * datebookpluginwidget.cpp * * copyright : (c) 2002,2003, 2004 by Maximilian Reiß * email : harlekin@handhelds.org * */ /*************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #include "datebookpluginwidget.h" #include <qpe/config.h> #include <qtl.h> DatebookPluginWidget::DatebookPluginWidget( QWidget *parent, const char* name ) : QWidget(parent, name ) { db = 0l; m_layoutDates = 0l; if ( m_layoutDates ) { delete m_layoutDates; } m_layoutDates = new QVBoxLayout( this ); m_layoutDates->setAutoAdd( true ); m_eventsList.setAutoDelete( true ); readConfig(); getDates(); } DatebookPluginWidget::~DatebookPluginWidget() { delete db; delete m_layoutDates; } void DatebookPluginWidget::readConfig() { Config cfg( "todaydatebookplugin" ); cfg.setGroup( "config" ); m_max_lines_meet = cfg.readNumEntry( "maxlinesmeet", 5 ); m_show_location = cfg.readNumEntry( "showlocation", 1 ); m_show_notes = cfg.readNumEntry( "shownotes", 0 ); m_onlyLater = cfg.readNumEntry( "onlylater", 1 ); m_moreDays = cfg.readNumEntry( "moredays", 0 ); m_timeExtraLine = cfg.readNumEntry( "timeextraline", 1 ); } void DatebookPluginWidget::reinitialize() { readConfig(); refresh(); } void DatebookPluginWidget::refresh() { m_eventsList.clear(); if ( m_layoutDates ) { delete m_layoutDates; } m_layoutDates = new QVBoxLayout( this ); m_layoutDates->setAutoAdd( true ); getDates(); } /** * Get all events that are in the datebook xml file for today */ void DatebookPluginWidget::getDates() { if ( db ) { delete db; } db = new DateBookDB; QDate date = QDate::currentDate(); QValueList<EffectiveEvent> list = db->getEffectiveEvents( date, date.addDays( m_moreDays ) ); qBubbleSort( list ); int count = 0; if ( list.count() > 0 ) { for ( QValueList<EffectiveEvent>::ConstIterator it = list.begin(); it != list.end(); ++it ) { if ( count < m_max_lines_meet ) { if ( !m_onlyLater ) { count++; DateBookEvent *l = new DateBookEvent( *it, this, m_show_location, m_show_notes, m_timeExtraLine ); m_eventsList.append( l ); l->show(); - QObject::connect ( l, SIGNAL( editEvent( const Event & ) ), l, SLOT( editEventSlot( const Event & ) ) ); + QObject::connect ( l, SIGNAL( editEvent(const Event&) ), l, SLOT( editEventSlot(const Event&) ) ); } else { if ( ( QDateTime::currentDateTime() <= (*it).event().end() ) // Show events which span over many days and are not elapsed. || ( ( (*it).event().start().date() != date ) && ( QDateTime::currentDateTime() <= (*it).event().end() ) ) // Show repeated event for today that is not elapsed. || ( ( (*it).event().repeatType() != Event::NoRepeat ) && ( ( date.dayOfWeek() == (*it).date().dayOfWeek() ) && ( QTime::currentTime() < (*it).event().start().time() ) ) ) // Show repeated event for next days. || ( ( (*it).event().repeatType() != Event::NoRepeat ) && ( date.dayOfWeek() != (*it).date().dayOfWeek() ) ) ) { count++; // show only later appointments DateBookEvent *l = new DateBookEvent( *it, this, m_show_location, m_show_notes, m_timeExtraLine ); m_eventsList.append( l ); l->show(); - QObject::connect ( l, SIGNAL( editEvent( const Event & ) ), l, SLOT( editEventSlot( const Event & ) ) ); + QObject::connect ( l, SIGNAL( editEvent(const Event&) ), l, SLOT( editEventSlot(const Event&) ) ); } } } } if ( m_onlyLater && count == 0 ) { QLabel* noMoreEvents = new QLabel( this ); m_eventsList.append( noMoreEvents ); noMoreEvents->show(); noMoreEvents->setText( QObject::tr( "No more appointments today" ) ); } } else { QLabel* noEvents = new QLabel( this ); m_eventsList.append( noEvents ); noEvents->show(); noEvents->setText( QObject::tr( "No appointments today" ) ); } } diff --git a/core/pim/today/plugins/mail/mailpluginwidget.cpp b/core/pim/today/plugins/mail/mailpluginwidget.cpp index 4194270..a8e4c41 100644 --- a/core/pim/today/plugins/mail/mailpluginwidget.cpp +++ b/core/pim/today/plugins/mail/mailpluginwidget.cpp @@ -1,97 +1,97 @@ /* * mailpluginwidget.cpp * * copyright : (c) 2002,2003,2004 by Maximilian Reiß * email : harlekin@handhelds.org * */ /*************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #include "mailpluginwidget.h" #include <qpe/config.h> #include <qpe/qcopenvelope_qws.h> MailPluginWidget::MailPluginWidget( QWidget *parent, const char* name) : QWidget(parent, name ) { m_mailLabel = 0l; m_layout = 0l; if ( m_mailLabel ) { delete m_mailLabel; } m_mailLabel = new OClickableLabel( this ); connect( m_mailLabel, SIGNAL( clicked() ), this, SLOT( startMail() ) ); if ( m_layout ) { delete m_layout; } m_layout = new QHBoxLayout( this ); m_layout->setAutoAdd( true ); #if defined(Q_WS_QWS) #if !defined(QT_NO_COP) QCopChannel *qCopChannel = new QCopChannel( "QPE/Pim" , this ); - connect ( qCopChannel, SIGNAL( received( const QCString &, const QByteArray &) ), - this, SLOT ( channelReceived( const QCString &, const QByteArray &) ) ); + connect ( qCopChannel, SIGNAL( received(const QCString&,const QByteArray&) ), + this, SLOT ( channelReceived(const QCString&,const QByteArray&) ) ); #endif #endif readConfig(); getInfo(); } void MailPluginWidget::channelReceived( const QCString &msg, const QByteArray & data ) { QDataStream stream( data, IO_ReadOnly ); if ( msg == "outgoingMails(int)" ) { stream >> m_outgoing; } else if ( msg == "newMails(int)" ) { stream >> m_newMails; } getInfo(); } MailPluginWidget::~MailPluginWidget() { delete m_mailLabel; delete m_layout; } void MailPluginWidget::readConfig() { Config cfg( "todaymailplugin" ); cfg.setGroup( "config" ); Config cfg2( "mail" ); cfg2.setGroup( "Status" ); m_newMails = cfg2.readNumEntry( "newMails", 0 ); m_outgoing = cfg2.readNumEntry( "outgoing", 0 ); } void MailPluginWidget::refresh() { getInfo(); } void MailPluginWidget::getInfo() { m_mailLabel->setText( QObject::tr( "<b>%1</b> new mail(s), <b>%2</b> outgoing" ).arg( m_newMails ).arg( m_outgoing ) ); } /** * launches datebook */ void MailPluginWidget::startMail() { QCopEnvelope e("QPE/System", "execute(QString)"); e << QString( "opiemail" ); } diff --git a/core/pim/today/today.cpp b/core/pim/today/today.cpp index 72cdfd6..812f8b5 100644 --- a/core/pim/today/today.cpp +++ b/core/pim/today/today.cpp @@ -1,249 +1,249 @@ /* * today.cpp * * copyright : (c) 2002,2003,2004 by Maximilian Reiß * email : harlekin@handhelds.org * */ /*************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #define QTOPIA_INTERNAL_LANGLIST #include "today.h" #include <qpe/config.h> #include <qpe/qcopenvelope_qws.h> #include <qpe/resource.h> #include <qpe/qpeapplication.h> #include <qpe/contact.h> #include <qdir.h> #include <qtimer.h> #include <qwhatsthis.h> struct TodayPlugin { TodayPlugin() : library( 0 ), iface( 0 ), guiPart( 0 ), guiBox( 0 ) {} QLibrary *library; QInterfacePtr<TodayPluginInterface> iface; TodayPluginObject *guiPart; QWidget *guiBox; QString name; bool active; bool excludeRefresh; int pos; }; static QValueList<TodayPlugin> pluginList; static QMap<QString, TodayPlugin> tempList; Today::Today( QWidget* parent, const char* name, WFlags fl ) : TodayBase( parent, name, fl ) { QObject::connect( (QObject*)ConfigButton, SIGNAL( clicked() ), this, SLOT( startConfig() ) ); QObject::connect( (QObject*)OwnerField, SIGNAL( clicked() ), this, SLOT( editCard() ) ); #if defined(Q_WS_QWS) #if !defined(QT_NO_COP) QCopChannel *todayChannel = new QCopChannel( "QPE/Today" , this ); - connect ( todayChannel, SIGNAL( received( const QCString &, const QByteArray &) ), - this, SLOT ( channelReceived( const QCString &, const QByteArray &) ) ); + connect ( todayChannel, SIGNAL( received(const QCString&,const QByteArray&) ), + this, SLOT ( channelReceived(const QCString&,const QByteArray&) ) ); #endif #endif setOwnerField(); m_refreshTimer = new QTimer( this ); connect( m_refreshTimer, SIGNAL( timeout() ), this, SLOT( refresh() ) ); m_refreshTimer->start( 15000 ); m_big_box = 0L; layout = new QVBoxLayout( this ); layout->addWidget( Frame ); layout->addWidget( OwnerField ); m_sv = new QScrollView( this ); m_sv->setResizePolicy( QScrollView::AutoOneFit ); m_sv->setHScrollBarMode( QScrollView::AlwaysOff ); m_sv->setFrameShape( QFrame::NoFrame ); layout->addWidget( m_sv ); layout->setStretchFactor( m_sv,4 ); qApp->processEvents(); loadPlugins(); QPEApplication::showWidget( this ); } /** * Qcop receive method. */ void Today::channelReceived( const QCString &msg, const QByteArray & data ) { QDataStream stream( data, IO_ReadOnly ); if ( msg == "message(QString)" ) { QString message; stream >> message; setOwnerField( message ); } } void Today::setRefreshTimer( int interval ) { disconnect( m_refreshTimer, SIGNAL( timeout() ), this, SLOT( refresh() ) ); // 0 is "never" case if ( !interval == 0 ) { connect( m_refreshTimer, SIGNAL( timeout() ), this, SLOT( refresh() ) ); m_refreshTimer->changeInterval( interval ); } } /** * Initialises the owner field with the default value, the username */ void Today::setOwnerField() { QString file = Global::applicationFileName( "addressbook", "businesscard.vcf" ); if ( QFile::exists( file ) ) { Contact cont = Contact::readVCard( file )[0]; QString returnString = cont.fullName(); OwnerField->setText( "<b>" + tr ( "Owned by " ) + returnString + "</b>" ); } else { OwnerField->setText( "<b>" + tr ( "Please fill out the business card" ) + " </b>" ); } } /** * Set the owner field with a given QString, for example per qcop. */ void Today::setOwnerField( QString &message ) { if ( !message.isEmpty() ) { OwnerField->setText( "<b>" + message + "</b>" ); } } /** * Init stuff needed for today. Reads the config file. */ void Today::init() { // read config Config cfg( "today" ); cfg.setGroup( "Plugins" ); m_excludeApplets = cfg.readListEntry( "ExcludeApplets", ',' ); m_allApplets = cfg.readListEntry( "AllApplets", ',' ); cfg.setGroup( "General" ); m_iconSize = cfg.readNumEntry( "IconSize", 18 ); m_hideBanner = cfg.readNumEntry( "HideBanner", 0 ); setRefreshTimer( cfg.readNumEntry( "checkinterval", 15000 ) ); // set the date in top label QDate date = QDate::currentDate(); DateLabel->setText( QString( "<font color=#FFFFFF>" + TimeString::longDateString( date ) + "</font>" ) ); if ( m_hideBanner ) { Opiezilla->hide(); TodayLabel->hide(); } else { Opiezilla->show(); TodayLabel->show(); } if ( m_big_box ) { delete m_big_box; } m_big_box = new QWidget( m_sv->viewport() ); m_sv->addChild( m_big_box ); m_bblayout = new QVBoxLayout ( m_big_box ); } /** * Load the plugins */ void Today::loadPlugins() { init(); QValueList<TodayPlugin>::Iterator tit; if ( !pluginList.isEmpty() ) { for ( tit = pluginList.begin(); tit != pluginList.end(); ++tit ) { (*tit).guiBox->hide(); (*tit).guiBox->reparent( 0, QPoint( 0, 0 ) ); delete (*tit).guiBox; (*tit).library->unload(); delete (*tit).library; } pluginList.clear(); } QString path = QPEApplication::qpeDir() + "/plugins/today"; #ifdef Q_OS_MACX qWarning("Searching for Plugins in: %s", path.latin1()); QDir dir( path, "lib*.dylib" ); #else QDir dir( path, "lib*.so" ); #endif QStringList list = dir.entryList(); QStringList::Iterator it; // QMap<QString, TodayPlugin> tempList; for ( it = list.begin(); it != list.end(); ++it ) { QInterfacePtr<TodayPluginInterface> iface; QLibrary *lib = new QLibrary( path + "/" + *it ); qDebug( "querying: %s", QString( path + "/" + *it ).latin1() ); if ( lib->queryInterface( IID_TodayPluginInterface, (QUnknownInterface**)&iface ) == QS_OK ) { qDebug( "accepted: %s", QString( path + "/" + *it ).latin1() ); qDebug( QString(*it) ); TodayPlugin plugin; plugin.library = lib; plugin.iface = iface; plugin.name = QString(*it); QString type = (*it).left( (*it).find(".") ); QString lang; Config config("locale"); config.setGroup("Language"); lang = config.readEntry( "Language", "en" ); qDebug( "Languages: " + lang ); QTranslator * trans = new QTranslator( qApp ); QString tfn = QPEApplication::qpeDir()+"/i18n/" + lang + "/" + type + ".qm"; if ( trans->load( tfn ) ) { qApp->installTranslator( trans ); } else { delete trans; } // find out if plugins should be shown if ( m_excludeApplets.grep( *it ).isEmpty() ) { plugin.active = true; } else { plugin.active = false; } plugin.guiPart = plugin.iface->guiPart(); plugin.excludeRefresh = plugin.guiPart->excludeFromRefresh(); // package the whole thing into a qwidget so it can be shown and hidden plugin.guiBox = new QWidget( m_big_box ); QHBoxLayout *boxLayout = new QHBoxLayout( plugin.guiBox ); QPixmap plugPix; plugPix.convertFromImage( Resource::loadImage( plugin.guiPart->pixmapNameWidget() ).smoothScale( m_iconSize, m_iconSize ), 0 ); OClickableLabel* plugIcon = new OClickableLabel( plugin.guiBox ); plugIcon->setPixmap( plugPix ); QWhatsThis::add( plugIcon, tr("Click here to launch the associated app") ); diff --git a/core/pim/today/todayconfig.cpp b/core/pim/today/todayconfig.cpp index 5c51515..a6f53e1 100644 --- a/core/pim/today/todayconfig.cpp +++ b/core/pim/today/todayconfig.cpp @@ -1,230 +1,230 @@ /* * todayconfig.cpp * * copyright : (c) 2002, 2003, 2004 by Maximilian Reiß * email : harlekin@handhelds.org * */ /*************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #include "todayconfig.h" #include <qpe/config.h> #include <qpe/resource.h> #include <qpe/qcopenvelope_qws.h> #include <qpe/qpeapplication.h> #include <qcheckbox.h> #include <qlabel.h> #include <qspinbox.h> #include <qlayout.h> #include <qheader.h> #include <qvbox.h> #include <qtoolbutton.h> #include <qwhatsthis.h> class ToolButton : public QToolButton { public: ToolButton( QWidget *parent, const char *name, const QString& icon, QObject *handler, const QString& slot, bool t = FALSE ) : QToolButton( parent, name ) { setPixmap( Resource::loadPixmap( icon ) ); setAutoRaise( TRUE ); setFocusPolicy( QWidget::NoFocus ); setToggleButton( t ); connect( this, t ? SIGNAL( toggled(bool) ) : SIGNAL( clicked() ), handler, slot ); } }; /** * The class has currently quite some duplicate code. * By that way it would be real easy to have it as seperate app in settings tab * */ TodayConfig::TodayConfig( QWidget* parent, const char* name, bool modal ) : QDialog( parent, name, modal, WStyle_ContextHelp ) { setCaption( tr( "Today Config" ) ); QVBoxLayout *layout = new QVBoxLayout( this ); TabWidget3 = new OTabWidget ( this, "tabwidget", OTabWidget::Global, OTabWidget::Bottom ); layout->addWidget( TabWidget3 ); tab_2 = new QWidget( TabWidget3, "tab_2" ); QVBoxLayout *tab2Layout = new QVBoxLayout( tab_2, 4 ,4 ); QLabel *l = new QLabel( tr( "Load which plugins in what order:" ), tab_2 ); tab2Layout->addWidget( l ); QHBox *hbox1 = new QHBox( tab_2 ); m_appletListView = new QListView( hbox1 ); m_appletListView->addColumn( "PluginList" ); m_appletListView->header()->hide(); m_appletListView->setSorting( -1 ); QWhatsThis::add( m_appletListView, tr( "Check a checkbox to activate/deactivate a plugin or use the arrow buttons on the right to change the appearance order" ) ); QVBox *vbox1 = new QVBox( hbox1 ); new ToolButton( vbox1, tr( "Move Up" ), "up", this , SLOT( moveSelectedUp() ) ); new ToolButton( vbox1, tr( "Move Down" ), "down", this , SLOT( moveSelectedDown() ) ); tab2Layout->addWidget( hbox1 ); TabWidget3->addTab( tab_2, "pass", tr( "active/order" ) ); // Misc tab tab_3 = new QWidget( TabWidget3, "tab_3" ); QVBoxLayout *tab3Layout = new QVBoxLayout( tab_3 ); m_guiMisc = new TodayConfigMiscBase( tab_3 ); tab3Layout->addWidget( m_guiMisc ); TabWidget3->addTab( tab_3, "SettingsIcon", tr( "Misc" ) ); m_applets_changed = false; - connect ( m_appletListView , SIGNAL( clicked ( QListViewItem * ) ), this, SLOT( appletChanged ( ) ) ); + connect ( m_appletListView , SIGNAL( clicked(QListViewItem*) ), this, SLOT( appletChanged() ) ); readConfig(); QPEApplication::showDialog( this ); } /** * Autostart, uses the new (opie only) autostart method in the launcher code. * If registered against that today ist started on each resume. */ void TodayConfig::setAutoStart() { Config cfg( "today" ); cfg.setGroup( "Autostart" ); if ( m_autoStart ) { QCopEnvelope e( "QPE/System", "autoStart(QString,QString,QString)" ); e << QString( "add" ); e << QString( "today" ); e << QString( "%1" ).arg( m_autoStartTimer ); } else { QCopEnvelope e( "QPE/System", "autoStart(QString,QString)" ); e << QString( "remove" ); e << QString( "today" ); } } /** * Read the config part */ void TodayConfig::readConfig() { Config cfg( "today" ); cfg.setGroup( "Autostart" ); m_autoStart = cfg.readNumEntry( "autostart", 1 ); m_guiMisc->CheckBoxAuto->setChecked( m_autoStart ); m_autoStartTimer = cfg.readNumEntry( "autostartdelay", 0 ); m_guiMisc->SpinBoxTime->setValue( m_autoStartTimer ); cfg.setGroup( "General" ); m_iconSize = cfg.readNumEntry( "IconSize", 18 ); m_guiMisc->SpinBoxIconSize->setValue( m_iconSize ); m_guiMisc->SpinRefresh->setValue( cfg.readNumEntry( "checkinterval", 15000 ) / 1000 ); m_guiMisc->CheckBoxHide->setChecked( cfg.readNumEntry( "HideBanner", 0 ) ); cfg.setGroup( "Plugins" ); m_excludeApplets = cfg.readListEntry( "ExcludeApplets", ',' ); } /** * Write the config part */ void TodayConfig::writeConfig() { Config cfg( "today" ); cfg.setGroup( "Plugins" ); if ( m_applets_changed ) { QStringList exclude; QStringList include; QStringList all_applets; QListViewItemIterator list_it( m_appletListView ); // this makes sure the names get saved in the order selected for ( ; list_it.current(); ++list_it ) { QMap <QString, QCheckListItem *>::Iterator it; for ( it = m_applets.begin(); it != m_applets. end (); ++it ) { if ( list_it.current() == (*it) && !(*it)-> isOn () ) { exclude << it.key(); } else if ( list_it.current() == (*it) && (*it)-> isOn () ){ include << it.key(); } if ( list_it.current() == (*it) ) { all_applets << it.key(); } } } cfg.writeEntry( "ExcludeApplets", exclude, ',' ); cfg.writeEntry( "IncludeApplets", include, ',' ); cfg.writeEntry( "AllApplets", all_applets, ',' ); } cfg.setGroup( "Autostart" ); m_autoStart = m_guiMisc->CheckBoxAuto->isChecked(); cfg.writeEntry( "autostart", m_autoStart ); m_autoStartTimer = m_guiMisc->SpinBoxTime->value(); cfg.writeEntry( "autostartdelay", m_autoStartTimer ); m_iconSize = m_guiMisc->SpinBoxIconSize->value(); cfg.setGroup( "General" ); cfg.writeEntry( "IconSize", m_iconSize ); cfg.writeEntry( "HideBanner", m_guiMisc->CheckBoxHide->isChecked() ); cfg.writeEntry( "checkinterval", m_guiMisc->SpinRefresh->value()*1000 ); // set autostart settings setAutoStart(); } void TodayConfig::moveSelectedUp() { QListViewItem *item = m_appletListView->selectedItem(); if ( item && item->itemAbove() ) { item->itemAbove()->moveItem( item ); } } void TodayConfig::moveSelectedDown() { QListViewItem *item = m_appletListView->selectedItem(); if ( item && item->itemBelow() ) { item->moveItem( item->itemBelow() ); } } /** * Set up the icons in the order/active tab */ void TodayConfig::pluginManagement( QString libName, QString name, QPixmap icon ) { QCheckListItem *item; item = new QCheckListItem( m_appletListView, name, QCheckListItem::CheckBox ); if ( !icon.isNull() ) { item->setPixmap( 0, icon ); } if ( m_excludeApplets.find( libName ) == m_excludeApplets.end() ) { item->setOn( TRUE ); } m_applets[libName] = item; // kind of hack to get the first tab as default. TabWidget3->setCurrentTab( tab_2 ); } void TodayConfig::appletChanged() { m_applets_changed = true; } TodayConfig::~TodayConfig() { } diff --git a/core/pim/todo/mainwindow.cpp b/core/pim/todo/mainwindow.cpp index b68aad2..a244e58 100644 --- a/core/pim/todo/mainwindow.cpp +++ b/core/pim/todo/mainwindow.cpp @@ -1,384 +1,384 @@ /* =. This file is part of the OPIE Project .=l. Copyright (c) 2002 <> .>+-= _;:, .> :=|. This program is free software; you can .> <`_, > . <= redistribute it and/or modify it under :`=1 )Y*s>-.-- : the terms of the GNU General Public .="- .-=="i, .._ License as published by the Free Software - . .-<_> .<> Foundation; either version 2 of the License, ._= =} : or (at your option) any later version. .%`+i> _;_. .i_,=:_. -<s. This program 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 -_. . . )=. = 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 <unistd.h> #include <opie2/opimrecurrence.h> #include <opie2/opimnotifymanager.h> #include <opie2/otodoaccessvcal.h> #include <opie2/oapplicationfactory.h> #include <qpe/applnk.h> #include <qpe/config.h> #include <qpe/ir.h> #include <qpe/resource.h> #include <qpe/qpemessagebox.h> #include <qpe/alarmserver.h> #include <qpe/qpeapplication.h> #include <qmenubar.h> #include <qmessagebox.h> #include <qpushbutton.h> #include <qaction.h> #include <qtimer.h> #include <qlayout.h> #include <qwhatsthis.h> #include "quickeditimpl.h" #include "todotemplatemanager.h" #include "templateeditor.h" #include "tableview.h" #include "textviewshow.h" #include "todoeditor.h" #include "mainwindow.h" OPIE_EXPORT_APP( OApplicationFactory<Todo::MainWindow> ) using namespace Todo; MainWindow::MainWindow( QWidget* parent, const char* name, WFlags ) : OPimMainWindow( "Todolist", parent, name, WType_TopLevel | WStyle_ContextHelp ) { if (!name) setName("todo window"); m_syncing = false; m_showing = false; m_counter = 0; m_tempManager = new TemplateManager(); m_tempManager->load(); initUI(); initConfig(); initViews(); initActions(); initEditor(); initShow(); initTemplate(); populateTemplates(); raiseCurrentView(); QTimer::singleShot(0, this, SLOT(populateCategories() ) ); } void MainWindow::initTemplate() { m_curTempEd = new TemplateEditor( this, templateManager() ); } void MainWindow::initActions() { // Data menu m_edit->insertItem(QWidget::tr("New from template"), m_template, -1, 0 ); QAction* a = new QAction( QWidget::tr("New Task" ), Resource::loadPixmap( "new" ), QString::null, 0, this, 0 ); connect(a, SIGNAL( activated() ), this, SLOT( slotNew() ) ); a->setWhatsThis( QWidget::tr( "Click here to create a new task." ) ); a->addTo(m_tool ); a->addTo(m_edit ); a = new QAction( QWidget::tr("Edit Task"), Resource::loadIconSet( "edit" ), QString::null, 0, this, 0 ); connect(a, SIGNAL(activated() ), this, SLOT( slotEdit() ) ); a->setWhatsThis( QWidget::tr( "Click here to modify the current task." ) ); a->addTo( m_tool ); a->addTo( m_edit ); m_editAction = a; a = new QAction( QString::null, QWidget::tr("View Task"), 0, this, 0 ); connect(a, SIGNAL( activated() ), this, SLOT( slotShowDetails() ) ); a->addTo( m_edit ); m_edit->insertSeparator(); a = new QAction( QWidget::tr("Delete..."), Resource::loadIconSet( "trash" ), QString::null, 0, this, 0 ); connect(a, SIGNAL(activated() ), this, SLOT(slotDelete() ) ); a->setWhatsThis( QWidget::tr( "Click here to remove the current task." ) ); a->addTo( m_tool ); a->addTo( m_edit ); m_deleteAction = a; a = new QAction( QString::null, QWidget::tr("Delete all..."), 0, this, 0 ); connect(a, SIGNAL( activated() ), this, SLOT( slotDeleteAll() ) ); a->addTo(m_edit ); m_deleteAllAction = a; a = new QAction( QString::null, QWidget::tr("Delete completed"), 0, this, 0 ); connect(a, SIGNAL( activated() ), this, SLOT( slotDeleteCompleted() ) ); a->addTo(m_edit ); a->setEnabled( TRUE ); m_deleteCompleteAction = a; m_edit->insertSeparator(); a = new QAction( QString::null, QWidget::tr("Duplicate"), 0, this, 0 ); connect(a, SIGNAL( activated() ), this, SLOT( slotDuplicate() ) ); a->addTo(m_edit ); m_duplicateAction = a; m_edit->insertSeparator(); if ( Ir::supported() ) { a = new QAction( QWidget::tr( "Beam" ), Resource::loadPixmap( "beam" ), QString::null, 0, this, 0 ); connect( a, SIGNAL( activated() ), this, SLOT( slotBeam() ) ); a->setWhatsThis( QWidget::tr( "Click here to send the current task to another device." ) ); a->addTo( m_edit ); a->addTo( m_tool ); } #if 0 // Options menu a = new QAction( QWidget::tr("Find"), Resource::loadIconSet( "mag" ), QString::null, 0, this, 0 ); connect(a, SIGNAL( activated() ), this, SLOT( slotFind() ) ); a->addTo( m_options ); m_findAction = a; m_options->insertSeparator(); #endif m_completedAction = new QAction( QString::null, QWidget::tr("Show completed tasks"), 0, this, 0, TRUE ); m_completedAction->addTo( m_options ); m_completedAction->setOn( showCompleted() ); connect(m_completedAction, SIGNAL( toggled(bool) ), this, SLOT(slotShowCompleted(bool) ) ); a = new QAction( QString::null, QWidget::tr("Show only over-due tasks"), 0, this, 0, TRUE ); a->addTo( m_options ); a->setOn( showOverDue() ); connect(a, SIGNAL(toggled(bool)), this, SLOT(slotShowDue(bool) ) ); m_showDeadLineAction = new QAction( QString::null, QWidget::tr("Show task deadlines"), 0, this, 0, TRUE ); m_showDeadLineAction->addTo( m_options ); m_showDeadLineAction->setOn( showDeadline() ); - connect(m_showDeadLineAction, SIGNAL(toggled(bool) ), this, SLOT( slotShowDeadLine( bool ) ) ); + connect(m_showDeadLineAction, SIGNAL(toggled(bool) ), this, SLOT( slotShowDeadLine(bool) ) ); m_showQuickTaskAction = new QAction( QString::null, QWidget::tr("Show quick task bar"), 0, this, 0, TRUE ); m_showQuickTaskAction->addTo( m_options ); m_showQuickTaskAction->setOn( showQuickTask() ); connect(m_showQuickTaskAction, SIGNAL( toggled(bool) ), this, SLOT(slotShowQuickTask(bool) ) ); m_options->insertSeparator(); m_bar->insertItem( QWidget::tr("Data") ,m_edit ); m_bar->insertItem( QWidget::tr("Category"), m_catMenu ); m_bar->insertItem( QWidget::tr("Options"), m_options ); m_curQuick = new QuickEditImpl( this, m_quicktask ); addToolBar( (QToolBar *)m_curQuick->widget(), QWidget::tr( "QuickEdit" ), QMainWindow::Top, TRUE ); m_curQuick->signal()->connect( this, SLOT(slotQuickEntered() ) ); } /* m_curCat from Config */ void MainWindow::initConfig() { Config config( "todo" ); config.setGroup( "View" ); m_completed = config.readBoolEntry( "ShowComplete", TRUE ); m_curCat = config.readEntry( "Category", QString::null ); m_deadline = config.readBoolEntry( "ShowDeadLine", TRUE); m_overdue = config.readBoolEntry("ShowOverDue", FALSE ); m_quicktask = config.readBoolEntry("ShowQuickTask", TRUE); } void MainWindow::initUI() { m_stack = new OWidgetStack(this, "main stack"); setCentralWidget( m_stack ); setToolBarsMovable( FALSE ); QToolBar *menubarholder = new QToolBar( this ); menubarholder->setHorizontalStretchable( TRUE ); m_bar = new QMenuBar( menubarholder ); m_tool = new QToolBar( this ); /** QPopupMenu */ m_edit = new QPopupMenu( this ); m_options = new QPopupMenu( this ); m_catMenu = new QPopupMenu( this ); m_template = new QPopupMenu( this ); m_catMenu->setCheckable( TRUE ); m_template->setCheckable( TRUE ); connect(m_catMenu, SIGNAL(activated(int) ), this, SLOT(setCategory(int) ) ); connect(m_template, SIGNAL(activated(int) ), this, SLOT(slotNewFromTemplate(int) ) ); } void MainWindow::initViews() { TableView* tableView = new TableView( this, m_stack ); QWhatsThis::add( tableView, QWidget::tr( "This is a listing of all current tasks.\n\nThe list displays the following information:\n1. Completed - A green checkmark indicates task is completed. Click here to complete a task.\n2. Priority - a graphical representation of task priority. Double-click here to modify.\n3. Description - description of task. Click here to select the task.\n4. Deadline - shows when task is due. This column can be shown or hidden by selecting Options->'Show task deadlines' from the menu above." ) ); m_stack->addWidget( tableView, m_counter++ ); m_views.append( tableView ); m_curView = tableView; connectBase( tableView ); /* add QString type + QString configname to * the View menu * and subdirs for multiple views */ } void MainWindow::initEditor() { m_curEdit = new Editor(); } void MainWindow::initShow() { m_curShow = new TextViewShow(this, this); m_stack->addWidget( m_curShow->widget() , m_counter++ ); } MainWindow::~MainWindow() { delete templateManager(); } void MainWindow::connectBase( ViewBase* ) { // once templates and signals mix we'll use it again } QPopupMenu* MainWindow::contextMenu( int , bool recur ) { QPopupMenu* menu = new QPopupMenu(); m_editAction->addTo( menu ); m_deleteAction->addTo( menu ); m_duplicateAction->addTo( menu ); menu->insertSeparator(); /* * if this event recurs we allow * to detach it. * remove all */ if ( recur ) { ; // FIXME } return menu; } QPopupMenu* MainWindow::options() { qWarning("Options"); return m_options; } QPopupMenu* MainWindow::edit() { return m_edit; } QToolBar* MainWindow::toolbar() { return m_tool; } OPimTodoAccess::List MainWindow::list()const { return m_todoMgr.list(); } OPimTodoAccess::List MainWindow::sorted( bool asc, int sortOrder ) { int cat = 0; if ( m_curCat != QWidget::tr("All Categories") ) cat = currentCatId(); if ( m_curCat == QWidget::tr("Unfiled") ) cat = -1; qWarning(" Category %d %s", cat, m_curCat.latin1() ); int filter = 1; if (!m_completed ) filter |= 4; if (m_overdue) filter |= 2; return m_todoMgr.sorted( asc, sortOrder, filter, cat ); } OPimTodoAccess::List MainWindow::sorted( bool asc, int sortOrder, int addFilter) { int cat = 0; if ( m_curCat != QWidget::tr("All Categories") ) cat = currentCatId(); if ( m_curCat == QWidget::tr("Unfiled") ) cat = -1; return m_todoMgr.sorted(asc, sortOrder, addFilter, cat ); } OPimTodo MainWindow::event( int uid ) { return m_todoMgr.event( uid ); } bool MainWindow::isSyncing()const { return m_syncing; } TemplateManager* MainWindow::templateManager() { return m_tempManager; } Editor* MainWindow::currentEditor() { return m_curEdit; } TodoShow* MainWindow::currentShow() { return m_curShow; } void MainWindow::slotReload() { m_syncing = FALSE; m_todoMgr.reload(); currentView()->updateView( ); raiseCurrentView(); } void MainWindow::closeEvent( QCloseEvent* e ) { if (m_stack->visibleWidget() == currentShow()->widget() ) { m_showing = false; raiseCurrentView(); e->ignore(); return; } /* * we should have flushed and now we're still saving * so there is no need to flush */ if (m_syncing ) { e->accept(); return; } bool quit = false; if ( m_todoMgr.saveAll() ){ qWarning("saved"); quit = true; }else { if ( QMessageBox::critical( this, QWidget::tr("Out of space"), QWidget::tr("Todo was unable\n" "to save your changes.\n" "Free up some space\n" "and try again.\n" "\nQuit Anyway?"), QMessageBox::Yes|QMessageBox::Escape, QMessageBox::No|QMessageBox::Default) diff --git a/core/pim/todo/otaskeditor.cpp b/core/pim/todo/otaskeditor.cpp index ab1ce94..d1e50f7 100644 --- a/core/pim/todo/otaskeditor.cpp +++ b/core/pim/todo/otaskeditor.cpp @@ -1,90 +1,90 @@ #include <qlayout.h> #include "taskeditoroverview.h" #include "taskeditorstatus.h" #include "taskeditoralarms.h" #include "otaskeditor.h" OTaskEditor::OTaskEditor(int cur) : QDialog( 0, 0, TRUE, WStyle_ContextHelp ) { init(); init( cur ); } OTaskEditor::OTaskEditor( const OPimTodo& to) : QDialog( 0, 0, TRUE, WStyle_ContextHelp ) { init(); init( to ); } OTaskEditor::~OTaskEditor() { } void OTaskEditor::init( int cur ) { OPimTodo to; to.setUid( 1 ); // generate a new uid if ( cur != 0 ) to.setCategories( cur ); load(to); } void OTaskEditor::init( const OPimTodo& to ) { load( to ); } OPimTodo OTaskEditor::todo()const{ qWarning("saving!"); OPimTodo to ( m_todo ); m_overView->save( to ); m_stat->save( to ); to.setRecurrence( m_rec->recurrence() ); m_alarm->save( to ); return to; } void OTaskEditor::load(const OPimTodo& to) { m_overView->load( to ); m_stat->load( to ); m_rec->setRecurrence( to.recurrence(), to.hasDueDate() ? to.dueDate() : QDate::currentDate() ); m_alarm->load( to ); m_todo = to; } void OTaskEditor::init() { setCaption(tr("Task Editor") ); QVBoxLayout* layo = new QVBoxLayout( this ); m_tab = new OTabWidget( this ); layo->addWidget( m_tab ); /* * Add the Widgets */ m_overView = new TaskEditorOverView( m_tab ); m_tab->addTab( m_overView, "todo/info", tr("Information") ); m_stat = new TaskEditorStatus( m_tab ); m_tab->addTab( m_stat, "todo/TodoList", tr("Status") ); m_alarm = new TaskEditorAlarms( m_tab ); m_tab->addTab( m_alarm, "todo/alarm", tr("Alarms") ); // m_remind = new TaskEditorAlarms( m_tab ); // m_tab->addTab( m_remind, "todo/reminder", tr("Reminders") ); // QLabel* lbl = new QLabel( m_tab ); // lbl->setText( tr("X-Ref") ); // m_tab->addTab( lbl, "todo/xref", tr("X-Ref") ); m_rec = new OPimRecurrenceWidget( true, QDate::currentDate(), this ); m_tab->addTab( m_rec, "repeat", tr("Recurrence") ); /* signal and slots */ connect(m_overView, SIGNAL(recurranceEnabled(bool) ), m_rec, SLOT(setEnabled(bool) ) ); /* connect due date changed to the recurrence tab */ connect(m_stat, SIGNAL(dueDateChanged(const QDate&) ), - m_rec, SLOT(setStartDate(const QDate& ) ) ); + m_rec, SLOT(setStartDate(const QDate&) ) ); m_tab->setCurrentTab( m_overView ); } diff --git a/core/pim/todo/tableview.cpp b/core/pim/todo/tableview.cpp index 5bbf880..0d298f4 100644 --- a/core/pim/todo/tableview.cpp +++ b/core/pim/todo/tableview.cpp @@ -1,318 +1,318 @@ /* =. This file is part of the OPIE Project .=l. Copyright (c) 2002 <zecke> .>+-= _;:, .> :=|. This program is free software; you can .> <`_, > . <= redistribute it and/or modify it under :`=1 )Y*s>-.-- : the terms of the GNU General Public .="- .-=="i, .._ License as published by the Free Software - . .-<_> .<> Foundation; either version 2 of the License, ._= =} : or (at your option) any later version. .%`+i> _;_. .i_,=:_. -<s. This program 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 <stdlib.h> #include <cmath> #include <cctype> #include <qcombobox.h> #include <qlineedit.h> #include <qtimer.h> #include <qpopupmenu.h> #include <qpe/config.h> #include <qpe/resource.h> #include <opie2/opimrecurrence.h> #include "mainwindow.h" //#include "tableitems.h" #include "tableview.h" using namespace Todo; namespace { static const int BoxSize = 14; static const int RowHeight = 20; } TableView::EditorWidget::EditorWidget() : m_wid(0l), m_row(-1), m_col(-1) { } void TableView::EditorWidget::setCellWidget(QWidget* wid, int row, int col ) { m_wid = wid; m_row = row; m_col = col; } void TableView::EditorWidget::releaseCellWidget() { m_wid = 0; m_row = m_col = -1; } QWidget* TableView::EditorWidget::cellWidget()const { return m_wid; } int TableView::EditorWidget::cellRow()const { return m_row; } int TableView::EditorWidget::cellCol()const { return m_col; } void TableView::initConfig() { Config config( "todo" ); config.setGroup( "Options" ); m_completeStrokeWidth = config.readNumEntry( "CompleteStrokeWidth", 8 ); for (int i = 0; i < numCols(); i++ ) { int width = config.readNumEntry("Width"+QString::number(i), -1 ); setColumnWidth(i, width == -1 ? columnWidth(i) : width ); } } TableView::TableView( MainWindow* window, QWidget* wid ) : QTable( wid ), TodoView( window ) { setName("TableView"); // Load icons // TODO - probably should be done globally somewhere else, // see also quickeditimpl.cpp/h, taskeditoroverview.cpp/h m_pic_completed = Resource::loadPixmap( "todo/completed" ); QString namestr; for ( unsigned int i = 1; i < 6; i++ ) { namestr = "todo/priority"; namestr.append( QString::number( i ) ); m_pic_priority[ i - 1 ] = Resource::loadPixmap( namestr ); } setUpdatesEnabled( false ); viewport()->setUpdatesEnabled( false ); m_enablePaint = false; setNumRows(0); setNumCols(4); horizontalHeader()->setLabel( 0, QWidget::tr("C.") ); horizontalHeader()->setLabel( 1, QWidget::tr("Priority") ); horizontalHeader()->setLabel( 2, QWidget::tr("Summary" ) ); horizontalHeader()->setLabel( 3, QWidget::tr("Deadline") ); setShowDeadline( todoWindow()->showDeadline() ); setSorting( TRUE ); setSelectionMode( NoSelection ); setLeftMargin( 0 ); verticalHeader()->hide(); - connect((QTable*)this, SIGNAL( clicked( int, int, int, const QPoint& ) ), - this, SLOT( slotClicked(int, int, int, const QPoint& ) ) ); - connect((QTable*)this, SIGNAL( pressed( int, int, int, const QPoint& ) ), - this, SLOT( slotPressed(int, int, int, const QPoint& ) ) ); - connect((QTable*)this, SIGNAL(valueChanged(int, int) ), - this, SLOT( slotValueChanged(int, int) ) ); - connect((QTable*)this, SIGNAL(currentChanged(int, int) ), - this, SLOT( slotCurrentChanged(int, int) ) ); + connect((QTable*)this, SIGNAL( clicked(int,int,int,const QPoint&) ), + this, SLOT( slotClicked(int,int,int,const QPoint&) ) ); + connect((QTable*)this, SIGNAL( pressed(int,int,int,const QPoint&) ), + this, SLOT( slotPressed(int,int,int,const QPoint&) ) ); + connect((QTable*)this, SIGNAL(valueChanged(int,int) ), + this, SLOT( slotValueChanged(int,int) ) ); + connect((QTable*)this, SIGNAL(currentChanged(int,int) ), + this, SLOT( slotCurrentChanged(int,int) ) ); m_menuTimer = new QTimer( this ); connect( m_menuTimer, SIGNAL(timeout()), this, SLOT(slotShowMenu()) ); /* now let's init the config */ initConfig(); m_enablePaint = true; setUpdatesEnabled( true ); viewport()->setUpdatesEnabled( true ); viewport()->update(); setSortOrder( 0 ); setAscending( TRUE ); m_first = true; } /* a new day has started * update the day */ void TableView::newDay() { clear(); updateView(); } TableView::~TableView() { Config config( "todo" ); config.setGroup( "Options" ); for (int i = 0; i < numCols(); i++ ) config.writeEntry("Width"+QString::number(i), columnWidth(i) ); } void TableView::slotShowMenu() { QPopupMenu *menu = todoWindow()->contextMenu( current(), sorted()[currentRow()].recurrence().doesRecur() ); menu->exec(QCursor::pos() ); delete menu; } QString TableView::type() const { return QString::fromLatin1( tr("Table View") ); } int TableView::current() { if (numRows() == 0 ) return 0; int uid = sorted().uidAt(currentRow() ); return uid; } int TableView::next() { if ( numRows() == 0 ) return 0; if ( currentRow() + 1 >= numRows() ) return 0; setCurrentCell( currentRow() +1, currentColumn() ); return sorted().uidAt( currentRow() ); } int TableView::prev() { if ( numRows() == 0 ) return 0; if ( currentRow() - 1 < 0 ) return 0; setCurrentCell( currentRow() -1, currentColumn() ); return sorted().uidAt( currentRow() ); } QString TableView::currentRepresentation() { OPimTodo to = sorted()[currentRow()]; return to.summary().isEmpty() ? to.description().left(20) : to.summary() ; } /* show overdue */ void TableView::showOverDue( bool ) { clear(); updateView(); } void TableView::updateView( ) { qWarning("update view"); m_row = false; static int id; id = startTimer(4000 ); /* FIXME we want one page to be read! * * Calculate that screensize */ todoWindow()->setReadAhead( 4 ); sort(); OPimTodoAccess::List::Iterator it, end; it = sorted().begin(); end = sorted().end(); qWarning("setTodos"); QTime time; time.start(); m_enablePaint = false; setUpdatesEnabled( false ); viewport()->setUpdatesEnabled( false ); setNumRows( it.count() ); if ( it.count() == 0 ) killTimer(id); // int elc = time.elapsed(); setUpdatesEnabled( true ); viewport()->setUpdatesEnabled( true ); viewport()->update(); m_enablePaint = true; // int el = time.elapsed(); } void TableView::setTodo( int, const OPimTodo&) { sort(); /* repaint */ repaint(); } void TableView::addEvent( const OPimTodo&) { /* fix problems of not showing the 'Haken' */ updateView(); } /* * find the event * and then replace the complete row */ void TableView::replaceEvent( const OPimTodo& ev) { addEvent( ev ); } /* * re aligning table can be slow too * FIXME: look what performs better * either this or the old align table */ void TableView::removeEvent( int ) { updateView(); } void TableView::setShowCompleted( bool b) { qWarning("Show Completed %d" , b ); updateView(); } void TableView::setShowDeadline( bool b ) { qWarning( "Show DeadLine %d" , b ); if ( b ) showColumn( 3 ); else hideColumn( 3 ); // Try to intelligently size columns // TODO - would use width() below, but doesn't have valid value at time of c'tor int col2width = 238; int width = m_pic_completed.width(); setColumnWidth( 0, width ); col2width -= width; width = fontMetrics().boundingRect( horizontalHeader()->label( 1 ) ).width() + 8; setColumnWidth( 1, width ); col2width -= width; if ( b ) { width = fontMetrics().boundingRect( horizontalHeader()->label( 3 ) ).width() + 8; setColumnWidth( 3, width ); col2width -= width; } setColumnWidth( 2, col2width ); } void TableView::setShowCategory( const QString& str) { qWarning("setShowCategory"); if ( str != m_oleCat || m_first ) updateView(); m_oleCat = str; m_first = false; } void TableView::clear() { setNumRows(0); } void TableView::slotClicked(int row, int col, int, const QPoint& point) { if ( m_editorWidget.cellWidget() ) { //setCellContentFromEditor(m_editorWidget.cellRow(), m_editorWidget.cellCol() ); endEdit(m_editorWidget.cellRow(), m_editorWidget.cellCol(), true, true ); m_editorWidget.releaseCellWidget(); } if ( !cellGeometry(row, col ).contains(point ) ) return; int ui= sorted().uidAt( row ); switch( col ) { case 0:{ int x = point.x() -columnPos( col ); int y = point.y() -rowPos( row ); int w = columnWidth( col ); int h = rowHeight( row ); if ( x >= ( w - BoxSize ) / 2 && x <= ( w - BoxSize ) / 2 + BoxSize && y >= ( h - BoxSize ) / 2 && diff --git a/core/pim/todo/taskeditoralarms.cpp b/core/pim/todo/taskeditoralarms.cpp index 930c94e..a512fb0 100644 --- a/core/pim/todo/taskeditoralarms.cpp +++ b/core/pim/todo/taskeditoralarms.cpp @@ -1,232 +1,232 @@ /* =. This file is part of the OPIE Project .=l. Copyright (c) 2002 <> .>+-= _;:, .> :=|. This program is free software; you can .> <`_, > . <= redistribute it and/or modify it under :`=1 )Y*s>-.-- : the terms of the GNU General Public .="- .-=="i, .._ License as published by the Free Software - . .-<_> .<> Foundation; either version 2 of the License, ._= =} : or (at your option) any later version. .%`+i> _;_. .i_,=:_. -<s. This program 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 -_. . . )=. = 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 "taskeditoralarms.h" #include <opie2/opimnotifymanager.h> #include <opie2/otimepicker.h> #include <qpe/datebookmonth.h> #include <qpe/resource.h> #include <qlistview.h> #include <qlayout.h> class AlarmItem : public QListViewItem { public: AlarmItem( QListView*, const OPimAlarm& ); ~AlarmItem(); OPimAlarm alarm()const; void setAlarm( const OPimAlarm& ); private: QDateTime m_dt; int m_type; }; AlarmItem::AlarmItem( QListView* view, const OPimAlarm& dt) : QListViewItem(view) { setAlarm( dt ); } void AlarmItem::setAlarm( const OPimAlarm& dt ) { m_dt = dt.dateTime(); m_type = dt.sound(); setText( 0, TimeString::dateString( m_dt.date() ) ); setText( 1, TimeString::timeString( m_dt.time() ) ); setText( 2, m_type == 0 ? QObject::tr("silent") : QObject::tr("loud") ); } AlarmItem::~AlarmItem() { } OPimAlarm AlarmItem::alarm()const{ OPimAlarm al( m_type, m_dt ); return al; } TaskEditorAlarms::TaskEditorAlarms( QWidget* parent, int, const char* name, WFlags fl ) : QWidget( parent, name, fl ) { m_date = m_type = m_time = 0; QGridLayout *layout = new QGridLayout( this, 2, 2, 4, 4 ); lstAlarms = new QListView( this ); lstAlarms->addColumn( tr("Date") ); lstAlarms->addColumn( tr("Time") ); lstAlarms->addColumn( tr("Type") ); - connect( lstAlarms, SIGNAL(clicked ( QListViewItem *, const QPoint &, int ) ), - this, SLOT(inlineEdit(QListViewItem*, const QPoint&, int ) ) ); + connect( lstAlarms, SIGNAL(clicked(QListViewItem*,const QPoint&,int) ), + this, SLOT(inlineEdit(QListViewItem*,const QPoint&,int) ) ); layout->addMultiCellWidget( lstAlarms, 0, 0, 0, 2 ); QPushButton *btn = new QPushButton( Resource::loadPixmap( "new" ), tr( "New" ), this ); //QWhatsThis::add( btn, tr( "Click here to add a new transaction." ) ); connect( btn, SIGNAL( clicked() ), this, SLOT( slotNew() ) ); layout->addWidget( btn, 1, 0 ); /* use when we've reminders too */ #if 0 btn = new QPushButton( Resource::loadPixmap( "edit" ), tr( "Edit" ), this ); //QWhatsThis::add( btn, tr( "Select a transaction and then click here to edit it." ) ); connect( btn, SIGNAL( clicked() ), this, SLOT( slotEdit() ) ); layout->addWidget( btn, 1, 1 ); #endif btn = new QPushButton( Resource::loadPixmap( "trash" ), tr( "Delete" ), this ); //QWhatsThis::add( btn, tr( "Select a checkbook and then click here to delete it." ) ); connect( btn, SIGNAL( clicked() ), this, SLOT( slotDelete() ) ); layout->addWidget( btn, 1, 2 ); } TaskEditorAlarms::~TaskEditorAlarms(){ } void TaskEditorAlarms::slotNew(){ (void)new AlarmItem(lstAlarms, OPimAlarm(0, QDateTime::currentDateTime() ) ); } void TaskEditorAlarms::slotEdit(){ } void TaskEditorAlarms::slotDelete(){ QListViewItem* item = lstAlarms->currentItem(); if (!item) return; lstAlarms->takeItem( item ); delete item; } void TaskEditorAlarms::load( const OPimTodo& todo) { lstAlarms->clear(); if (!todo.hasNotifiers() ) return; OPimNotifyManager::Alarms als = todo.notifiers().alarms(); if (als.isEmpty() ) return; OPimNotifyManager::Alarms::Iterator it = als.begin(); for ( ; it != als.end(); ++it ) (void)new AlarmItem( lstAlarms, (*it) ); } void TaskEditorAlarms::save( OPimTodo& todo ) { if (lstAlarms->childCount() <= 0 ) return; OPimNotifyManager::Alarms alarms; for ( QListViewItem* item = lstAlarms->firstChild(); item; item = item->nextSibling() ) { AlarmItem *alItem = static_cast<AlarmItem*>(item); alarms.append( alItem->alarm() ); } OPimNotifyManager& manager = todo.notifiers(); manager.setAlarms( alarms ); } void TaskEditorAlarms::inlineEdit( QListViewItem* alarm, const QPoint& p, int col ) { if (!alarm) return; AlarmItem* item = static_cast<AlarmItem*>(alarm); switch( col ) { // date case 0: return inlineSetDate( item, p ); // time case 1: return inlineSetTime( item ); // type case 2: return inlineSetType( item, p ); } } void TaskEditorAlarms::inlineSetDate( AlarmItem* item, const QPoint& p ) { QPopupMenu* pop = popup( 0 ); m_dbMonth->setDate( item->alarm().dateTime().date() ); pop->exec(p); OPimAlarm al = item->alarm(); QDateTime dt = al.dateTime(); dt.setDate( m_dbMonth->selectedDate() ); al.setDateTime( dt ); item->setAlarm( al ); } void TaskEditorAlarms::inlineSetType( AlarmItem* item, const QPoint& p ) { int type; QPopupMenu* pop = popup( 2 ); switch( pop->exec(p) ) { case 10: type = 1; break; case 20: default: type = 0; } OPimAlarm al = item->alarm(); al.setSound( type ); item->setAlarm( al ); } void TaskEditorAlarms::inlineSetTime( AlarmItem* item ) { OPimAlarm al = item->alarm(); QDateTime dt = al.dateTime(); OTimePickerDialog dialog; dialog.setTime( dt.time() ); if ( dialog.exec() == QDialog::Accepted ) { dt.setTime( dialog.time() ); al.setDateTime( dt ); item->setAlarm( al ); } } QPopupMenu* TaskEditorAlarms::popup( int column ) { QPopupMenu* pop = 0; switch( column ) { case 0:{ if (!m_date) { m_date = new QPopupMenu(this); m_dbMonth = new DateBookMonth(m_date, 0, TRUE); m_date->insertItem(m_dbMonth); } pop = m_date; } break; case 1: break; case 2:{ if (!m_type) { m_type = new QPopupMenu(this); m_type->insertItem( QObject::tr("loud"), 10 ); m_type->insertItem( QObject::tr("silent"), 20 ); } pop = m_type; } break; default: break; } return pop; } diff --git a/core/pim/todo/taskeditorstatus.cpp b/core/pim/todo/taskeditorstatus.cpp index 367dd58..16351e0 100644 --- a/core/pim/todo/taskeditorstatus.cpp +++ b/core/pim/todo/taskeditorstatus.cpp @@ -1,302 +1,302 @@ /* =. This file is part of the OPIE Project .=l. Copyright (c) 2002 <> .>+-= _;:, .> :=|. This program is free software; you can .> <`_, > . <= redistribute it and/or modify it under :`=1 )Y*s>-.-- : the terms of the GNU General Public .="- .-=="i, .._ License as published by the Free Software - . .-<_> .<> Foundation; either version 2 of the License, ._= =} : or (at your option) any later version. .%`+i> _;_. .i_,=:_. -<s. This program 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 -_. . . )=. = 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 "taskeditorstatus.h" #include <opie2/opimmaintainer.h> #include <opie2/opimstate.h> #include <qpe/datebookmonth.h> #include <qcheckbox.h> #include <qcombobox.h> #include <qlabel.h> #include <qlayout.h> #include <qwhatsthis.h> // FIXME add the hack slots instead of setPopup!!!! // drw you shouldn't have removed them TaskEditorStatus::TaskEditorStatus( QWidget* parent, const char* name, WFlags fl ) : QWidget( parent, name, fl ) { QDate curDate = QDate::currentDate(); m_start = m_comp = m_due = curDate; QString curDateStr = TimeString::longDateString( curDate ); QVBoxLayout *vb = new QVBoxLayout( this ); QScrollView *sv = new QScrollView( this ); vb->addWidget( sv ); sv->setResizePolicy( QScrollView::AutoOneFit ); sv->setFrameStyle( QFrame::NoFrame ); QWidget *container = new QWidget( sv->viewport() ); sv->addChild( container ); QGridLayout *layout = new QGridLayout( container, 7, 3, 4, 4 ); // Status QLabel *label = new QLabel( tr( "Status:" ), container ); layout->addWidget( label, 0, 0 ); QWhatsThis::add( label, tr( "Click here to set the current status of this task." ) ); cmbStatus = new QComboBox( FALSE, container ); cmbStatus->insertItem( tr( "Started" ) ); cmbStatus->insertItem( tr( "Postponed" ) ); cmbStatus->insertItem( tr( "Finished" ) ); cmbStatus->insertItem( tr( "Not started" ) ); layout->addMultiCellWidget( cmbStatus, 0, 0, 1, 2 ); QWhatsThis::add( cmbStatus, tr( "Click here to set the current status of this task." ) ); // Progress label = new QLabel( tr( "Progress:" ), container ); layout->addWidget( label, 1, 0 ); QWhatsThis::add( label, tr( "Select progress made on this task here." ) ); cmbProgress = new QComboBox( FALSE, container ); cmbProgress->insertItem( tr( "0 %" ) ); cmbProgress->insertItem( tr( "20 %" ) ); cmbProgress->insertItem( tr( "40 %" ) ); cmbProgress->insertItem( tr( "60 %" ) ); cmbProgress->insertItem( tr( "80 %" ) ); cmbProgress->insertItem( tr( "100 %" ) ); layout->addMultiCellWidget( cmbProgress, 1, 1, 1, 2 ); QWhatsThis::add( cmbProgress, tr( "Select progress made on this task here." ) ); // Start date ckbStart = new QCheckBox( tr( "Start Date:" ), container ); layout->addWidget( ckbStart, 2, 0 ); QWhatsThis::add( ckbStart, tr( "Click here to set the date this task was started." ) ); connect( ckbStart, SIGNAL( clicked() ), this, SLOT( slotStartChecked() ) ); btnStart = new QPushButton( curDateStr, container ); btnStart->setEnabled( FALSE ); layout->addMultiCellWidget( btnStart, 2, 2, 1, 2 ); QWhatsThis::add( btnStart, tr( "Click here to set the date this task was started." ) ); QPopupMenu *popup = new QPopupMenu( this ); m_startBook = new DateBookMonth( popup, 0, TRUE ); popup->insertItem( m_startBook ); btnStart->setPopup( popup ); - connect( m_startBook, SIGNAL( dateClicked( int, int, int ) ), - this, SLOT( slotStartChanged( int, int, int ) ) ); + connect( m_startBook, SIGNAL( dateClicked(int,int,int) ), + this, SLOT( slotStartChanged(int,int,int) ) ); // Due date ckbDue = new QCheckBox( tr( "Due Date:" ), container ); layout->addWidget( ckbDue, 3, 0 ); QWhatsThis::add( ckbDue, tr( "Click here to set the date this task needs to be completed by." ) ); connect( ckbDue, SIGNAL( clicked() ), this, SLOT( slotDueChecked() ) ); btnDue = new QPushButton( curDateStr, container ); btnDue->setEnabled( FALSE ); layout->addMultiCellWidget( btnDue, 3, 3, 1, 2 ); QWhatsThis::add( btnDue, tr( "Click here to set the date this task needs to be completed by." ) ); popup = new QPopupMenu( this ); m_dueBook = new DateBookMonth( popup, 0, TRUE ); popup->insertItem( m_dueBook ); btnDue->setPopup( popup ); - connect( m_dueBook, SIGNAL( dateClicked( int, int, int ) ), - this, SLOT( slotDueChanged( int, int, int ) ) ); + connect( m_dueBook, SIGNAL( dateClicked(int,int,int) ), + this, SLOT( slotDueChanged(int,int,int) ) ); // Completed ckbComp = new QCheckBox( tr( "Completed:" ), container ); layout->addWidget( ckbComp, 4, 0 ); QWhatsThis::add( ckbComp, tr( "Click here to mark this task as completed." ) ); connect( ckbComp, SIGNAL( clicked() ), this, SLOT( slotCompChecked() ) ); btnComp = new QPushButton( curDateStr, container ); btnComp->setEnabled( FALSE ); layout->addMultiCellWidget( btnComp, 4, 4, 1, 2 ); QWhatsThis::add( btnComp, tr( "Click here to set the date this task was completed." ) ); popup = new QPopupMenu( this ); m_compBook = new DateBookMonth( popup, 0, TRUE ); popup->insertItem( m_compBook ); btnComp->setPopup( popup ); - connect( m_compBook, SIGNAL( dateClicked( int, int, int ) ), - this, SLOT( slotCompChanged( int, int, int ) ) ); + connect( m_compBook, SIGNAL( dateClicked(int,int,int) ), + this, SLOT( slotCompChanged(int,int,int) ) ); QSpacerItem *spacer = new QSpacerItem( 5, 5, QSizePolicy::Minimum, QSizePolicy::MinimumExpanding ); layout->addItem( spacer, 5, 0 ); // Maintainer mode #if 0 label = new QLabel( tr( "Maintainer Mode:" ), container ); layout->addWidget( label, 6, 0 ); QWhatsThis::add( label, tr( "Click here to set the maintainer's role." ) ); cmbMaintMode = new QComboBox( FALSE, container ); cmbMaintMode->insertItem( tr( "Nothing" ) ); cmbMaintMode->insertItem( tr( "Responsible" ) ); cmbMaintMode->insertItem( tr( "Done By" ) ); cmbMaintMode->insertItem( tr( "Coordinating" ) ); // layout->addMultiCellWidget( cmbMaintMode, 6, 6, 1, 2 ); QWhatsThis::add( cmbMaintMode, tr( "Click here to set the maintainer's role." ) ); // Maintainer label = new QLabel( tr( "Maintainer:" ), container ); layout->addWidget( label, 7, 0 ); QWhatsThis::add( label, tr( "This is the name of the current task maintainer." ) ); txtMaintainer = new QLabel( tr( "test" ), container ); txtMaintainer->setTextFormat( QLabel::RichText ); layout->addWidget( txtMaintainer, 7, 1 ); QWhatsThis::add( txtMaintainer, tr( "This is the name of the current task maintainer." ) ); tbtMaintainer = new QToolButton( container ); tbtMaintainer->setPixmap( Resource::loadPixmap( "todo/more" ) ); // layout->addWidget( tbtMaintainer, 7, 2 ); QWhatsThis::add( tbtMaintainer, tr( "Click here to select the task maintainer." ) ); #endif } TaskEditorStatus::~TaskEditorStatus() { } void TaskEditorStatus::load( const OPimTodo &todo ) { QDate date = QDate::currentDate(); QString str = TimeString::longDateString( date ); // Status int state = todo.hasState()? todo.state().state() : OPimState::NotStarted; if ( state == OPimState::Undefined ) state = OPimState::NotStarted; cmbStatus->setCurrentItem( state ); // Progress cmbProgress->setCurrentItem( todo.progress() / 20 ); // Start date ckbStart->setChecked( todo.hasStartDate() ); btnStart->setEnabled( todo.hasStartDate() ); if ( todo.hasStartDate() ) { m_start = todo.startDate(); btnStart->setText( TimeString::longDateString( m_start ) ); } else btnStart->setText( str ); // Due date ckbDue->setChecked( todo.hasDueDate() ); btnDue->setText( TimeString::longDateString( todo.dueDate() ) ); btnDue->setEnabled( todo.hasDueDate() ); m_due = todo.dueDate(); // Completed ckbComp->setChecked( todo.isCompleted() ); btnComp->setEnabled( todo.hasCompletedDate() ); if ( todo.hasCompletedDate() ) { m_comp = todo.completedDate(); btnComp->setText( TimeString::longDateString( m_comp ) ); } else btnComp->setText( str ); // Maintainer Mode #if 0 state = todo.hasMaintainer() ? todo.maintainer().mode() : OPimMaintainer::Nothing; if ( state == OPimMaintainer::Undefined ) state = OPimMaintainer::Nothing; cmbMaintMode->setCurrentItem( state ); #endif // Maintainer - not implemented yet } void TaskEditorStatus::save( OPimTodo &todo ) { QDate inval; // Status todo.setState( OPimState( cmbStatus->currentItem() ) ); // Progress todo.setProgress( cmbProgress->currentItem() * 20 ); // Start date if ( ckbStart->isChecked() ) { todo.setStartDate( m_start ); } else todo.setStartDate( inval ); // Due date if ( ckbDue->isChecked() ) { todo.setDueDate( m_due ); todo.setHasDueDate( true ); } else todo.setHasDueDate( false ); // Completed todo.setCompleted( ckbComp->isChecked() ); if ( ckbComp->isChecked() ) { todo.setCompletedDate( m_comp ); } else todo.setCompletedDate( inval ); #if 0 // Maintainer mode - not implemented yet // Maintainer /* TODO - resolve name to uid.....*/ todo.setMaintainer( OPimMaintainer( cmbMaintMode->currentItem(), -10 ) ); #endif } void TaskEditorStatus::slotStartChecked() { btnStart->setEnabled( ckbStart->isChecked() ); } void TaskEditorStatus::slotCompChecked() { btnComp->setEnabled( ckbComp->isChecked() ); } void TaskEditorStatus::slotDueChecked() { btnDue->setEnabled( ckbDue->isChecked() ); } void TaskEditorStatus::slotStartChanged(int y, int m, int d) { m_start.setYMD( y, m, d ); btnStart->setText( TimeString::longDateString( m_start ) ); } void TaskEditorStatus::slotCompChanged(int y, int m, int d) { m_comp.setYMD( y, m, d ); btnComp->setText( TimeString::longDateString( m_comp ) ); } void TaskEditorStatus::slotDueChanged(int y, int m, int d) { m_due.setYMD( y, m, d ); btnDue->setText( TimeString::longDateString( m_due ) ); emit dueDateChanged( m_due ); } diff --git a/core/qws/qcopbridge.cpp b/core/qws/qcopbridge.cpp index c0c52e8..4fd0807 100644 --- a/core/qws/qcopbridge.cpp +++ b/core/qws/qcopbridge.cpp @@ -1,270 +1,270 @@ /********************************************************************** ** Copyright (C) 2000-2002 Trolltech AS. All rights reserved. ** ** This file is part of the Qtopia Environment. ** ** This file may be distributed and/or modified under the terms of the ** GNU General Public License version 2 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. ** ** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE ** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. ** ** See http://www.trolltech.com/gpl/ for GPL licensing information. ** ** Contact info@trolltech.com if any conditions of this licensing are ** not clear to you. ** **********************************************************************/ #include "qcopbridge.h" #include "transferserver.h" #include <qpe/qcopenvelope_qws.h> #include <qpe/qpeapplication.h> #include <qpe/version.h> #include <qtextstream.h> #ifdef QWS #include <qcopchannel_qws.h> #endif #define _XOPEN_SOURCE #include <pwd.h> #include <sys/types.h> #include <unistd.h> #if defined(_OS_LINUX_) #include <shadow.h> #endif //#define INSECURE const int block_size = 51200; QCopBridge::QCopBridge( Q_UINT16 port, QObject *parent , const char* name ) : QServerSocket( port, 1, parent, name ), desktopChannel( 0 ), cardChannel( 0 ) { if ( !ok() ) qWarning( "Failed to bind to port %d", port ); else { #ifndef QT_NO_COP desktopChannel = new QCopChannel( "QPE/Desktop", this ); - connect( desktopChannel, SIGNAL(received(const QCString &, const QByteArray &)), - this, SLOT(desktopMessage( const QCString &, const QByteArray &)) ); + connect( desktopChannel, SIGNAL(received(const QCString&,const QByteArray&)), + this, SLOT(desktopMessage(const QCString&,const QByteArray&)) ); cardChannel = new QCopChannel( "QPE/Card", this ); - connect( cardChannel, SIGNAL(received(const QCString &, const QByteArray &)), - this, SLOT(desktopMessage( const QCString &, const QByteArray &)) ); + connect( cardChannel, SIGNAL(received(const QCString&,const QByteArray&)), + this, SLOT(desktopMessage(const QCString&,const QByteArray&)) ); #endif } sendSync = FALSE; } QCopBridge::~QCopBridge() { #ifndef QT_NO_COP delete desktopChannel; #endif } void QCopBridge::newConnection( int socket ) { QCopBridgePI *pi = new QCopBridgePI( socket, this ); openConnections.append( pi ); - connect ( pi, SIGNAL( connectionClosed( QCopBridgePI *) ), this, SLOT( connectionClosed( QCopBridgePI *) ) ); + connect ( pi, SIGNAL( connectionClosed(QCopBridgePI*) ), this, SLOT( connectionClosed(QCopBridgePI*) ) ); #ifndef QT_NO_COP QCopEnvelope( "QPE/System", "setScreenSaverMode(int)" ) << QPEApplication::DisableSuspend; #endif if ( sendSync ) { pi ->startSync(); sendSync = FALSE; } } void QCopBridge::connectionClosed( QCopBridgePI *pi ) { openConnections.remove( pi ); if ( openConnections.count() == 0 ) { #ifndef QT_NO_COP QCopEnvelope( "QPE/System", "setScreenSaverMode(int)" ) << QPEApplication::Enable; #endif } } void QCopBridge::closeOpenConnections() { QCopBridgePI *pi; for ( pi = openConnections.first(); pi != 0; pi = openConnections.next() ) pi->close(); } void QCopBridge::desktopMessage( const QCString &command, const QByteArray &args ) { command.stripWhiteSpace(); int paren = command.find( "(" ); if ( paren <= 0 ) { qDebug("DesktopMessage: bad qcop syntax"); return; } QString params = command.mid( paren + 1 ); if ( params[params.length()-1] != ')' ) { qDebug("DesktopMessage: bad qcop syntax"); return; } params.truncate( params.length()-1 ); QStringList paramList = QStringList::split( ",", params ); QString data; if ( paramList.count() ) { QDataStream stream( args, IO_ReadOnly ); for ( QStringList::Iterator it = paramList.begin(); it != paramList.end(); ++it ) { QString str; if ( *it == "QString" ) { stream >> str; } else if ( *it == "QCString" ) { QCString cstr; stream >> cstr; str = QString::fromLocal8Bit( cstr ); } else if ( *it == "int" ) { int i; stream >> i; str = QString::number( i ); } else if ( *it == "bool" ) { int i; stream >> i; str = QString::number( i ); } else { qDebug(" cannot route the argument type %s throught the qcop bridge", (*it).latin1() ); return; } QString estr; for (int i=0; i<(int)str.length(); i++) { QChar ch = str[i]; if ( ch.row() ) goto quick; switch (ch.cell()) { case '&': estr.append( "&" ); break; case ' ': estr.append( "&0x20;" ); break; case '\n': estr.append( "&0x0d;" ); break; case '\r': estr.append( "&0x0a;" ); break; default: quick: estr.append(ch); } } data += " " + estr; } } QString sendCommand = QString(command.data()) + data; // send the command to all open connections if ( command == "startSync()" ) { // we need to buffer it a bit sendSync = TRUE; startTimer( 20000 ); } QCopBridgePI *pi; for ( pi = openConnections.first(); pi != 0; pi = openConnections.next() ) { pi->sendDesktopMessage( sendCommand ); } } void QCopBridge::timerEvent( QTimerEvent * ) { sendSync = FALSE; killTimers(); } QCopBridgePI::QCopBridgePI( int socket, QObject *parent , const char* name ) : QSocket( parent, name ) { setSocket( socket ); peerport = peerPort(); peeraddress = peerAddress(); #ifndef INSECURE if ( !SyncAuthentication::isAuthorized(peeraddress) ) { state = Forbidden; startTimer( 0 ); } else #endif { state = Connected; sendSync = FALSE; connect( this, SIGNAL( readyRead() ), SLOT( read() ) ); connect( this, SIGNAL( connectionClosed() ), SLOT( connectionClosed() ) ); QString intro="220 Qtopia "; intro += QPE_VERSION; intro += ";"; intro += "challenge="; intro += SyncAuthentication::serverId(); intro += ";"; intro += "loginname="; intro += SyncAuthentication::loginName(); intro += ";"; intro += "displayname="; intro += SyncAuthentication::ownerName(); intro += ";"; send( intro ); state = Wait_USER; // idle timer to close connections when not used anymore startTimer( 60000 ); connected = TRUE; } } QCopBridgePI::~QCopBridgePI() { } void QCopBridgePI::connectionClosed() { emit connectionClosed( this ); // qDebug( "Debug: Connection closed" ); delete this; } void QCopBridgePI::sendDesktopMessage( const QString &msg ) { QString str = "CALL QPE/Desktop " + msg; send ( str ); } void QCopBridgePI::send( const QString& msg ) { QTextStream os( this ); os << msg << endl; //qDebug( "sending qcop message: %s", msg.latin1() ); } void QCopBridgePI::read() { while ( canReadLine() ) process( readLine().stripWhiteSpace() ); } void QCopBridgePI::process( const QString& message ) { //qDebug( "Command: %s", message.latin1() ); // split message using "," as separator QStringList msg = QStringList::split( " ", message ); if ( msg.isEmpty() ) return; // command token diff --git a/core/qws/transferserver.cpp b/core/qws/transferserver.cpp index 30bf438..daf63ec 100644 --- a/core/qws/transferserver.cpp +++ b/core/qws/transferserver.cpp @@ -105,397 +105,397 @@ QString UidGen::uuid() } #elif defined(_OS_LINUX_) /* * linux got a /proc/sys/kernel/random/uuid file * it'll generate the uuids for us */ QString UidGen::uuid() { QFile file( "/proc/sys/kernel/random/uuid" ); if (!file.open(IO_ReadOnly ) ) return QString::null; QTextStream stream(&file); return "{" + stream.read().stripWhiteSpace() + "}"; } #else QString UidGen::uuid() { uuid_t uuid; ::uuid_generate( uuid ); return QUUid( uuid ).toString(); } #endif } QString SyncAuthentication::serverId() { Config cfg("Security"); cfg.setGroup("Sync"); QString r = cfg.readEntry("serverid"); if ( r.isEmpty() ) { UidGen gen; r = gen.uuid(); cfg.writeEntry("serverid", r ); } return r; } QString SyncAuthentication::ownerName() { QString vfilename = Global::applicationFileName("addressbook", "businesscard.vcf"); if (QFile::exists(vfilename)) { Contact c; c = Contact::readVCard( vfilename )[0]; return c.fullName(); } return ""; } QString SyncAuthentication::loginName() { struct passwd *pw; pw = getpwuid( geteuid() ); return QString::fromLocal8Bit( pw->pw_name ); } int SyncAuthentication::isAuthorized(QHostAddress peeraddress) { Config cfg("Security"); cfg.setGroup("Sync"); // QString allowedstr = cfg.readEntry("auth_peer","192.168.1.0"); uint auth_peer = cfg.readNumEntry("auth_peer", 0xc0a80100); // QHostAddress allowed; // allowed.setAddress(allowedstr); // uint auth_peer = allowed.ip4Addr(); uint auth_peer_bits = cfg.readNumEntry("auth_peer_bits", 24); uint mask = auth_peer_bits >= 32 // shifting by 32 is not defined ? 0xffffffff : (((1 << auth_peer_bits) - 1) << (32 - auth_peer_bits)); return (peeraddress.ip4Addr() & mask) == auth_peer; } bool SyncAuthentication::checkUser( const QString& user ) { if ( user.isEmpty() ) return FALSE; QString euser = loginName(); return user == euser; } bool SyncAuthentication::checkPassword( const QString& password ) { #ifdef ALLOW_UNIX_USER_FTP // First, check system password... struct passwd *pw = 0; struct spwd *spw = 0; pw = getpwuid( geteuid() ); spw = getspnam( pw->pw_name ); QString cpwd = QString::fromLocal8Bit( pw->pw_passwd ); if ( cpwd == "x" && spw ) cpwd = QString::fromLocal8Bit( spw->sp_pwdp ); // Note: some systems use more than crypt for passwords. QString cpassword = QString::fromLocal8Bit( crypt( password.local8Bit(), cpwd.local8Bit() ) ); if ( cpwd == cpassword ) return TRUE; #endif static int lastdenial = 0; static int denials = 0; int now = time(0); // Detect old Qtopia Desktop (no password) if ( password.isEmpty() ) { if ( denials < 1 || now > lastdenial + 600 ) { QMessageBox::warning( 0, tr("Sync Connection"), tr("<p>An unauthorized system is requesting access to this device." "<p>If you are using a version of Qtopia Desktop older than 1.5.1, " "please upgrade."), tr("Deny") ); denials++; lastdenial = now; } return FALSE; } // Second, check sync password... QString pass = password.left(6); /* old QtopiaDesktops are sending * rootme newer versions got a Qtopia * prefixed. Qtopia prefix will suceed * until the sync software syncs up * FIXME */ if ( pass == "rootme" || pass == "Qtopia") { QString cpassword = QString::fromLocal8Bit( crypt( password.mid(8).local8Bit(), "qp" ) ); Config cfg("Security"); cfg.setGroup("Sync"); QString pwds = cfg.readEntry("Passwords"); if ( QStringList::split(QChar(' '), pwds).contains(cpassword) ) return TRUE; // Unrecognized system. Be careful... if ( (denials > 2 && now < lastdenial + 600) || QMessageBox::warning(0, tr("Sync Connection"), tr("<p>An unrecognized system is requesting access to this device." "<p>If you have just initiated a Sync for the first time, this is normal."), tr("Allow"), tr("Deny"), 0, 1, 1 ) == 1 ) { denials++; lastdenial = now; return FALSE; } else { denials = 0; cfg.writeEntry("Passwords", pwds + " " + cpassword); return TRUE; } } return FALSE; } ServerPI::ServerPI( int socket, QObject *parent , const char* name ) : QSocket( parent, name ) , dtp( 0 ), serversocket( 0 ), waitsocket( 0 ) { state = Connected; setSocket( socket ); peerport = peerPort(); peeraddress = peerAddress(); #ifndef INSECURE if ( !SyncAuthentication::isAuthorized(peeraddress) ) { state = Forbidden; startTimer( 0 ); } else #endif { connect( this, SIGNAL( readyRead() ), SLOT( read() ) ); connect( this, SIGNAL( connectionClosed() ), SLOT( connectionClosed() ) ); passiv = FALSE; for ( int i = 0; i < 4; i++ ) wait[i] = FALSE; send( "220 Qtopia " QPE_VERSION " FTP Server" ); state = Wait_USER; dtp = new ServerDTP( this ); connect( dtp, SIGNAL( completed() ), SLOT( dtpCompleted() ) ); connect( dtp, SIGNAL( failed() ), SLOT( dtpFailed() ) ); - connect( dtp, SIGNAL( error( int ) ), SLOT( dtpError( int ) ) ); + connect( dtp, SIGNAL( error(int) ), SLOT( dtpError(int) ) ); directory = QDir::currentDirPath(); static int p = 1024; while ( !serversocket || !serversocket->ok() ) { delete serversocket; serversocket = new ServerSocket( ++p, this ); } - connect( serversocket, SIGNAL( newIncomming( int ) ), - SLOT( newConnection( int ) ) ); + connect( serversocket, SIGNAL( newIncomming(int) ), + SLOT( newConnection(int) ) ); } } ServerPI::~ServerPI() { } void ServerPI::connectionClosed() { // qDebug( "Debug: Connection closed" ); delete this; } void ServerPI::send( const QString& msg ) { QTextStream os( this ); os << msg << endl; //qDebug( "Reply: %s", msg.latin1() ); } void ServerPI::read() { while ( canReadLine() ) process( readLine().stripWhiteSpace() ); } bool ServerPI::checkReadFile( const QString& file ) { QString filename; if ( file[0] != "/" ) filename = directory.path() + "/" + file; else filename = file; QFileInfo fi( filename ); return ( fi.exists() && fi.isReadable() ); } bool ServerPI::checkWriteFile( const QString& file ) { QString filename; if ( file[0] != "/" ) filename = directory.path() + "/" + file; else filename = file; QFileInfo fi( filename ); if ( fi.exists() ) if ( !QFile( filename ).remove() ) return FALSE; return TRUE; } void ServerPI::process( const QString& message ) { //qDebug( "Command: %s", message.latin1() ); // split message using "," as separator QStringList msg = QStringList::split( " ", message ); if ( msg.isEmpty() ) return ; // command token QString cmd = msg[0].upper(); // argument token QString arg; if ( msg.count() >= 2 ) arg = msg[1]; // full argument string QString args; if ( msg.count() >= 2 ) { QStringList copy( msg ); // FIXME: for Qt3 // copy.pop_front() copy.remove( copy.begin() ); args = copy.join( " " ); } //qDebug( "args: %s", args.latin1() ); // we always respond to QUIT, regardless of state if ( cmd == "QUIT" ) { send( "211 Good bye!" ); delete this; return ; } // connected to client if ( Connected == state ) return ; // waiting for user name if ( Wait_USER == state ) { if ( cmd != "USER" || msg.count() < 2 || !SyncAuthentication::checkUser( arg ) ) { send( "530 Please login with USER and PASS" ); return ; } send( "331 User name ok, need password" ); state = Wait_PASS; return ; } // waiting for password if ( Wait_PASS == state ) { if ( cmd != "PASS" || !SyncAuthentication::checkPassword( arg ) ) { send( "530 Please login with USER and PASS" ); return ; } send( "230 User logged in, proceed" ); state = Ready; return ; } // ACCESS CONTROL COMMANDS // account (ACCT) if ( cmd == "ACCT" ) { // even wu-ftp does not support it send( "502 Command not implemented" ); } // change working directory (CWD) else if ( cmd == "CWD" ) { if ( !args.isEmpty() ) { if ( directory.cd( args, TRUE ) ) send( "250 Requested file action okay, completed" ); else send( "550 Requested action not taken" ); } else send( "500 Syntax error, command unrecognized" ); } // change to parent directory (CDUP) else if ( cmd == "CDUP" ) { if ( directory.cdUp() ) send( "250 Requested file action okay, completed" ); else send( "550 Requested action not taken" ); } // structure mount (SMNT) else if ( cmd == "SMNT" ) { // even wu-ftp does not support it send( "502 Command not implemented" ); } // reinitialize (REIN) else if ( cmd == "REIN" ) { // even wu-ftp does not support it send( "502 Command not implemented" ); } // TRANSFER PARAMETER COMMANDS // data port (PORT) else if ( cmd == "PORT" ) { if ( parsePort( arg ) ) send( "200 Command okay" ); else send( "500 Syntax error, command unrecognized" ); } // passive (PASV) else if ( cmd == "PASV" ) { passiv = TRUE; send( "227 Entering Passive Mode (" + address().toString().replace( QRegExp( "\\." ), "," ) + "," + QString::number( ( serversocket->port() ) >> 8 ) + "," + QString::number( ( serversocket->port() ) & 0xFF ) + ")" ); } // representation type (TYPE) else if ( cmd == "TYPE" ) { if ( arg.upper() == "A" || arg.upper() == "I" ) send( "200 Command okay" ); else send( "504 Command not implemented for that parameter" ); } // file structure (STRU) @@ -857,579 +857,579 @@ bool ServerPI::sendList( const QString& arg ) ts << "total " << QString::number( total / 1024 ) << endl; it.toFirst(); while ( ( info = it.current() ) ) { if ( info->fileName() == "." || info->fileName() == ".." ) { ++it; continue; } ts << fileListing( info ) << endl; ++it; } } if ( passiv ) { waitarray = buffer.buffer(); wait[SendByteArray] = TRUE; if ( waitsocket ) newConnection( waitsocket ); } else dtp->sendByteArray( buffer.buffer(), peeraddress, peerport ); return TRUE; } QString ServerPI::fileListing( QFileInfo *info ) { if ( !info ) return QString::null; QString s; // type char if ( info->isDir() ) s += "d"; else if ( info->isSymLink() ) s += "l"; else s += "-"; // permisson string s += permissionString( info ) + " "; // number of hardlinks int subdirs = 1; if ( info->isDir() ) subdirs = 2; // FIXME : this is to slow //if ( info->isDir() ) //subdirs = QDir( info->absFilePath() ).entryList( QDir::Dirs ).count(); s += QString::number( subdirs ).rightJustify( 3, ' ', TRUE ) + " "; // owner s += info->owner().leftJustify( 8, ' ', TRUE ) + " "; // group s += info->group().leftJustify( 8, ' ', TRUE ) + " "; // file size in bytes s += QString::number( info->size() ).rightJustify( 9, ' ', TRUE ) + " "; // last modified date QDate date = info->lastModified().date(); QTime time = info->lastModified().time(); s += date.monthName( date.month() ) + " " + QString::number( date.day() ).rightJustify( 2, ' ', TRUE ) + " " + QString::number( time.hour() ).rightJustify( 2, '0', TRUE ) + ":" + QString::number( time.minute() ).rightJustify( 2, '0', TRUE ) + " "; // file name s += info->fileName(); return s; } QString ServerPI::permissionString( QFileInfo *info ) { if ( !info ) return QString( "---------" ); QString s; // user if ( info->permission( QFileInfo::ReadUser ) ) s += "r"; else s += "-"; if ( info->permission( QFileInfo::WriteUser ) ) s += "w"; else s += "-"; if ( info->permission( QFileInfo::ExeUser ) ) s += "x"; else s += "-"; // group if ( info->permission( QFileInfo::ReadGroup ) ) s += "r"; else s += "-"; if ( info->permission( QFileInfo::WriteGroup ) ) s += "w"; else s += "-"; if ( info->permission( QFileInfo::ExeGroup ) ) s += "x"; else s += "-"; // exec if ( info->permission( QFileInfo::ReadOther ) ) s += "r"; else s += "-"; if ( info->permission( QFileInfo::WriteOther ) ) s += "w"; else s += "-"; if ( info->permission( QFileInfo::ExeOther ) ) s += "x"; else s += "-"; return s; } void ServerPI::newConnection( int socket ) { //qDebug( "New incomming connection" ); if ( !passiv ) return ; if ( wait[SendFile] ) { QStringList targets; if ( backupRestoreGzip( waitfile, targets ) ) dtp->sendGzipFile( waitfile, targets ); else dtp->sendFile( waitfile ); dtp->setSocket( socket ); } else if ( wait[RetrieveFile] ) { qDebug("check retrieve file"); if ( backupRestoreGzip( waitfile ) ) dtp->retrieveGzipFile( waitfile ); else dtp->retrieveFile( waitfile ); dtp->setSocket( socket ); } else if ( wait[SendByteArray] ) { dtp->sendByteArray( waitarray ); dtp->setSocket( socket ); } else if ( wait[RetrieveByteArray] ) { qDebug("retrieve byte array"); dtp->retrieveByteArray(); dtp->setSocket( socket ); } else waitsocket = socket; for ( int i = 0; i < 4; i++ ) wait[i] = FALSE; } QString ServerPI::absFilePath( const QString& file ) { if ( file.isEmpty() ) return file; QString filepath( file ); if ( file[0] != "/" ) filepath = directory.path() + "/" + file; return filepath; } void ServerPI::timerEvent( QTimerEvent * ) { connectionClosed(); } ServerDTP::ServerDTP( QObject *parent, const char* name) : QSocket( parent, name ), mode( Idle ), createTargzProc( 0 ), retrieveTargzProc( 0 ), gzipProc( 0 ) { connect( this, SIGNAL( connected() ), SLOT( connected() ) ); connect( this, SIGNAL( connectionClosed() ), SLOT( connectionClosed() ) ); - connect( this, SIGNAL( bytesWritten( int ) ), SLOT( bytesWritten( int ) ) ); + connect( this, SIGNAL( bytesWritten(int) ), SLOT( bytesWritten(int) ) ); connect( this, SIGNAL( readyRead() ), SLOT( readyRead() ) ); gzipProc = new OProcess( this, "gzipProc" ); createTargzProc = new OProcess( QString("tar"), this, "createTargzProc"); createTargzProc->setWorkingDirectory( QDir::rootDirPath() ); - connect( createTargzProc, SIGNAL( processExited(OProcess *) ), SLOT( targzDone() ) ); + connect( createTargzProc, SIGNAL( processExited(OProcess*) ), SLOT( targzDone() ) ); QStringList args = "tar"; args += "-xv"; retrieveTargzProc = new OProcess( args, this, "retrieveTargzProc" ); retrieveTargzProc->setWorkingDirectory( QDir::rootDirPath() ); - connect( retrieveTargzProc, SIGNAL( processExited(OProcess *) ), + connect( retrieveTargzProc, SIGNAL( processExited(OProcess*) ), SIGNAL( completed() ) ); - connect( retrieveTargzProc, SIGNAL( processExited(OProcess *) ), + connect( retrieveTargzProc, SIGNAL( processExited(OProcess*) ), SLOT( extractTarDone() ) ); } ServerDTP::~ServerDTP() { buf.close(); file.close(); createTargzProc->kill(); } void ServerDTP::extractTarDone() { qDebug("extract done"); #ifndef QT_NO_COP QCopEnvelope e( "QPE/Desktop", "restoreDone(QString)" ); e << file.name(); #endif } void ServerDTP::connected() { // send file mode switch ( mode ) { case SendFile : if ( !file.exists() || !file.open( IO_ReadOnly) ) { emit failed(); mode = Idle; return ; } //qDebug( "Debug: Sending file '%s'", file.name().latin1() ); bytes_written = 0; if ( file.size() == 0 ) { //make sure it doesn't hang on empty files file.close(); emit completed(); mode = Idle; } else { if ( !file.atEnd() ) { QCString s; s.resize( block_size ); int bytes = file.readBlock( s.data(), block_size ); writeBlock( s.data(), bytes ); } } break; case SendGzipFile: if ( createTargzProc->isRunning() ) { // SHOULDN'T GET HERE, BUT DOING A SAFETY CHECK ANYWAY qWarning("Previous tar --gzip process is still running; killing it..."); createTargzProc->kill(); } bytes_written = 0; qDebug("==>start send tar process"); if ( !createTargzProc->start(OProcess::NotifyOnExit, OProcess::Stdout) ) qWarning("Error starting %s or %s", createTargzProc->args()[0].data(), gzipProc->args()[0].data()); break; case SendBuffer: if ( !buf.open( IO_ReadOnly) ) { emit failed(); mode = Idle; return ; } // qDebug( "Debug: Sending byte array" ); bytes_written = 0; while ( !buf.atEnd() ) putch( buf.getch() ); buf.close(); break; case RetrieveFile: // retrieve file mode if ( file.exists() && !file.remove() ) { emit failed(); mode = Idle; return ; } if ( !file.open( IO_WriteOnly) ) { emit failed(); mode = Idle; return ; } // qDebug( "Debug: Retrieving file %s", file.name().latin1() ); break; case RetrieveGzipFile: qDebug("=-> starting tar process to receive .tgz file"); break; case RetrieveBuffer: // retrieve buffer mode if ( !buf.open( IO_WriteOnly) ) { emit failed(); mode = Idle; return ; } // qDebug( "Debug: Retrieving byte array" ); break; case Idle: qDebug("connection established but mode set to Idle; BUG!"); break; } } void ServerDTP::connectionClosed() { //qDebug( "Debug: Data connection closed %ld bytes written", bytes_written ); // send file mode if ( SendFile == mode ) { if ( bytes_written == file.size() ) emit completed(); else emit failed(); } // send buffer mode else if ( SendBuffer == mode ) { if ( bytes_written == buf.size() ) emit completed(); else emit failed(); } // retrieve file mode else if ( RetrieveFile == mode ) { file.close(); emit completed(); } else if ( RetrieveGzipFile == mode ) { qDebug("Done writing ungzip file; closing input"); gzipProc->flushStdin(); gzipProc->closeStdin(); } // retrieve buffer mode else if ( RetrieveBuffer == mode ) { buf.close(); emit completed(); } mode = Idle; } void ServerDTP::bytesWritten( int bytes ) { bytes_written += bytes; // send file mode if ( SendFile == mode ) { if ( bytes_written == file.size() ) { // qDebug( "Debug: Sending complete: %d bytes", file.size() ); file.close(); emit completed(); mode = Idle; } else if ( !file.atEnd() ) { QCString s; s.resize( block_size ); int bytes = file.readBlock( s.data(), block_size ); writeBlock( s.data(), bytes ); } } // send buffer mode if ( SendBuffer == mode ) { if ( bytes_written == buf.size() ) { // qDebug( "Debug: Sending complete: %d bytes", buf.size() ); emit completed(); mode = Idle; } } } void ServerDTP::readyRead() { // retrieve file mode if ( RetrieveFile == mode ) { QCString s; s.resize( bytesAvailable() ); readBlock( s.data(), bytesAvailable() ); file.writeBlock( s.data(), s.size() ); } else if ( RetrieveGzipFile == mode ) { if ( !gzipProc->isRunning() ) gzipProc->start(OProcess::NotifyOnExit, (OProcess::Communication) ( OProcess::Stdin | OProcess::Stdout )); QByteArray s; s.resize( bytesAvailable() ); readBlock( s.data(), bytesAvailable() ); gzipProc->writeStdin( s.data(), s.size() ); qDebug("wrote %d bytes to ungzip ", s.size() ); } // retrieve buffer mode else if ( RetrieveBuffer == mode ) { QCString s; s.resize( bytesAvailable() ); readBlock( s.data(), bytesAvailable() ); buf.writeBlock( s.data(), s.size() ); } } void ServerDTP::writeTargzBlock(OProcess *, char *buffer, int buflen) { writeBlock( buffer, buflen ); qDebug("writeTargzBlock %d", buflen); if ( !createTargzProc->isRunning() ) { qDebug("tar and gzip done"); emit completed(); mode = Idle; - disconnect( gzipProc, SIGNAL( receivedStdout(OProcess *, char *, int ) ), - this, SLOT( writeTargzBlock(OProcess *, char *, int) ) ); + disconnect( gzipProc, SIGNAL( receivedStdout(OProcess*,char*,int) ), + this, SLOT( writeTargzBlock(OProcess*,char*,int) ) ); } } void ServerDTP::targzDone() { //qDebug("targz done"); - disconnect( createTargzProc, SIGNAL( receivedStdout(OProcess *, char *, int) ), - this, SLOT( gzipTarBlock(OProcess *, char *, int) ) ); + disconnect( createTargzProc, SIGNAL( receivedStdout(OProcess*,char*,int) ), + this, SLOT( gzipTarBlock(OProcess*,char*,int) ) ); gzipProc->closeStdin(); } void ServerDTP::gzipTarBlock(OProcess *, char *buffer, int buflen) { //qDebug("gzipTarBlock"); if ( !gzipProc->isRunning() ) { //qDebug("auto start gzip proc"); gzipProc->start(OProcess::NotifyOnExit, (OProcess::Communication) ( OProcess::Stdin | OProcess::Stdout )); } gzipProc->writeStdin( buffer, buflen ); } void ServerDTP::sendFile( const QString fn, const QHostAddress& host, Q_UINT16 port ) { file.setName( fn ); mode = SendFile; connectToHost( host.toString(), port ); } void ServerDTP::sendFile( const QString fn ) { file.setName( fn ); mode = SendFile; } void ServerDTP::sendGzipFile( const QString &fn, const QStringList &archiveTargets, const QHostAddress& host, Q_UINT16 port ) { sendGzipFile( fn, archiveTargets ); connectToHost( host.toString(), port ); } void ServerDTP::sendGzipFile( const QString &fn, const QStringList &archiveTargets ) { mode = SendGzipFile; file.setName( fn ); QStringList args = "tar"; args += "-cv"; args += archiveTargets; qDebug("sendGzipFile %s", args.join(" ").latin1() ); createTargzProc->clearArguments( ); *createTargzProc << args; connect( createTargzProc, - SIGNAL( receivedStdout(OProcess *, char *, int) ), SLOT( gzipTarBlock(OProcess *, char *, int) ) ); + SIGNAL( receivedStdout(OProcess*,char*,int) ), SLOT( gzipTarBlock(OProcess*,char*,int) ) ); gzipProc->clearArguments( ); *gzipProc << "gzip"; - connect( gzipProc, SIGNAL( receivedStdout(OProcess *, char *, int) ), - SLOT( writeTargzBlock(OProcess *, char *, int) ) ); + connect( gzipProc, SIGNAL( receivedStdout(OProcess*,char*,int) ), + SLOT( writeTargzBlock(OProcess*,char*,int) ) ); } void ServerDTP::gunzipDone() { qDebug("gunzipDone"); disconnect( gzipProc, SIGNAL( processExited() ), this, SLOT( gunzipDone() ) ); retrieveTargzProc->closeStdin(); - disconnect( gzipProc, SIGNAL( receivedStdout(OProcess *, char *, int) ), - this, SLOT( tarExtractBlock(OProcess *, char *, int) ) ); + disconnect( gzipProc, SIGNAL( receivedStdout(OProcess*,char*,int) ), + this, SLOT( tarExtractBlock(OProcess*,char*,int) ) ); } void ServerDTP::tarExtractBlock(OProcess *, char *buffer, int buflen) { qDebug("tarExtractBlock"); if ( !retrieveTargzProc->isRunning() ) { qDebug("auto start ungzip proc"); if ( !retrieveTargzProc->start(OProcess::NotifyOnExit, OProcess::Stdin) ) qWarning(" failed to start tar -x process"); } retrieveTargzProc->writeStdin( buffer, buflen ); } void ServerDTP::retrieveFile( const QString fn, const QHostAddress& host, Q_UINT16 port ) { file.setName( fn ); mode = RetrieveFile; connectToHost( host.toString(), port ); } void ServerDTP::retrieveFile( const QString fn ) { file.setName( fn ); mode = RetrieveFile; } void ServerDTP::retrieveGzipFile( const QString &fn ) { qDebug("retrieveGzipFile %s", fn.latin1()); file.setName( fn ); mode = RetrieveGzipFile; gzipProc->clearArguments(); *gzipProc << "gunzip"; connect( gzipProc, SIGNAL( readyReadStdout() ), SLOT( tarExtractBlock() ) ); connect( gzipProc, SIGNAL( processExited() ), SLOT( gunzipDone() ) ); } void ServerDTP::retrieveGzipFile( const QString &fn, const QHostAddress& host, Q_UINT16 port ) { retrieveGzipFile( fn ); connectToHost( host.toString(), port ); } void ServerDTP::sendByteArray( const QByteArray& array, const QHostAddress& host, Q_UINT16 port ) { buf.setBuffer( array ); mode = SendBuffer; connectToHost( host.toString(), port ); } void ServerDTP::sendByteArray( const QByteArray& array ) { buf.setBuffer( array ); mode = SendBuffer; } void ServerDTP::retrieveByteArray( const QHostAddress& host, Q_UINT16 port ) { buf.setBuffer( QByteArray() ); mode = RetrieveBuffer; connectToHost( host.toString(), port ); } void ServerDTP::retrieveByteArray() { buf.setBuffer( QByteArray() ); mode = RetrieveBuffer; } void ServerDTP::setSocket( int socket ) { QSocket::setSocket( socket ); connected(); } diff --git a/core/settings/button/buttonsettings.cpp b/core/settings/button/buttonsettings.cpp index 141e0f6..d80e496 100644 --- a/core/settings/button/buttonsettings.cpp +++ b/core/settings/button/buttonsettings.cpp @@ -1,254 +1,254 @@ /* =. This file is part of the OPIE Project .=l. Copyright (c) 2002 Robert Griebl <sandman@handhelds.org> .>+-= _;:, .> :=|. This file is free software; you can .> <`_, > . <= redistribute it and/or modify it under :`=1 )Y*s>-.-- : the terms of the GNU General Public .="- .-=="i, .._ License as published by the Free Software - . .-<_> .<> Foundation; either version 2 of the License, ._= =} : or (at your option) any later version. .%`+i> _;_. .i_,=:_. -<s. This file 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 General ..}^=.= = ; Public License for more details. ++= -. .` .: : = ...= . :.=- You should have received a copy of the GNU -. .:....=;==+<; General Public License along with this file; -_. . . )=. = see the file COPYING. If not, write to the -- :-=` Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include <qlayout.h> #include <qlabel.h> #include <qtimer.h> #include <opie/odevice.h> #include "buttonsettings.h" #include "buttonutils.h" #include "remapdlg.h" using namespace Opie; struct buttoninfo { const ODeviceButton *m_button; int m_index; OQCopMessage m_pmsg; QLabel *m_picon; QLabel *m_plabel; OQCopMessage m_hmsg; QLabel *m_hicon; QLabel *m_hlabel; bool m_pdirty : 1; bool m_hdirty : 1; }; ButtonSettings::ButtonSettings ( QWidget *parent , const char *name, bool modal, WFlags f ) : QDialog ( 0, "ButtonSettings", false, WStyle_ContextHelp ) { const QValueList <ODeviceButton> &buttons = ODevice::inst ( )-> buttons ( ); (void) ButtonUtils::inst ( ); // initialise setCaption ( tr( "Button Settings" )); QVBoxLayout *toplay = new QVBoxLayout ( this, 3, 3 ); QLabel *l = new QLabel ( tr( "<center>Press or hold the button you want to remap.</center>" ), this ); toplay-> addWidget ( l ); QGridLayout *lay = new QGridLayout ( toplay ); lay-> setMargin ( 0 ); lay-> setColStretch ( 0, 0 ); lay-> setColStretch ( 1, 0 ); lay-> setColStretch ( 2, 0 ); lay-> setColStretch ( 3, 10 ); m_infos. setAutoDelete ( true ); int i = 1; int index = 0; for ( QValueList<ODeviceButton>::ConstIterator it = buttons. begin ( ); it != buttons. end ( ); it++ ) { if ( it != buttons. begin ( )) { QFrame *f = new QFrame ( this ); f-> setFrameStyle ( QFrame::Sunken | QFrame::VLine ); lay-> addMultiCellWidget ( f, i, i, 0, 3 ); i++; } buttoninfo *bi = new buttoninfo ( ); bi-> m_button = &(*it); bi-> m_index = index++; bi-> m_pmsg = (*it). pressedAction ( ); bi-> m_hmsg = (*it). heldAction ( ); bi-> m_pdirty = false; bi-> m_hdirty = false; l = new QLabel ( this ); l-> setPixmap (( *it ). pixmap ( )); lay-> addMultiCellWidget ( l, i, i + 1, 0, 0 ); l = new QLabel ( tr( "Press:" ), this ); lay-> addWidget ( l, i, 1, AlignLeft | AlignBottom ); l = new QLabel ( tr( "Hold:" ), this ); lay-> addWidget ( l, i + 1, 1, AlignLeft | AlignTop ); l = new QLabel ( this ); l-> setFixedSize ( 16, 16 ); lay-> addWidget ( l, i, 2, AlignLeft | AlignBottom ); bi-> m_picon = l; l = new QLabel ( this ); l-> setAlignment ( AlignLeft | AlignVCenter | SingleLine ); lay-> addWidget ( l, i, 3, AlignLeft | AlignBottom ); bi-> m_plabel = l; l = new QLabel ( this ); l-> setFixedSize ( 16, 16 ); lay-> addWidget ( l, i + 1, 2, AlignLeft | AlignTop ); bi-> m_hicon = l; l = new QLabel ( this ); l-> setAlignment ( AlignLeft | AlignVCenter | SingleLine ); lay-> addWidget ( l, i + 1, 3, AlignLeft | AlignTop ); bi-> m_hlabel = l; i += 2; m_infos. append ( bi ); } toplay-> addStretch ( 10 ); m_last_button = 0; m_lock = false; m_timer = new QTimer ( this ); - connect ( m_timer, SIGNAL( timeout ( )), this, SLOT( keyTimeout ( ))); + connect ( m_timer, SIGNAL( timeout()), this, SLOT( keyTimeout())); updateLabels ( ); QPEApplication::grabKeyboard ( ); } ButtonSettings::~ButtonSettings ( ) { QPEApplication::ungrabKeyboard ( ); } void ButtonSettings::updateLabels ( ) { for ( QListIterator <buttoninfo> it ( m_infos ); *it; ++it ) { qCopInfo cip = ButtonUtils::inst ( )-> messageToInfo ((*it)-> m_pmsg ); (*it)-> m_picon-> setPixmap ( cip. m_icon ); (*it)-> m_plabel-> setText ( cip. m_name ); qCopInfo cih = ButtonUtils::inst ( )-> messageToInfo ((*it)-> m_hmsg ); (*it)-> m_hicon-> setPixmap ( cih. m_icon ); (*it)-> m_hlabel-> setText ( cih. m_name ); } } buttoninfo *ButtonSettings::buttonInfoForKeycode ( ushort key ) { for ( QListIterator <buttoninfo> it ( m_infos ); *it; ++it ) { if ((*it)-> m_button-> keycode ( ) == key ) return *it; } return 0; } void ButtonSettings::keyPressEvent ( QKeyEvent *e ) { buttoninfo *bi = buttonInfoForKeycode ( e-> key ( )); if ( bi && !e-> isAutoRepeat ( )) { m_timer-> stop ( ); m_last_button = bi; m_timer-> start ( ODevice::inst ( )-> buttonHoldTime ( ), true ); } else QDialog::keyPressEvent ( e ); } void ButtonSettings::keyReleaseEvent ( QKeyEvent *e ) { buttoninfo *bi = buttonInfoForKeycode ( e-> key ( )); if ( bi && !e-> isAutoRepeat ( ) && m_timer-> isActive ( )) { m_timer-> stop ( ); edit ( bi, false ); } else QDialog::keyReleaseEvent ( e ); } void ButtonSettings::keyTimeout ( ) { if ( m_last_button ) { edit ( m_last_button, true ); m_last_button = false; } } void ButtonSettings::edit ( buttoninfo *bi, bool hold ) { if ( m_lock ) return; m_lock = true; RemapDlg *d = new RemapDlg ( bi-> m_button, hold, this ); if ( QPEApplication::execDialog ( d ) == QDialog::Accepted ) { if ( hold ) { bi-> m_hmsg = d-> message ( ); bi-> m_hdirty = true; } else { bi-> m_pmsg = d-> message ( ); bi-> m_pdirty = true; } updateLabels ( ); } delete d; m_lock = false; } void ButtonSettings::accept ( ) { for ( QListIterator <buttoninfo> it ( m_infos ); *it; ++it ) { buttoninfo *bi = *it; if ( bi-> m_pdirty ) ODevice::inst ( )-> remapPressedAction ( bi-> m_index, bi-> m_pmsg ); if ( bi-> m_hdirty ) ODevice::inst ( )-> remapHeldAction ( bi-> m_index, bi-> m_hmsg ); } QDialog::accept ( ); } void ButtonSettings::done ( int r ) { QDialog::done ( r ); close ( ); } diff --git a/core/settings/button/remapdlg.cpp b/core/settings/button/remapdlg.cpp index 7dabe68..121173a 100644 --- a/core/settings/button/remapdlg.cpp +++ b/core/settings/button/remapdlg.cpp @@ -1,155 +1,155 @@ #include <qlistview.h> #include <qcombobox.h> #include <qtimer.h> #include "remapdlg.h" #include "buttonutils.h" using namespace Opie; class NoSortItem : public QListViewItem { public: NoSortItem ( QListView *lv, uint pos, const QString &str, const QCString &s1 = 0, const QCString &s2 = 0 ) : QListViewItem ( lv, str, s1, s2 ) { m_key = QString ( QChar ( 'a' + pos )); m_def = false; } void setDefault ( bool b ) { m_def = b; } virtual QString key ( int /*column*/, bool /*ascending*/ ) const { return m_key; } virtual void paintCell ( QPainter * p, const QColorGroup & cg, int column, int width, int align ) { if ( m_def ) { QFont f ( listView ( )-> font ( )); f. setBold ( true ); p-> setFont ( f ); } QListViewItem::paintCell ( p, cg, column, width, align ); } private: QString m_key; bool m_def; }; RemapDlg::RemapDlg ( const Opie::ODeviceButton *b, bool hold, QWidget *parent, const char *name ) : RemapDlgBase ( parent, name, true, WStyle_ContextHelp ) { setCaption ( tr( "%1 %2", "(hold|press) buttoname" ). arg( hold ? tr( "Held" ) : tr( "Pressed" )). arg ( b-> userText ( ))); m_current = 0; static const char * const def_channels [] = { "QPE/Application/", "QPE/Launcher", "QPE/System", "QPE/TaskBar", "QPE/", 0 }; w_channel-> insertStrList ((const char **) def_channels ); m_msg = hold ? b-> heldAction ( ) : b-> pressedAction ( ); m_msg_preset = hold ? b-> factoryPresetHeldAction ( ) : b-> factoryPresetPressedAction ( ); m_map_none = new NoSortItem ( w_list, 0, tr( "No mapping" )); m_map_preset = new NoSortItem ( w_list, 1, tr( "Default" ), m_msg_preset. channel ( ), m_msg_preset. message ( )); ((NoSortItem *) m_map_preset )-> setDefault ( true ); if (m_msg. channel ( ) == "ignore") { m_map_custom = new NoSortItem ( w_list, 2, tr( "Custom" ), m_msg_preset. channel ( ), m_msg_preset. message ( )); m_current = m_map_none; } else { m_map_custom = new NoSortItem ( w_list, 2, tr( "Custom" ), m_msg. channel ( ), m_msg. message ( )); m_current = m_map_custom; } QListViewItem *it = new NoSortItem ( w_list, 3, tr( "Actions" )); ButtonUtils::inst ( )-> insertActions ( it ); it-> setOpen ( true ); m_map_show = new NoSortItem ( w_list, 4, tr( "Show" )); w_list-> setCurrentItem ( m_current ); - QTimer::singleShot ( 0, this, SLOT( delayedInit ( ))); + QTimer::singleShot ( 0, this, SLOT( delayedInit())); } RemapDlg::~RemapDlg ( ) { } void RemapDlg::delayedInit ( ) { bool b = w_list-> viewport ( )-> isUpdatesEnabled ( ); w_list-> viewport ( )-> setUpdatesEnabled ( false ); ButtonUtils::inst ( )-> insertAppLnks ( m_map_show ); w_list-> viewport ( )-> setUpdatesEnabled ( b ); m_map_show-> repaint ( ); } void RemapDlg::itemChanged ( QListViewItem *it ) { bool enabled = false; OQCopMessage m; m_current = it; if ( it == m_map_none ) { m_msg = m = OQCopMessage ( "ignore", 0 ); qDebug ("***ignoring"); } else if ( it == m_map_preset ) { m_msg = m = m_msg_preset; qDebug ("***Preset"); } else if ( it && !it-> childCount ( ) ) { qDebug ("***Custom: %s %s ",it-> text ( 1 ). latin1 ( ), it-> text ( 2 ). latin1 ( )); enabled = ( it == m_map_custom ); m_msg = m = OQCopMessage ( it-> text ( 1 ). latin1 ( ), it-> text ( 2 ). latin1 ( )); } w_channel-> setEnabled ( enabled ); w_message-> setEnabled ( enabled ); w_channel-> setEditText ( m. channel ( )); //hack for if user has typed in a message, such as 'suspend()' //so raise() is always present if(m. message ( ) != "raise()") w_message->insertItem("raise()"); w_message-> setEditText ( m. message ( )); } void RemapDlg::textChanged ( const QString &str ) { if ( !m_current ) return; QComboBox *which = (QComboBox *) sender ( ); if ( which == w_channel ) m_current-> setText ( 1, str ); else if ( which == w_message ) m_current-> setText ( 2, str ); } OQCopMessage RemapDlg::message ( ) { //make sure to update message if typed in itemChanged(w_list->currentItem()); return m_msg; } diff --git a/core/settings/citytime/citytime.cpp b/core/settings/citytime/citytime.cpp index e7f0c46..721285d 100644 --- a/core/settings/citytime/citytime.cpp +++ b/core/settings/citytime/citytime.cpp @@ -1,279 +1,279 @@ /********************************************************************** ** Copyright (C) 2000 Trolltech AS. All rights reserved. ** ** This file is part of Qtopia Environment. ** ** This file may be distributed and/or modified under the terms of the ** GNU General Public License version 2 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. ** ** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE ** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. ** ** See http://www.trolltech.com/gpl/ for GPL licensing information. ** ** Contact info@trolltech.com if any conditions of this licensing are ** not clear to you. ** **********************************************************************/ // changes by Maximilian Reiss <harlekin@handhelds.org> #include "zonemap.h" #include "citytime.h" #include <qpe/qpeapplication.h> #include <qpe/config.h> #include <qpe/tzselect.h> #if !defined(QT_NO_COP) #include <qpe/qcopenvelope_qws.h> #endif #include <qlabel.h> #include <qmessagebox.h> #include <qtoolbutton.h> #include <qlayout.h> #include <stdlib.h> CityTime::CityTime( QWidget *parent, const char* name, WFlags fl ) : CityTimeBase( parent, name, fl ), strRealTz(0), bAdded(false) { Config config( "qpe" ); config.setGroup( "Time" ); bWhichClock = config.readBoolEntry( "AMPM", TRUE ); qDebug( QString("%1").arg(bWhichClock) ); frmMap->changeClock( bWhichClock ); char *pEnv; pEnv = NULL; pEnv = getenv("TZ"); if ( pEnv ) strRealTz = pEnv; pEnv = NULL; pEnv = getenv("HOME"); if ( pEnv ) strHome = pEnv; // append the labels to their respective lists... listCities.setAutoDelete( true ); listTimes.setAutoDelete( true ); listCities.append( cmdCity1 ); listCities.append( cmdCity2 ); listCities.append( cmdCity3 ); listTimes.append( lblCTime1 ); listTimes.append( lblCTime2 ); listTimes.append( lblCTime3 ); // kludgy way of getting the screen size so we don't have to depend // on a resize event... QWidget *d = QApplication::desktop(); if ( d->width() < d->height() ) { // append for that 4 down look listCities.append( cmdCity4 ); listCities.append( cmdCity5 ); listCities.append( cmdCity6 ); listTimes.append( lblCTime4 ); listTimes.append( lblCTime5 ); listTimes.append( lblCTime6 ); lblCTime7->hide(); lblCTime8->hide(); lblCTime9->hide(); cmdCity7->hide(); cmdCity8->hide(); cmdCity9->hide(); } else { listCities.append( cmdCity7 ); listCities.append( cmdCity8 ); listCities.append( cmdCity9 ); listTimes.append( lblCTime7 ); listTimes.append( lblCTime8 ); listTimes.append( lblCTime9 ); lblCTime4->hide(); lblCTime5->hide(); lblCTime6->hide(); cmdCity4->hide(); cmdCity5->hide(); cmdCity6->hide(); } selWidget = frmMap->selectionWidget( this ); selWidget->hide(); CityTimeBaseLayout->addWidget( selWidget ); bAdded = true; readInTimes(); changed = FALSE; - QObject::connect( qApp, SIGNAL( clockChanged( bool ) ), - this, SLOT( changeClock( bool ) ) ); + QObject::connect( qApp, SIGNAL( clockChanged(bool) ), + this, SLOT( changeClock(bool) ) ); // now start the timer so we can update the time quickly every second timerEvent( 0 ); } CityTime::~CityTime() { if ( changed ) { Config cfg("CityTime"); cfg.setGroup("TimeZones"); QListIterator<QToolButton> itCity( listCities ); int i; bool realTzWritten = FALSE; for ( i = 0, itCity.toFirst(); i < CITIES; i++, ++itCity ) { if ( !strCityTz[i].isNull() ) { cfg.writeEntry("Zone"+QString::number(i), strCityTz[i]); cfg.writeEntry("ZoneName"+QString::number(i), itCity.current()->text()); if ( strCityTz[i] == strRealTz ) realTzWritten = TRUE; } } if ( realTzWritten ) { cfg.removeEntry("Zone"+QString::number(CITIES)); cfg.removeEntry("ZoneName"+QString::number(CITIES)); } else { cfg.writeEntry("Zone"+QString::number(CITIES), strRealTz); if ( nameRealTz.isEmpty() ) { int i = strRealTz.find( '/' ); nameRealTz = strRealTz.mid( i+1 ); } cfg.writeEntry("ZoneName"+QString::number(CITIES), nameRealTz); } QCopEnvelope ( "QPE/System", "timeZoneListChange()" ); changed = FALSE; } // restore the timezone, just in case we messed with it and // are destroyed at an inoppurtune moment if ( !strRealTz.isNull() ) { // this should be checked, but there is not much that can done at this //point if it fails setenv( "TZ", strRealTz, true ); } } void CityTime::timerEvent( QTimerEvent *e ) { if ( e ) killTimer( timerId ); // change the time again!! showTime(); int ms = 1000 - QTime::currentTime().msec(); timerId = startTimer( ms ); } void CityTime::mousePressEvent( QMouseEvent * ) { // DEBUG enable this to get a look at the zone information DEBUG // frmMap->showZones(); } void CityTime::showTime( void ) { int i; QListIterator<QLabel> itTime(listTimes); // traverse the list... for ( i = 0, itTime.toFirst(); i < CITIES; i++, ++itTime) { if ( !strCityTz[i].isNull() ) { if ( setenv( "TZ", strCityTz[i], true ) == 0 ) { itTime.current()->setText( TimeString::shortTime( bWhichClock ) ); } else { QMessageBox::critical( this, tr( "Time Changing" ), tr( "There was a problem setting timezone %1" ) .arg( QString::number( i + 1 ) ) ); } } } // done playing around... put it all back unsetenv( "TZ" ); if ( !strRealTz.isNull() ) { if ( setenv( "TZ", strRealTz, true ) != 0 ) { QMessageBox::critical( this, tr( "Restore Time Zone" ), tr( "There was a problem setting your timezone." "Your time may be wrong now..." ) ); } } } void CityTime::beginNewTz() { buttonWidget->hide(); frmMap->setFocus(); selWidget->show(); // CityTimeBaseLayout->addWidget( selWidget ); } void CityTime::slotNewTz( const QString & strNewCountry, const QString & strNewCity ) { // determine what to do based on what putton is pressed... QListIterator<QToolButton> itCity(listCities); int i; // go through the list and make adjustments based on which button is on for ( i = 0, itCity.toFirst(); itCity.current(), i < CITIES; i++, ++itCity ) { QToolButton *cmdTmp = itCity.current(); if ( cmdTmp->isOn() ) { strCityTz[i] = strNewCountry + strNewCity; QString s = strNewCity; cmdTmp->setText( s.replace( QRegExp("_"), " " ) ); cmdTmp->toggle(); // we can actually break, since there is only one button // that is ever pressed! changed = TRUE; break; } } showTime(); buttonWidget->show(); selWidget->hide(); } void CityTime::readInTimes( void ) { Config cfg("CityTime"); cfg.setGroup("TimeZones"); QListIterator<QToolButton> itCity( listCities ); int i=0; nameRealTz = QString::null; QString zn; for ( ; i < CITIES ; i++ ) { zn = cfg.readEntry("Zone"+QString::number(i), QString::null); if ( zn.isNull() ) break; QString nm = cfg.readEntry("ZoneName"+QString::number(i)); strCityTz[i] = zn; itCity.current()->setText(nm); if ( zn == strRealTz ) nameRealTz = nm; ++itCity; } if ( i == 0 ) { // write in our own in a shameless self promotion and some humor QStringList list = timezoneDefaults(); int i; QStringList::Iterator it = list.begin(); for ( i = 0, itCity.toFirst(); i < CITIES && itCity.current(); i++, ++itCity ) { strCityTz[i] = *it++; itCity.current()->setText( *it++ ); } } if ( nameRealTz.isEmpty() ) { //remember the current time zone even if we don't have room //to show it. zn = cfg.readEntry("Zone"+QString::number(CITIES), QString::null); if ( zn == strRealTz ) nameRealTz = cfg.readEntry("ZoneName"+QString::number(CITIES)); i++; } } void CityTime::changeClock( bool newClock ) { bWhichClock = newClock; showTime(); } diff --git a/core/settings/citytime/citytimebase.cpp b/core/settings/citytime/citytimebase.cpp index a3483cc..323929b 100644 --- a/core/settings/citytime/citytimebase.cpp +++ b/core/settings/citytime/citytimebase.cpp @@ -41,371 +41,371 @@ CityTimeBase::CityTimeBase( QWidget* parent, const char* name, WFlags ) cmdCity7_font.setBold( TRUE ); cmdCity7->setFont( cmdCity7_font ); cmdCity7->setFocusPolicy( QToolButton::TabFocus ); cmdCity7->setText( tr( "" ) ); cmdCity7->setToggleButton( TRUE ); cmdCity7->setToggleButton( TRUE ); Layout2->addWidget( cmdCity7, 0, 2 ); lblCTime9 = new QLabel( buttonWidget, "lblCTime9" ); lblCTime9->setSizePolicy( QSizePolicy( (QSizePolicy::SizeType)5, (QSizePolicy::SizeType)1, lblCTime9->sizePolicy().hasHeightForWidth() ) ); QFont lblCTime9_font( lblCTime9->font() ); lblCTime9_font.setPointSize( 10 ); lblCTime9->setFont( lblCTime9_font ); lblCTime9->setText( tr( "" ) ); lblCTime9->setAlignment( int( QLabel::AlignVCenter | QLabel::AlignRight ) ); Layout2->addWidget( lblCTime9, 2, 3 ); cmdCity8 = new QToolButton( buttonWidget, "cmdCity8" ); cmdCity8->setSizePolicy( QSizePolicy( (QSizePolicy::SizeType)5, (QSizePolicy::SizeType)1, cmdCity8->sizePolicy().hasHeightForWidth() ) ); QFont cmdCity8_font( cmdCity8->font() ); cmdCity8_font.setBold( TRUE ); cmdCity8->setFont( cmdCity8_font ); cmdCity8->setFocusPolicy( QToolButton::TabFocus ); cmdCity8->setText( tr( "" ) ); cmdCity8->setToggleButton( TRUE ); cmdCity8->setToggleButton( TRUE ); Layout2->addWidget( cmdCity8, 1, 2 ); cmdCity2 = new QToolButton( buttonWidget, "cmdCity2" ); QFont cmdCity2_font( cmdCity2->font() ); cmdCity2_font.setBold( TRUE ); cmdCity2->setFont( cmdCity2_font ); cmdCity2->setFocusPolicy( QToolButton::TabFocus ); cmdCity2->setText( tr( "" ) ); cmdCity2->setToggleButton( TRUE ); cmdCity2->setToggleButton( TRUE ); Layout2->addWidget( cmdCity2, 1, 0 ); lblCTime6 = new QLabel( buttonWidget, "lblCTime6" ); QFont lblCTime6_font( lblCTime6->font() ); lblCTime6_font.setPointSize( 10 ); lblCTime6->setFont( lblCTime6_font ); lblCTime6->setText( tr( "" ) ); lblCTime6->setAlignment( int( QLabel::AlignVCenter | QLabel::AlignRight ) ); Layout2->addWidget( lblCTime6, 5, 1 ); cmdCity6 = new QToolButton( buttonWidget, "cmdCity6" ); cmdCity6->setSizePolicy( QSizePolicy( (QSizePolicy::SizeType)5, (QSizePolicy::SizeType)1, cmdCity6->sizePolicy().hasHeightForWidth() ) ); QFont cmdCity6_font( cmdCity6->font() ); cmdCity6_font.setBold( TRUE ); cmdCity6->setFont( cmdCity6_font ); cmdCity6->setFocusPolicy( QToolButton::TabFocus ); cmdCity6->setText( tr( "" ) ); cmdCity6->setToggleButton( TRUE ); cmdCity6->setToggleButton( TRUE ); Layout2->addWidget( cmdCity6, 5, 0 ); cmdCity4 = new QToolButton( buttonWidget, "cmdCity4" ); cmdCity4->setSizePolicy( QSizePolicy( (QSizePolicy::SizeType)5, (QSizePolicy::SizeType)1, cmdCity4->sizePolicy().hasHeightForWidth() ) ); QFont cmdCity4_font( cmdCity4->font() ); cmdCity4_font.setBold( TRUE ); cmdCity4->setFont( cmdCity4_font ); cmdCity4->setFocusPolicy( QToolButton::TabFocus ); cmdCity4->setText( tr( "" ) ); cmdCity4->setToggleButton( TRUE ); cmdCity4->setToggleButton( TRUE ); Layout2->addWidget( cmdCity4, 3, 0 ); lblCTime5 = new QLabel( buttonWidget, "lblCTime5" ); QFont lblCTime5_font( lblCTime5->font() ); lblCTime5_font.setPointSize( 10 ); lblCTime5->setFont( lblCTime5_font ); lblCTime5->setText( tr( "" ) ); lblCTime5->setAlignment( int( QLabel::AlignVCenter | QLabel::AlignRight ) ); Layout2->addWidget( lblCTime5, 4, 1 ); lblCTime2 = new QLabel( buttonWidget, "lblCTime2" ); lblCTime2->setSizePolicy( QSizePolicy( (QSizePolicy::SizeType)1, (QSizePolicy::SizeType)1, lblCTime2->sizePolicy().hasHeightForWidth() ) ); QFont lblCTime2_font( lblCTime2->font() ); lblCTime2_font.setPointSize( 10 ); lblCTime2->setFont( lblCTime2_font ); lblCTime2->setText( tr( "" ) ); lblCTime2->setAlignment( int( QLabel::AlignVCenter | QLabel::AlignRight ) ); Layout2->addWidget( lblCTime2, 1, 1 ); lblCTime1 = new QLabel( buttonWidget, "lblCTime1" ); lblCTime1->setSizePolicy( QSizePolicy( (QSizePolicy::SizeType)1, (QSizePolicy::SizeType)1, lblCTime1->sizePolicy().hasHeightForWidth() ) ); QFont lblCTime1_font( lblCTime1->font() ); lblCTime1_font.setPointSize( 10 ); lblCTime1->setFont( lblCTime1_font ); lblCTime1->setText( tr( "" ) ); lblCTime1->setAlignment( int( QLabel::AlignVCenter | QLabel::AlignRight ) ); Layout2->addWidget( lblCTime1, 0, 1 ); cmdCity3 = new QToolButton( buttonWidget, "cmdCity3" ); cmdCity3->setSizePolicy( QSizePolicy( (QSizePolicy::SizeType)5, (QSizePolicy::SizeType)1, cmdCity3->sizePolicy().hasHeightForWidth() ) ); QFont cmdCity3_font( cmdCity3->font() ); cmdCity3_font.setBold( TRUE ); cmdCity3->setFont( cmdCity3_font ); cmdCity3->setFocusPolicy( QToolButton::TabFocus ); cmdCity3->setText( tr( "" ) ); cmdCity3->setToggleButton( TRUE ); cmdCity3->setToggleButton( TRUE ); Layout2->addWidget( cmdCity3, 2, 0 ); lblCTime8 = new QLabel( buttonWidget, "lblCTime8" ); lblCTime8->setSizePolicy( QSizePolicy( (QSizePolicy::SizeType)5, (QSizePolicy::SizeType)1, lblCTime8->sizePolicy().hasHeightForWidth() ) ); QFont lblCTime8_font( lblCTime8->font() ); lblCTime8_font.setPointSize( 10 ); lblCTime8->setFont( lblCTime8_font ); lblCTime8->setText( tr( "" ) ); lblCTime8->setAlignment( int( QLabel::AlignVCenter | QLabel::AlignRight ) ); Layout2->addWidget( lblCTime8, 1, 3 ); cmdCity1 = new QToolButton( buttonWidget, "cmdCity1" ); cmdCity1->setSizePolicy( QSizePolicy( (QSizePolicy::SizeType)5, (QSizePolicy::SizeType)1, cmdCity1->sizePolicy().hasHeightForWidth() ) ); QFont cmdCity1_font( cmdCity1->font() ); cmdCity1_font.setBold( TRUE ); cmdCity1->setFont( cmdCity1_font ); cmdCity1->setFocusPolicy( QToolButton::TabFocus ); cmdCity1->setText( tr( "" ) ); cmdCity1->setToggleButton( TRUE ); cmdCity1->setToggleButton( TRUE ); Layout2->addWidget( cmdCity1, 0, 0 ); lblCTime7 = new QLabel( buttonWidget, "lblCTime7" ); lblCTime7->setSizePolicy( QSizePolicy( (QSizePolicy::SizeType)5, (QSizePolicy::SizeType)1, lblCTime7->sizePolicy().hasHeightForWidth() ) ); QFont lblCTime7_font( lblCTime7->font() ); lblCTime7_font.setPointSize( 10 ); lblCTime7->setFont( lblCTime7_font ); lblCTime7->setText( tr( "" ) ); lblCTime7->setAlignment( int( QLabel::AlignVCenter | QLabel::AlignRight ) ); Layout2->addWidget( lblCTime7, 0, 3 ); lblCTime4 = new QLabel( buttonWidget, "lblCTime4" ); QFont lblCTime4_font( lblCTime4->font() ); lblCTime4_font.setPointSize( 10 ); lblCTime4->setFont( lblCTime4_font ); lblCTime4->setText( tr( "" ) ); lblCTime4->setAlignment( int( QLabel::AlignVCenter | QLabel::AlignRight ) ); Layout2->addWidget( lblCTime4, 3, 1 ); cmdCity5 = new QToolButton( buttonWidget, "cmdCity5" ); cmdCity5->setSizePolicy( QSizePolicy( (QSizePolicy::SizeType)5, (QSizePolicy::SizeType)1, cmdCity5->sizePolicy().hasHeightForWidth() ) ); QFont cmdCity5_font( cmdCity5->font() ); cmdCity5_font.setBold( TRUE ); cmdCity5->setFont( cmdCity5_font ); cmdCity5->setFocusPolicy( QToolButton::TabFocus ); cmdCity5->setText( tr( "" ) ); cmdCity5->setToggleButton( TRUE ); cmdCity5->setToggleButton( TRUE ); Layout2->addWidget( cmdCity5, 4, 0 ); lblCTime3 = new QLabel( buttonWidget, "lblCTime3" ); QFont lblCTime3_font( lblCTime3->font() ); lblCTime3_font.setPointSize( 10 ); lblCTime3->setFont( lblCTime3_font ); lblCTime3->setText( tr( "" ) ); lblCTime3->setAlignment( int( QLabel::AlignVCenter | QLabel::AlignRight ) ); Layout2->addWidget( lblCTime3, 2, 1 ); cmdCity9 = new QToolButton( buttonWidget, "cmdCity9" ); cmdCity9->setSizePolicy( QSizePolicy( (QSizePolicy::SizeType)5, (QSizePolicy::SizeType)1, cmdCity9->sizePolicy().hasHeightForWidth() ) ); QFont cmdCity9_font( cmdCity9->font() ); cmdCity9_font.setBold( TRUE ); cmdCity9->setFont( cmdCity9_font ); cmdCity9->setFocusPolicy( QToolButton::TabFocus ); cmdCity9->setText( tr( "" ) ); cmdCity9->setToggleButton( TRUE ); cmdCity9->setToggleButton( TRUE ); Layout2->addWidget( cmdCity9, 2, 2 ); CityTimeBaseLayout->addWidget( buttonWidget ); // signals and slots connections - connect( frmMap, SIGNAL( signalTz(const QString &, const QString &) ), this, SLOT( slotNewTz(const QString &, const QString &) ) ); + connect( frmMap, SIGNAL( signalTz(const QString&,const QString&) ), this, SLOT( slotNewTz(const QString&,const QString&) ) ); connect( cmdCity1, SIGNAL( toggled(bool) ), cmdCity2, SLOT( setDisabled(bool) ) ); connect( cmdCity1, SIGNAL( toggled(bool) ), cmdCity3, SLOT( setDisabled(bool) ) ); connect( cmdCity1, SIGNAL( toggled(bool) ), cmdCity4, SLOT( setDisabled(bool) ) ); connect( cmdCity1, SIGNAL( toggled(bool) ), cmdCity7, SLOT( setDisabled(bool) ) ); connect( cmdCity1, SIGNAL( toggled(bool) ), cmdCity8, SLOT( setDisabled(bool) ) ); connect( cmdCity2, SIGNAL( toggled(bool) ), cmdCity1, SLOT( setDisabled(bool) ) ); connect( cmdCity2, SIGNAL( toggled(bool) ), cmdCity3, SLOT( setDisabled(bool) ) ); connect( cmdCity2, SIGNAL( toggled(bool) ), cmdCity4, SLOT( setDisabled(bool) ) ); connect( cmdCity4, SIGNAL( toggled(bool) ), cmdCity7, SLOT( setDisabled(bool) ) ); connect( cmdCity2, SIGNAL( toggled(bool) ), cmdCity8, SLOT( setDisabled(bool) ) ); connect( cmdCity2, SIGNAL( toggled(bool) ), cmdCity7, SLOT( setDisabled(bool) ) ); connect( cmdCity3, SIGNAL( toggled(bool) ), cmdCity1, SLOT( setDisabled(bool) ) ); connect( cmdCity3, SIGNAL( toggled(bool) ), cmdCity2, SLOT( setDisabled(bool) ) ); connect( cmdCity3, SIGNAL( toggled(bool) ), cmdCity4, SLOT( setDisabled(bool) ) ); connect( cmdCity3, SIGNAL( toggled(bool) ), cmdCity7, SLOT( setDisabled(bool) ) ); connect( cmdCity3, SIGNAL( toggled(bool) ), cmdCity8, SLOT( setDisabled(bool) ) ); connect( cmdCity4, SIGNAL( toggled(bool) ), cmdCity1, SLOT( setDisabled(bool) ) ); connect( cmdCity4, SIGNAL( toggled(bool) ), cmdCity2, SLOT( setDisabled(bool) ) ); connect( cmdCity4, SIGNAL( toggled(bool) ), cmdCity3, SLOT( setDisabled(bool) ) ); connect( cmdCity4, SIGNAL( toggled(bool) ), cmdCity8, SLOT( setDisabled(bool) ) ); connect( cmdCity7, SIGNAL( toggled(bool) ), cmdCity1, SLOT( setDisabled(bool) ) ); connect( cmdCity7, SIGNAL( toggled(bool) ), cmdCity2, SLOT( setDisabled(bool) ) ); connect( cmdCity7, SIGNAL( toggled(bool) ), cmdCity3, SLOT( setDisabled(bool) ) ); connect( cmdCity7, SIGNAL( toggled(bool) ), cmdCity4, SLOT( setDisabled(bool) ) ); connect( cmdCity7, SIGNAL( toggled(bool) ), cmdCity8, SLOT( setDisabled(bool) ) ); connect( cmdCity8, SIGNAL( toggled(bool) ), cmdCity1, SLOT( setDisabled(bool) ) ); connect( cmdCity8, SIGNAL( toggled(bool) ), cmdCity2, SLOT( setDisabled(bool) ) ); connect( cmdCity8, SIGNAL( toggled(bool) ), cmdCity3, SLOT( setDisabled(bool) ) ); connect( cmdCity8, SIGNAL( toggled(bool) ), cmdCity4, SLOT( setDisabled(bool) ) ); connect( cmdCity8, SIGNAL( toggled(bool) ), cmdCity7, SLOT( setDisabled(bool) ) ); connect( cmdCity1, SIGNAL( toggled(bool) ), cmdCity5, SLOT( setDisabled(bool) ) ); connect( cmdCity2, SIGNAL( toggled(bool) ), cmdCity5, SLOT( setDisabled(bool) ) ); connect( cmdCity3, SIGNAL( toggled(bool) ), cmdCity5, SLOT( setDisabled(bool) ) ); connect( cmdCity4, SIGNAL( toggled(bool) ), cmdCity5, SLOT( setDisabled(bool) ) ); connect( cmdCity7, SIGNAL( toggled(bool) ), cmdCity5, SLOT( setDisabled(bool) ) ); connect( cmdCity8, SIGNAL( toggled(bool) ), cmdCity5, SLOT( setDisabled(bool) ) ); connect( cmdCity5, SIGNAL( toggled(bool) ), cmdCity1, SLOT( setDisabled(bool) ) ); connect( cmdCity5, SIGNAL( toggled(bool) ), cmdCity2, SLOT( setDisabled(bool) ) ); connect( cmdCity5, SIGNAL( toggled(bool) ), cmdCity3, SLOT( setDisabled(bool) ) ); connect( cmdCity5, SIGNAL( toggled(bool) ), cmdCity4, SLOT( setDisabled(bool) ) ); connect( cmdCity5, SIGNAL( toggled(bool) ), cmdCity7, SLOT( setDisabled(bool) ) ); connect( cmdCity5, SIGNAL( toggled(bool) ), cmdCity8, SLOT( setDisabled(bool) ) ); connect( cmdCity1, SIGNAL( toggled(bool) ), cmdCity6, SLOT( setDisabled(bool) ) ); connect( cmdCity2, SIGNAL( toggled(bool) ), cmdCity6, SLOT( setDisabled(bool) ) ); connect( cmdCity3, SIGNAL( toggled(bool) ), cmdCity6, SLOT( setDisabled(bool) ) ); connect( cmdCity4, SIGNAL( toggled(bool) ), cmdCity6, SLOT( setDisabled(bool) ) ); connect( cmdCity5, SIGNAL( toggled(bool) ), cmdCity6, SLOT( setDisabled(bool) ) ); connect( cmdCity6, SIGNAL( toggled(bool) ), cmdCity1, SLOT( setDisabled(bool) ) ); connect( cmdCity6, SIGNAL( toggled(bool) ), cmdCity2, SLOT( setDisabled(bool) ) ); connect( cmdCity6, SIGNAL( toggled(bool) ), cmdCity3, SLOT( setDisabled(bool) ) ); connect( cmdCity6, SIGNAL( toggled(bool) ), cmdCity4, SLOT( setDisabled(bool) ) ); connect( cmdCity6, SIGNAL( toggled(bool) ), cmdCity5, SLOT( setDisabled(bool) ) ); connect( cmdCity6, SIGNAL( toggled(bool) ), cmdCity7, SLOT( setDisabled(bool) ) ); connect( cmdCity6, SIGNAL( toggled(bool) ), cmdCity8, SLOT( setDisabled(bool) ) ); connect( cmdCity6, SIGNAL( toggled(bool) ), cmdCity9, SLOT( setDisabled(bool) ) ); connect( cmdCity7, SIGNAL( toggled(bool) ), cmdCity6, SLOT( setDisabled(bool) ) ); connect( cmdCity8, SIGNAL( toggled(bool) ), cmdCity6, SLOT( setDisabled(bool) ) ); connect( cmdCity9, SIGNAL( toggled(bool) ), cmdCity1, SLOT( setDisabled(bool) ) ); connect( cmdCity9, SIGNAL( toggled(bool) ), cmdCity3, SLOT( setDisabled(bool) ) ); connect( cmdCity9, SIGNAL( toggled(bool) ), cmdCity4, SLOT( setDisabled(bool) ) ); connect( cmdCity9, SIGNAL( toggled(bool) ), cmdCity5, SLOT( setDisabled(bool) ) ); connect( cmdCity9, SIGNAL( toggled(bool) ), cmdCity6, SLOT( setDisabled(bool) ) ); connect( cmdCity9, SIGNAL( toggled(bool) ), cmdCity7, SLOT( setDisabled(bool) ) ); connect( cmdCity9, SIGNAL( toggled(bool) ), cmdCity8, SLOT( setDisabled(bool) ) ); connect( cmdCity1, SIGNAL( toggled(bool) ), cmdCity9, SLOT( setDisabled(bool) ) ); connect( cmdCity2, SIGNAL( toggled(bool) ), cmdCity9, SLOT( setDisabled(bool) ) ); connect( cmdCity3, SIGNAL( toggled(bool) ), cmdCity9, SLOT( setDisabled(bool) ) ); connect( cmdCity4, SIGNAL( toggled(bool) ), cmdCity9, SLOT( setDisabled(bool) ) ); connect( cmdCity5, SIGNAL( toggled(bool) ), cmdCity9, SLOT( setDisabled(bool) ) ); connect( cmdCity7, SIGNAL( toggled(bool) ), cmdCity9, SLOT( setDisabled(bool) ) ); connect( cmdCity8, SIGNAL( toggled(bool) ), cmdCity9, SLOT( setDisabled(bool) ) ); connect( cmdCity9, SIGNAL( toggled(bool) ), cmdCity2, SLOT( setDisabled(bool) ) ); connect( cmdCity1, SIGNAL( toggled(bool) ), this, SLOT( beginNewTz() ) ); connect( cmdCity2, SIGNAL( toggled(bool) ), this, SLOT( beginNewTz() ) ); connect( cmdCity7, SIGNAL( toggled(bool) ), this, SLOT( beginNewTz() ) ); connect( cmdCity3, SIGNAL( toggled(bool) ), this, SLOT( beginNewTz() ) ); connect( cmdCity4, SIGNAL( toggled(bool) ), this, SLOT( beginNewTz() ) ); connect( cmdCity5, SIGNAL( toggled(bool) ), this, SLOT( beginNewTz() ) ); connect( cmdCity6, SIGNAL( toggled(bool) ), this, SLOT( beginNewTz() ) ); connect( cmdCity8, SIGNAL( toggled(bool) ), this, SLOT( beginNewTz() ) ); connect( cmdCity9, SIGNAL( toggled(bool) ), this, SLOT( beginNewTz() ) ); // tab order setTabOrder( cmdCity1, cmdCity2 ); setTabOrder( cmdCity2, cmdCity3 ); setTabOrder( cmdCity3, cmdCity4 ); setTabOrder( cmdCity4, cmdCity5 ); setTabOrder( cmdCity5, cmdCity6 ); setTabOrder( cmdCity6, cmdCity7 ); setTabOrder( cmdCity7, cmdCity8 ); setTabOrder( cmdCity8, cmdCity9 ); setTabOrder( cmdCity9, frmMap ); } /* * Destroys the object and frees any allocated resources */ CityTimeBase::~CityTimeBase() { // no need to delete child widgets, Qt does it all for us } /* * Main event handler. Reimplemented to handle application * font changes */ bool CityTimeBase::event( QEvent* ev ) { bool ret = QWidget::event( ev ); if ( ev->type() == QEvent::ApplicationFontChange ) { QFont cmdCity7_font( cmdCity7->font() ); cmdCity7_font.setBold( TRUE ); cmdCity7->setFont( cmdCity7_font ); QFont lblCTime9_font( lblCTime9->font() ); lblCTime9_font.setPointSize( 10 ); lblCTime9->setFont( lblCTime9_font ); QFont cmdCity8_font( cmdCity8->font() ); cmdCity8_font.setBold( TRUE ); cmdCity8->setFont( cmdCity8_font ); QFont cmdCity2_font( cmdCity2->font() ); cmdCity2_font.setBold( TRUE ); cmdCity2->setFont( cmdCity2_font ); QFont lblCTime6_font( lblCTime6->font() ); lblCTime6_font.setPointSize( 10 ); lblCTime6->setFont( lblCTime6_font ); QFont cmdCity6_font( cmdCity6->font() ); cmdCity6_font.setBold( TRUE ); cmdCity6->setFont( cmdCity6_font ); QFont cmdCity4_font( cmdCity4->font() ); cmdCity4_font.setBold( TRUE ); cmdCity4->setFont( cmdCity4_font ); QFont lblCTime5_font( lblCTime5->font() ); lblCTime5_font.setPointSize( 10 ); lblCTime5->setFont( lblCTime5_font ); QFont lblCTime2_font( lblCTime2->font() ); lblCTime2_font.setPointSize( 10 ); lblCTime2->setFont( lblCTime2_font ); QFont lblCTime1_font( lblCTime1->font() ); lblCTime1_font.setPointSize( 10 ); lblCTime1->setFont( lblCTime1_font ); QFont cmdCity3_font( cmdCity3->font() ); cmdCity3_font.setBold( TRUE ); cmdCity3->setFont( cmdCity3_font ); QFont lblCTime8_font( lblCTime8->font() ); lblCTime8_font.setPointSize( 10 ); lblCTime8->setFont( lblCTime8_font ); QFont cmdCity1_font( cmdCity1->font() ); cmdCity1_font.setBold( TRUE ); cmdCity1->setFont( cmdCity1_font ); QFont lblCTime7_font( lblCTime7->font() ); lblCTime7_font.setPointSize( 10 ); lblCTime7->setFont( lblCTime7_font ); QFont lblCTime4_font( lblCTime4->font() ); lblCTime4_font.setPointSize( 10 ); lblCTime4->setFont( lblCTime4_font ); QFont cmdCity5_font( cmdCity5->font() ); cmdCity5_font.setBold( TRUE ); cmdCity5->setFont( cmdCity5_font ); QFont lblCTime3_font( lblCTime3->font() ); lblCTime3_font.setPointSize( 10 ); lblCTime3->setFont( lblCTime3_font ); QFont cmdCity9_font( cmdCity9->font() ); cmdCity9_font.setBold( TRUE ); cmdCity9->setFont( cmdCity9_font ); } return ret; } void CityTimeBase::beginNewTz() { qWarning( "CityTimeBase::beginNewTz(): Not implemented yet!" ); } void CityTimeBase::slotNewTz(const QString &, const QString &) { qWarning( "CityTimeBase::slotNewTz(const QString &, const QString &): Not implemented yet!" ); } diff --git a/core/settings/citytime/zonemap.cpp b/core/settings/citytime/zonemap.cpp index b83da59..b6843d2 100644 --- a/core/settings/citytime/zonemap.cpp +++ b/core/settings/citytime/zonemap.cpp @@ -1,697 +1,697 @@ /********************************************************************** ** Copyright (C) 2000 Trolltech AS. All rights reserved. ** ** This file is part of Qtopia Environment. ** ** This file may be distributed and/or modified under the terms of the ** GNU General Public License version 2 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. ** ** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE ** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. ** ** See http://www.trolltech.com/gpl/ for GPL licensing information. ** ** Contact info@trolltech.com if any conditions of this licensing are ** not clear to you. ** **********************************************************************/ // changes by Maximilian Reiss <harlekin@handhelds.org> #include "sun.h" #include "zonemap.h" #include <qpe/resource.h> #include <qpe/qpeapplication.h> #include <qfile.h> #include <qlabel.h> #include <qmessagebox.h> #include <qtextstream.h> #include <qtimer.h> #include <qtoolbutton.h> #include <qlayout.h> #include <qhbox.h> #include <qlistview.h> #include <qwhatsthis.h> #include <limits.h> // the map file... static const char strZONEINFO[] = "/usr/share/zoneinfo/zone.tab"; static const char strMAP[] = "citytime/simple_grid_400"; // the maximum distance we'll allow the pointer to be away from a city // and still show the city's time static const int iTHRESHOLD = 50000; // The label offset (how far away from pointer) static const int iLABELOFFSET = 8; // the size of the dot to draw, and where to start it static const int iCITYSIZE = 3; const int iCITYOFFSET = 2; // the darkening function static inline void darken( QImage *pImage, int start, int stop, int row ); static void dayNight( QImage *pImage ); ZoneField::ZoneField( const QString& strLine ) { // make a bunch of RegExp's to match the data from the line QRegExp regCoord( "[-+][0-9]+" ); // the latitude QRegExp regCountry( "[A-Za-z]+/" ); // the country (not good enough) QRegExp regCity( "[A-Za-z_-]*" ); // the city int iStart, iStop, iLen, tmp; QString strTmp; // we should be able to assume that the country code is always the first // two chars, so just grap them and let it go... strCountryCode = strLine.left( 2 ); iStart = regCoord.match( strLine, 0, &iLen ); if ( iStart >= 0 ) { strTmp = strLine.mid( iStart, iLen ); tmp = strTmp.toInt(); // okay, there are two versions of the format, make a decision based on // the size... // Oh BTW, we are storing everything in seconds! if ( iLen < 7 ) { _y = tmp / 100; _y *= 60; _y += tmp % 100; _y *= 60; } else { _y = tmp / 10000; _y *= 60; tmp %= 10000; _y += tmp / 100; _y *= 60; tmp %= 100; _y += tmp; } } iStart = regCoord.match( strLine, iStart + iLen, &iLen ); if ( iStart >= 0 ) { strTmp = strLine.mid( iStart, iLen ); tmp = strTmp.toInt(); if ( iLen < 8 ) { _x = tmp / 100; _x *= 60; _x += tmp % 100; _x *= 60; } else { _x = tmp / 10000; _x *= 60; tmp %= 10000; _x += tmp / 100; _x *= 60; tmp %= 100; _x += tmp; } } iStart = regCountry.match( strLine, 0, &iLen ); // help with the shortcoming in 2.x regexp... iStop = strLine.findRev( '/' ); if ( iStart >= 0 ) { iLen = (iStop - iStart) + 1; strCountry = strLine.mid( iStart, iLen ); } // now match the city... iStart = regCity.match( strLine, iStart + iLen, &iLen ); if ( iStart >= 0 ) { strCity = strLine.mid( iStart, iLen ); } } void ZoneField::showStructure( void ) const { qDebug( "Country: %s", strCountry.latin1() ); qDebug( "City: %s", strCity.latin1() ); qDebug( "x: %d", _x ); qDebug( "y: %d\n", _y ); } ZoneMap::ZoneMap( QWidget *parent, const char* name ) : QScrollView( parent, name ), pLast( 0 ), pRepaint( 0 ), ox( 0 ), oy( 0 ), drawableW( -1 ), drawableH( -1 ), bZoom( FALSE ), bIllum( TRUE ), cursor( 0 ) { viewport()->setFocusPolicy( StrongFocus ); // set mouse tracking so we can use the mouse move event zones.setAutoDelete( true ); // get the map loaded // just set the current image to point pixCurr = new QPixmap(); QPixmap pixZoom = Resource::loadPixmap( "mag" ); cmdZoom = new QToolButton( this, "Zoom command" ); cmdZoom->setPixmap( pixZoom ); cmdZoom->setToggleButton( true ); cmdZoom->setSizePolicy( QSizePolicy( (QSizePolicy::SizeType)0, (QSizePolicy::SizeType)0, cmdZoom->sizePolicy().hasHeightForWidth() ) ); cmdZoom->setMaximumSize( cmdZoom->sizeHint() ); // probably don't need this, but just in case... cmdZoom->move( width() - cmdZoom->width(), height() - cmdZoom->height() ); lblCity = new QLabel( tr( "CITY" ), this, "City Label" ); lblCity->setMinimumSize( lblCity->sizeHint() ); lblCity->setFrameStyle( QFrame::Plain | QFrame::Box ); lblCity->setBackgroundColor( yellow ); lblCity->hide(); // A timer to make sure the label gets hidden tHide = new QTimer( this, "Label Timer" ); QObject::connect( tHide, SIGNAL( timeout() ), lblCity, SLOT( hide() ) ); QObject::connect( tHide, SIGNAL( timeout() ), this, SLOT( slotRedraw() ) ); QTimer *tUpdate = new QTimer( this, "Update Timer" ); QObject::connect( tUpdate, SIGNAL( timeout() ), this, SLOT( slotUpdate() ) ); QObject::connect( qApp, SIGNAL( timeChanged() ), this, SLOT( slotUpdate() ) ); - QObject::connect( cmdZoom, SIGNAL( toggled( bool ) ), - this, SLOT( slotZoom( bool ) ) ); - QObject::connect( &norm, SIGNAL( signalNewPoint( const QPoint& ) ), - this, SLOT( slotFindCity( const QPoint& ) ) ); - QObject::connect( qApp, SIGNAL( clockChanged( bool ) ), - this, SLOT( changeClock( bool ) ) ); + QObject::connect( cmdZoom, SIGNAL( toggled(bool) ), + this, SLOT( slotZoom(bool) ) ); + QObject::connect( &norm, SIGNAL( signalNewPoint(const QPoint&) ), + this, SLOT( slotFindCity(const QPoint&) ) ); + QObject::connect( qApp, SIGNAL( clockChanged(bool) ), + this, SLOT( changeClock(bool) ) ); // update the sun's movement every 5 minutes tUpdate->start( 5 * 60 * 1000 ); // May as well read in the timezone information too... readZones(); } ZoneMap::~ZoneMap() { } void ZoneMap::readZones( void ) { QFile fZone( strZONEINFO ); if ( !fZone.open( IO_ReadOnly ) ) { QMessageBox::warning (this, tr( "Unable to Find Timezone Info" ), tr( "<p>Unable to find any timezone information in %1" ) .arg( strZONEINFO )); exit(-1); } else { QTextStream tZone( &fZone ); while ( !tZone.atEnd() ) { QString strLine = tZone.readLine(); // only pass on lines that aren't comments if ( strLine[0] != '#' ) { zones.append( new ZoneField( strLine ) ); } } fZone.close(); } } void ZoneMap::viewportMousePressEvent( QMouseEvent* event ) { // add the mouse event into the normalizer, and get the average, // pass it along slotRedraw(); norm.start(); norm.addEvent( event->pos() ); } void ZoneMap::viewportMouseMoveEvent( QMouseEvent* event ) { norm.addEvent( event->pos() ); } void ZoneMap::viewportMouseReleaseEvent( QMouseEvent* ) { // get the averaged points in case a timeout hasn't occurred, // more for "mouse clicks" norm.stop(); if ( pLast != NULL ) { emit signalTz( pLast->country(), pLast->city() ); pLast = NULL; } tHide->start( 2000, true ); } void ZoneMap::keyPressEvent( QKeyEvent *ke ) { switch ( ke->key() ) { case Key_Left: case Key_Right: case Key_Up: case Key_Down: { tHide->stop(); if ( !cursor ) slotFindCity( QPoint( contentsWidth(), contentsHeight() ) / 2 ); ZoneField *city = findCityNear( cursor, ke->key() ); if ( city ) { cursor = city; int tmpx, tmpy; zoneToWin( cursor->x(), cursor->y(), tmpx, tmpy ); ensureVisible( tmpx, tmpy ); showCity( cursor ); tHide->start( 3000, true ); } } break; case Key_Space: case Key_Enter: case Key_Return: if ( cursor ) { emit signalTz( cursor->country(), cursor->city() ); tHide->start( 0, true ); } break; } } ZoneField *ZoneMap::findCityNear( ZoneField *city, int key ) { ZoneField *pZone; ZoneField *pClosest = 0; long ddist = LONG_MAX; QListIterator<ZoneField> it( zones ); for (; it.current(); ++it) { pZone = it.current(); long dx = (pZone->x() - city->x())/100; long dy = (pZone->y() - city->y())/100; switch ( key ) { case Key_Right: case Key_Left: if ( key == Key_Left ) dx = -dx; if ( dx > 0 ) { long dist = QABS(dy)*4 + dx; if ( dist < ddist ) { ddist = dist; pClosest = pZone; } } break; case Key_Down: case Key_Up: if ( key == Key_Down ) dy = -dy; if ( dy > 0 ) { long dist = QABS(dx)*4 + dy; if ( dist < ddist ) { ddist = dist; pClosest = pZone; } } break; } } return pClosest; } void ZoneMap::slotFindCity( const QPoint &pos ) { lblCity->hide(); // given coordinates on the screen find the closest city and display the // label close to it int tmpx, tmpy, x, y; long lDistance, lClosest; ZoneField *pZone, *pClosest; if ( tHide->isActive() ) { tHide->stop(); } viewportToContents(pos.x(), pos.y(), tmpx, tmpy); winToZone( tmpx, tmpy, x, y ); // Find city alogorithim: start out at an (near) infinite distance away and // then find the closest city, (similar to the Z-buffer technique, I guess) // the only problem is that this is all done with doubles, but I don't know // another way to do it at the moment. Another problem is a linked list is // used obviously something indexed would help QListIterator<ZoneField> it( zones ); pClosest = 0; lClosest = LONG_MAX; for (; it.current(); ++it) { pZone = it.current(); // use the manhattenLength, a good enough of an appoximation here lDistance = QABS( x - pZone->x() ) + QABS( y - pZone->y() ); // first to zero wins! if ( lDistance < lClosest ) { lClosest = lDistance; pClosest = pZone; } } // Okay, we found the closest city, but it might still be too far away. if ( lClosest <= iTHRESHOLD ) { showCity( pClosest ); cursor = pClosest; } } void ZoneMap::showCity( ZoneField *city ) { pLast = city; // we'll use city and country a couple of times, get them to save some // time QString strCity = pLast->city(); QString strCountry = pLast->country(); // Display the time at this location by setting the environment timezone // getting the current time [there] and then swapping back the variable // so no one notices... QString strSave; char *p = getenv( "TZ" ); if ( p ) { strSave = p; } // set the timezone :) setenv( "TZ", strCountry + strCity, true ); lblCity->setText( strCity.replace( QRegExp("_"), " ") + "\n" + TimeString::shortTime( ampm ) ); lblCity->setMinimumSize( lblCity->sizeHint() ); // undue our damage... unsetenv( "TZ" ); if ( p ) setenv( "TZ", strSave, true ); // Now decide where to move the label, x & y can be reused int tmpx, tmpy, x, y; zoneToWin( pLast->x(), pLast->y(), tmpx, tmpy ); contentsToViewport(tmpx, tmpy, x, y); if ( lblCity->width() > drawableW - x ) { // oops... try putting it on the right x = x - lblCity->width() - iLABELOFFSET; } else { // the default... x += iLABELOFFSET; } if ( lblCity->height() > drawableH - y ) { // move it up... y = y - lblCity->height() - iLABELOFFSET; } else if ( y < 0 ) { // the city is actually off the screen... // this only happens on the a zoom when you are near the top, // a quick workaround.. y = iLABELOFFSET; } else { // the default y += iLABELOFFSET; } // draw in the city and the label if ( pRepaint ) { int repx, repy; zoneToWin( pRepaint->x(), pRepaint->y(), repx, repy ); updateContents( repx - iCITYOFFSET, repy - iCITYOFFSET, iCITYSIZE, iCITYSIZE ); } updateContents( tmpx - iCITYOFFSET, tmpy - iCITYOFFSET, iCITYSIZE, iCITYSIZE ); pRepaint = pLast; lblCity->move( x, y ); lblCity->show(); } void ZoneMap::resizeEvent( QResizeEvent *e ) { // keep the zoom button down in the corner QSize _size = e->size(); cmdZoom->move( _size.width() - cmdZoom->width(), _size.height() - cmdZoom->height() ); if ( !bZoom ) { drawableW = width() - 2 * frameWidth(); drawableH = height() - 2 * frameWidth(); makeMap( drawableW, drawableH ); resizeContents( drawableW, drawableH ); } } void ZoneMap::showZones( void ) const { // go through the zones in the list and just display the values... QListIterator<ZoneField> itZone( zones ); for ( itZone.toFirst(); itZone.current(); ++itZone ) { ZoneField *pZone = itZone.current(); pZone->showStructure(); } } QWidget* ZoneMap::selectionWidget( QWidget *parent) { QWidget *returnWidget = new QWidget( parent ); QVBoxLayout *layout = new QVBoxLayout( returnWidget ); QHBox *hBox = new QHBox( returnWidget ); QListView *continentView = new QListView( hBox ); continentView->addColumn( tr("Continent") ); QWhatsThis::add( continentView, tr("Select a continent/country here, then select a city") ); - connect ( continentView, SIGNAL( clicked ( QListViewItem * ) ), this, SLOT( slotGetCities( QListViewItem * ) ) ); + connect ( continentView, SIGNAL( clicked(QListViewItem*) ), this, SLOT( slotGetCities(QListViewItem*) ) ); QStringList continentList; QListIterator<ZoneField> itZone( zones ); for ( itZone.toFirst(); itZone.current(); ++itZone ) { ZoneField *pZone = itZone.current(); if ( continentList.contains( pZone->country() ) == 0 ) { QString name; QListViewItem *item; if ( !(pZone->country().length() > 24) ) { name = pZone->country().left(pZone->country().length()-1 ); } else { name = pZone->country().left( 24 ); } item = new QListViewItem( continentView, name, pZone->country() ); continentList.append( pZone->country() ); } } cityView = new QListView( hBox ); cityView->addColumn( tr("City") ); layout->addWidget( hBox ); return returnWidget; } void ZoneMap::slotGetCities( QListViewItem * contItem) { cityView->clear(); selectedCont = contItem->text( 1 ); QListIterator<ZoneField> itZone( zones ); for ( itZone.toFirst(); itZone.current(); ++itZone ) { ZoneField *pZone = itZone.current(); if ( pZone->country() == contItem->text( 1 ) ) { QListViewItem *item; item = new QListViewItem( cityView, pZone->city() ); - connect ( cityView, SIGNAL( clicked ( QListViewItem* ) ), this, SLOT( slotCitySelected( QListViewItem* ) ) ); + connect ( cityView, SIGNAL( clicked(QListViewItem*) ), this, SLOT( slotCitySelected(QListViewItem*) ) ); } } } void ZoneMap::slotCitySelected( QListViewItem *cityItem ) { if ( cityItem ) { emit signalTz( selectedCont, cityItem->text( 0 ) ); } } void ZoneMap::drawCities( QPainter *p ) { int x, y, j; // draw in the cities // for testing only as when you put it // on the small screen it looks awful and not to mention useless p->setPen( red ); QListIterator<ZoneField> itZone( zones ); for ( itZone.toFirst(), j = 0; itZone.current(); ++itZone, j++ ) { ZoneField *pZone = itZone.current(); zoneToWin( pZone->x(), pZone->y(), x, y ); if ( x > wImg ) x = x - wImg; p->drawRect( x - iCITYOFFSET, y - iCITYOFFSET, iCITYSIZE, iCITYSIZE); } } static void dayNight(QImage *pImage) { // create a mask the functions from sun.h double dJulian, dSunRad, dSunDecl, dSunRadius, dSunLong; int wImage = pImage->width(), hImage = pImage->height(), iStart, iStop, iMid, relw, i; short wtab[ wImage ]; time_t tCurrent; struct tm *pTm; // get the position of the sun bassed on our current time... tCurrent = time( NULL ); pTm = gmtime( &tCurrent ); dJulian = jtime( pTm ); sunpos( dJulian, 0, &dSunRad, &dSunDecl, &dSunRadius, &dSunLong ); // now get the projected illumination projillum( wtab, wImage, hImage, dSunDecl ); relw = wImage - int( wImage * 0.0275 ); // draw the map, keeping in mind that we may go too far off the map... iMid = ( relw * ( 24*60 - pTm->tm_hour * 60 - pTm->tm_min ) ) / ( 24*60 ); for ( i = 0; i < hImage; i++ ) { if ( wtab[i] > 0 ) { iStart = iMid - wtab[i]; iStop = iMid + wtab[i]; if ( iStart < 0 ) { darken( pImage, iStop, wImage + iStart, i ); } else if ( iStop > wImage ) { darken( pImage, iStop - wImage, iStart, i ); } else { darken( pImage, 0, iStart, i ); darken( pImage, iStop, wImage, i ); } } else { darken( pImage, 0, wImage, i ); } } } static inline void darken( QImage *pImage, int start, int stop, int row ) { int colors, j; uchar *p; // assume that the image is similar to the one we have... colors = pImage->numColors() / 2; p = pImage->scanLine( row ); for ( j = start; j <= stop; j++ ) { if ( p[j] < colors ) p[j] += colors; } } void ZoneMap::makeMap( int w, int h ) { QImage imgOrig = Resource::loadImage( strMAP ); if ( imgOrig.isNull() ) { QMessageBox::warning( this, tr( "Couldn't Find Map" ), tr( "<p>Couldn't load map: %1, exiting") .arg( strMAP ) ); exit(-1); } // set up the color table for darkening... imgOrig = imgOrig.convertDepth( 8 ); int numColors = imgOrig.numColors(); // double the colors imgOrig.setNumColors( 2 * numColors ); // darken the new ones... for ( int i = 0; i < numColors; i++ ) { QRgb rgb = imgOrig.color( i ); imgOrig.setColor ( i + numColors, qRgb( 2 * qRed( rgb ) / 3, 2 * qGreen( rgb ) / 3, 2 * qBlue( rgb ) / 3 ) ); } // else go one with making the map... if ( bIllum ) { // do a daylight mask dayNight(&imgOrig); } // redo the width and height wImg = w; hImg = h; ox = ( wImg / 2 ) - int( wImg * 0.0275 ); oy = hImg / 2; pixCurr->convertFromImage( imgOrig.smoothScale(w, h), QPixmap::ThresholdDither ); } void ZoneMap::drawCity( QPainter *p, const ZoneField *pCity ) { int x, y; p->setPen( red ); zoneToWin( pCity->x(), pCity->y(), x, y ); p->drawRect( x - iCITYOFFSET, y - iCITYOFFSET, iCITYSIZE, iCITYSIZE ); } void ZoneMap::drawContents( QPainter *p, int cx, int cy, int cw, int ch ) { // if there is a need to resize, then do it... // get our drawable area drawableW = width() - 2 * frameWidth(); drawableH = height() - 2 * frameWidth(); int pixmapW = pixCurr->width(), pixmapH = pixCurr->height(); if ( !bZoom && ( ( pixmapW != drawableW ) || ( pixmapH != drawableH) ) ) { makeMap( drawableW, drawableH ); } // taken from the scrollview example... int rowheight = pixCurr->height(); int toprow = cy / rowheight; int bottomrow = ( cy + ch + rowheight - 1 ) / rowheight; int colwidth = pixCurr->width(); int leftcol= cx / colwidth; int rightcol= ( cx + cw + colwidth - 1 ) / colwidth; for ( int r = toprow; r <= bottomrow; r++ ) { int py = r * rowheight; for ( int c = leftcol; c <= rightcol; c++ ) { int px = c * colwidth; p->drawPixmap( px, py, *pixCurr ); } } // Draw that city! if ( pLast ) drawCity( p, pLast ); } void ZoneMap::slotZoom( bool setZoom ) { bZoom = setZoom; if ( bZoom ) { makeMap( 2 * wImg , 2 * hImg ); resizeContents( wImg, hImg ); } else { makeMap( drawableW, drawableH ); resizeContents( drawableW, drawableH ); } } void ZoneMap::slotIllum( bool setIllum ) { bIllum = !setIllum; // make the map... makeMap( pixCurr->width(), pixCurr->height() ); updateContents( 0, 0, wImg, hImg ); diff --git a/core/settings/launcher/menusettings.cpp b/core/settings/launcher/menusettings.cpp index dc8e993..2b64c47 100644 --- a/core/settings/launcher/menusettings.cpp +++ b/core/settings/launcher/menusettings.cpp @@ -1,178 +1,178 @@ /* This file is part of the OPIE Project =. Copyright (c) 2002 Trolltech AS <info@trolltech.com> .=l. Copyright (c) 2002 Robert Griebl <sandman@handhelds.org> .>+-= _;:, .> :=|. This file is free software; you can .> <`_, > . <= redistribute it and/or modify it under :`=1 )Y*s>-.-- : the terms of the GNU General Public .="- .-=="i, .._ License as published by the Free Software - . .-<_> .<> Foundation; either version 2 of the License, ._= =} : or (at your option) any later version. .%`+i> _;_. .i_,=:_. -<s. This file 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 General ..}^=.= = ; Public License for more details. ++= -. .` .: : = ...= . :.=- You should have received a copy of the GNU -. .:....=;==+<; General Public License along with this file; -_. . . )=. = see the file COPYING. If not, write to the -- :-=` Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include "menusettings.h" #include <qpe/config.h> #include <qpe/qlibrary.h> #include <qpe/qpeapplication.h> #include <qpe/menuappletinterface.h> #include <qpe/qcopenvelope_qws.h> #include <qdir.h> #include <qlistview.h> #include <qcheckbox.h> #include <qheader.h> #include <qlayout.h> #include <qlabel.h> #include <qwhatsthis.h> #include <stdlib.h> MenuSettings::MenuSettings ( QWidget *parent, const char *name ) : QWidget ( parent, name ) { m_applets_changed = false; QBoxLayout *lay = new QVBoxLayout ( this, 4, 4 ); QLabel *l = new QLabel ( tr( "Load applets in O-Menu:" ), this ); lay-> addWidget ( l ); m_list = new QListView ( this ); m_list-> addColumn ( "foobar" ); m_list-> header ( )-> hide ( ); lay-> addWidget ( m_list ); m_menutabs = new QCheckBox ( tr( "Show Launcher tabs in O-Menu" ), this ); lay-> addWidget ( m_menutabs ); m_menusubpopup = new QCheckBox ( tr( "Show Applications in Subpopups" ), this ); lay-> addWidget ( m_menusubpopup ); QWhatsThis::add ( m_list, tr( "Check the applets that you want to have included in the O-Menu." )); QWhatsThis::add ( m_menutabs, tr( "Adds the contents of the Launcher Tabs as menus in the O-Menu." )); - connect ( m_list, SIGNAL( clicked ( QListViewItem * )), this, SLOT( appletChanged ( ))); + connect ( m_list, SIGNAL( clicked(QListViewItem*)), this, SLOT( appletChanged())); init ( ); } void MenuSettings::init ( ) { Config cfg ( "StartMenu" ); cfg. setGroup ( "Applets" ); QStringList exclude = cfg. readListEntry ( "ExcludeApplets", ',' ); QString path = QPEApplication::qpeDir ( ) + "/plugins/applets"; #ifdef Q_OS_MACX QStringList list = QDir ( path, "lib*.dylib" ). entryList ( ); #else QStringList list = QDir ( path, "lib*.so" ). entryList ( ); #endif /* Q_OS_MACX */ for ( QStringList::Iterator it = list. begin ( ); it != list. end ( ); ++it ) { QString name; QPixmap icon; MenuAppletInterface *iface = 0; QLibrary *lib = new QLibrary ( path + "/" + *it ); lib-> queryInterface ( IID_MenuApplet, (QUnknownInterface**) &iface ); if ( iface ) { QString lang = getenv( "LANG" ); QTranslator *trans = new QTranslator ( qApp ); QString type = (*it). left ((*it). find (".")); QString tfn = QPEApplication::qpeDir ( ) + "/i18n/" + lang + "/" + type + ".qm"; if ( trans-> load ( tfn )) qApp-> installTranslator ( trans ); else delete trans; name = iface-> name ( ); icon = iface-> icon ( ). pixmap ( QIconSet::Small, QIconSet::Normal ); iface-> release ( ); lib-> unload ( ); QCheckListItem *item; item = new QCheckListItem ( m_list, name, QCheckListItem::CheckBox ); if ( !icon. isNull ( )) item-> setPixmap ( 0, icon ); item-> setOn ( exclude. find ( *it ) == exclude. end ( )); m_applets [*it] = item; } else { delete lib; } } cfg. setGroup ( "Menu" ); m_menutabs->setChecked( cfg.readBoolEntry( "LauncherTabs", true ) ); m_menusubpopup->setChecked( cfg.readBoolEntry( "LauncherSubPopup", true ) ); m_menusubpopup->setEnabled( m_menutabs->isChecked() ); - connect( m_menutabs, SIGNAL( stateChanged( int ) ), m_menusubpopup, SLOT( setEnabled( bool ) ) ); + connect( m_menutabs, SIGNAL( stateChanged(int) ), m_menusubpopup, SLOT( setEnabled(bool) ) ); } void MenuSettings::appletChanged() { m_applets_changed = true; } void MenuSettings::accept ( ) { bool apps_changed = false; Config cfg ( "StartMenu" ); cfg. setGroup ( "Applets" ); if ( m_applets_changed ) { QStringList exclude; QMap <QString, QCheckListItem *>::Iterator it; for ( it = m_applets. begin ( ); it != m_applets. end ( ); ++it ) { if ( !(*it)-> isOn ( )) exclude << it. key ( ); } cfg. writeEntry ( "ExcludeApplets", exclude, ',' ); } cfg. writeEntry ( "SafeMode", false ); cfg. setGroup ( "Menu" ); if ( m_menutabs-> isChecked ( ) != cfg. readBoolEntry ( "LauncherTabs", true )) { apps_changed = true; cfg. writeEntry ( "LauncherTabs", m_menutabs-> isChecked ( )); } if ( m_menusubpopup-> isChecked ( ) != cfg. readBoolEntry ( "LauncherSubPopup", true )) { apps_changed = true; cfg. writeEntry ( "LauncherSubPopup", m_menusubpopup-> isChecked ( )); } cfg. write ( ); if ( m_applets_changed ) { QCopEnvelope ( "QPE/TaskBar", "reloadApplets()" ); m_applets_changed = false; } if ( apps_changed ) { // currently use reloadApplets() since reloadApps is now used exclusive for server // to refresh the tabs. But what we want here is also a refresh of the startmenu entries QCopEnvelope ( "QPE/TaskBar", "reloadApps()" ); QCopEnvelope ( "QPE/TaskBar", "reloadApplets()" ); } } diff --git a/core/settings/launcher/tabdialog.cpp b/core/settings/launcher/tabdialog.cpp index f79ad40..c0d1cf2 100644 --- a/core/settings/launcher/tabdialog.cpp +++ b/core/settings/launcher/tabdialog.cpp @@ -130,384 +130,384 @@ public: painter. drawLine ( 0, i*3, width()-1, i*3 ); painter. drawLine ( 0, i*3+1, width()-1, i*3+1 ); painter. setPen ( colorGroup().background().light(105) ); painter. drawLine ( 0, i*3+2, width()-1, i*3+2 ); } painter.end ( ); setBackgroundPixmap ( bg ); break; } case TabConfig::SolidColor: { setBackgroundPixmap ( QPixmap ( )); if ( val. isEmpty ( )) setBackgroundColor ( colorGroup ( ). base ( )); else setBackgroundColor ( val ); break; } case TabConfig::Image: { qDebug( "Loading image: %s", val.latin1() ); QPixmap bg ( Resource::loadPixmap ( "wallpaper/" + val )); if ( bg. isNull ( )) { QImageIO imgio; imgio. setFileName ( val ); QSize ds = qApp-> desktop ( )-> size ( ); QString param ( "Scale( %1, %2, ScaleMin )" ); // No tr imgio. setParameters ( param. arg ( ds. width ( )). arg ( ds. height ( )). latin1 ( )); imgio. read ( ); bg = imgio. image ( ); } setBackgroundPixmap ( bg ); break; } } m_bgtype = t; viewport ( )-> update ( ); } void setTextColor ( const QColor &tc ) { m_textcolor = tc; QColorGroup cg = colorGroup ( ); cg. setColor ( QColorGroup::Text, tc ); setPalette ( QPalette ( cg, cg, cg )); viewport ( )-> update ( ); } void setViewFont ( const QFont &f ) { setFont ( f ); } void setItemTextPos ( ItemTextPos pos ) { calculateGrid ( pos ); QIconView::setItemTextPos( pos ); } void calculateGrid ( ItemTextPos pos ) { int dw = QApplication::desktop ( )-> width ( ); int viewerWidth = dw - style ( ).scrollBarExtent ( ). width ( ); if ( pos == Bottom ) { int cols = 3; if ( viewerWidth <= 200 ) cols = 2; else if ( viewerWidth >= 400 ) cols = viewerWidth/96; setSpacing ( 4 ); setGridX (( viewerWidth - ( cols + 1 ) * spacing ( )) / cols ); setGridY ( fontMetrics ( ). height ( ) * 2 + 24 ); } else { int cols = 2; if ( viewerWidth < 150 ) cols = 1; else if ( viewerWidth >= 400 ) cols = viewerWidth / 150; setSpacing ( 2 ); setGridX (( viewerWidth - ( cols + 1 ) * spacing ( )) / cols ); setGridY ( fontMetrics ( ). height ( ) + 2 ); } } void paletteChange( const QPalette &p ) { static bool excllock = false; if ( excllock ) return; excllock = true; unsetPalette ( ); QIconView::paletteChange ( p ); if ( m_bgtype == TabConfig::Ruled ) setBackgroundType ( TabConfig::Ruled, QString::null ); QColorGroup cg = colorGroup ( ); cg.setColor ( QColorGroup::Text, m_textcolor ); setPalette ( QPalette ( cg, cg, cg )); excllock = false; } void setBackgroundPixmap ( const QPixmap &pm ) { m_bgpix = pm; } void setBackgroundColor ( const QColor &c ) { m_bgcolor = c; } void drawBackground ( QPainter *p, const QRect &r ) { if ( !m_bgpix. isNull ( )) { p-> drawTiledPixmap ( r, m_bgpix, QPoint (( r. x ( ) + contentsX ( )) % m_bgpix. width ( ), ( r. y ( ) + contentsY ( )) % m_bgpix. height ( ))); } else p-> fillRect ( r, m_bgcolor ); } private: QColor m_textcolor; QColor m_bgcolor; QPixmap m_bgpix; TabConfig::BackgroundType m_bgtype; }; TabDialog::TabDialog ( const QPixmap *tabicon, const QString &tabname, TabConfig &tc, QWidget *parent, const char *dname, bool modal, WFlags fl ) : QDialog ( parent, dname, modal, fl | WStyle_ContextHelp ), m_tc ( tc ) { setCaption ( tr( "Edit Tab" )); QVBoxLayout *lay = new QVBoxLayout ( this, 3, 3 ); OTabWidget *tw = new OTabWidget ( this, "tabwidget", OTabWidget::Global, OTabWidget::Bottom ); QWidget *bgtab; tw-> addTab ( bgtab = createBgTab ( tw ), "appearance/color", tr( "Background" )); tw-> addTab ( createFontTab ( tw ), "font", tr( "Font" )); tw-> addTab ( createIconTab ( tw ), "pixmap", tr( "Icons" ) ); tw-> setCurrentTab ( bgtab ); QWidget *sample = new QVBox ( this ); QTabBar *tb = new QTabBar ( sample ); QString name ( tr( "Previewing %1" ). arg ( tabname )); tb-> addTab ( tabicon ? new QTab ( *tabicon, name ) : new QTab ( name )); m_sample = new SampleView ( sample ); lay-> addWidget ( tw, 10 ); lay-> addWidget ( sample, 1 ); m_iconsize-> setButton ( tc. m_view ); iconSizeClicked ( tc. m_view ); //m_iconcolor-> setColor ( QColor ( m_tc. m_text_color )); iconColorClicked ( m_iconcolor-> color ( )); m_bgtype-> setButton ( tc. m_bg_type ); //m_solidcolor-> setColor ( QColor ( tc. m_bg_color )); m_bgimage = tc. m_bg_image; bgTypeClicked ( tc. m_bg_type ); m_fontuse-> setChecked ( tc. m_font_use ); m_fontselect-> setSelectedFont ( QFont ( tc. m_font_family, tc. m_font_size, tc. m_font_weight, tc. m_font_italic )); m_fontselect-> setEnabled ( m_fontuse-> isChecked ( )); fontClicked ( m_fontselect-> selectedFont ( )); QWhatsThis::add ( sample, tr( "This is a rough preview of what the currently selected Tab will look like." )); } TabDialog::~TabDialog ( ) { } QWidget *TabDialog::createFontTab ( QWidget *parent ) { QWidget *tab = new QWidget ( parent, "FontTab" ); QVBoxLayout *vertLayout = new QVBoxLayout ( tab, 3, 3 ); m_fontuse = new QCheckBox ( tr( "Use a custom font" ), tab ); vertLayout-> addWidget ( m_fontuse ); m_fontselect = new OFontSelector ( false, tab, "fontsel" ); vertLayout-> addWidget ( m_fontselect ); - connect ( m_fontuse, SIGNAL( toggled ( bool )), m_fontselect, SLOT( setEnabled ( bool ))); - connect( m_fontselect, SIGNAL( fontSelected ( const QFont & )), - this, SLOT( fontClicked ( const QFont & ))); + connect ( m_fontuse, SIGNAL( toggled(bool)), m_fontselect, SLOT( setEnabled(bool))); + connect( m_fontselect, SIGNAL( fontSelected(const QFont&)), + this, SLOT( fontClicked(const QFont&))); return tab; } QWidget *TabDialog::createBgTab ( QWidget *parent ) { QWidget *tab = new QWidget( parent, "BgTab" ); QVBoxLayout *vertLayout = new QVBoxLayout( tab, 3, 3 ); QGridLayout* gridLayout = new QGridLayout ( vertLayout ); gridLayout-> setColStretch ( 1, 10 ); QLabel* label = new QLabel( tr( "Type:" ), tab ); gridLayout-> addWidget ( label, 0, 0 ); m_bgtype = new QButtonGroup( tab, "buttongroup" ); m_bgtype-> hide ( ); m_bgtype-> setExclusive ( true ); QRadioButton *rb; rb = new QRadioButton( tr( "Ruled" ), tab, "ruled" ); m_bgtype-> insert ( rb, TabConfig::Ruled ); gridLayout-> addWidget( rb, 0, 1 ); QHBoxLayout *hb = new QHBoxLayout ( ); hb-> setSpacing ( 3 ); rb = new QRadioButton( tr( "Solid color" ), tab, "solid" ); m_bgtype-> insert ( rb, TabConfig::SolidColor ); hb-> addWidget ( rb ); hb-> addSpacing ( 10 ); m_solidcolor = new OColorButton ( tab, QColor ( m_tc. m_bg_color ) ); - connect ( m_solidcolor, SIGNAL( colorSelected ( const QColor & )), this, SLOT( bgColorClicked ( const QColor & ))); + connect ( m_solidcolor, SIGNAL( colorSelected(const QColor&)), this, SLOT( bgColorClicked(const QColor&))); hb-> addWidget ( m_solidcolor ); hb-> addStretch ( 10 ); gridLayout-> addLayout ( hb, 1, 1 ); hb = new QHBoxLayout ( ); hb-> setSpacing ( 3 ); rb = new QRadioButton( tr( "Image" ), tab, "image" ); m_bgtype-> insert ( rb, TabConfig::Image ); hb-> addWidget( rb ); hb-> addSpacing ( 10 ); m_imagebrowse = new QPushButton ( tr( "Select..." ), tab ); - connect ( m_imagebrowse, SIGNAL( clicked ( )), this, SLOT( bgImageClicked ( ))); + connect ( m_imagebrowse, SIGNAL( clicked()), this, SLOT( bgImageClicked())); hb-> addWidget ( m_imagebrowse ); hb-> addStretch ( 10 ); gridLayout-> addLayout ( hb, 2, 1 ); QPushButton *p = new QPushButton ( tr( "Default" ), tab ); - connect ( p, SIGNAL( clicked ( )), this, SLOT( bgDefaultClicked ( ))); + connect ( p, SIGNAL( clicked()), this, SLOT( bgDefaultClicked())); gridLayout-> addWidget ( p, 3, 1 ); - connect ( m_bgtype, SIGNAL( clicked ( int )), this, SLOT( bgTypeClicked ( int ))); + connect ( m_bgtype, SIGNAL( clicked(int)), this, SLOT( bgTypeClicked(int))); vertLayout-> addStretch ( 10 ); return tab; } QWidget *TabDialog::createIconTab ( QWidget *parent ) { QWidget *tab = new QWidget( parent, "IconTab" ); QVBoxLayout *vertLayout = new QVBoxLayout( tab, 3, 3 ); QGridLayout* gridLayout = new QGridLayout ( vertLayout ); gridLayout-> setColStretch ( 1, 10 ); QLabel* label = new QLabel( tr( "Size:" ), tab ); gridLayout-> addWidget ( label, 0, 0 ); m_iconsize = new QButtonGroup( tab, "buttongroup" ); m_iconsize-> hide ( ); m_iconsize-> setExclusive ( true ); QRadioButton *rb; rb = new QRadioButton( tr( "Small" ), tab, "iconsmall" ); m_iconsize-> insert ( rb, TabConfig::List ); gridLayout-> addWidget( rb, 0, 1 ); rb = new QRadioButton( tr( "Large" ), tab, "iconlarge" ); m_iconsize-> insert ( rb, TabConfig::Icon ); gridLayout-> addWidget( rb, 1, 1 ); - connect ( m_iconsize, SIGNAL( clicked ( int )), this, SLOT( iconSizeClicked ( int ))); + connect ( m_iconsize, SIGNAL( clicked(int)), this, SLOT( iconSizeClicked(int))); // vertLayout-> addSpacing ( 8 ); // gridLayout = new QGridLayout ( vertLayout ); gridLayout-> addRowSpacing ( 2, 8 ); label = new QLabel ( tr( "Color:" ), tab ); gridLayout-> addWidget ( label, 3, 0 ); m_iconcolor = new OColorButton ( tab, QColor ( m_tc. m_text_color ) ); - connect ( m_iconcolor, SIGNAL( colorSelected ( const QColor & )), this, SLOT( iconColorClicked ( const QColor & ))); + connect ( m_iconcolor, SIGNAL( colorSelected(const QColor&)), this, SLOT( iconColorClicked(const QColor&))); gridLayout-> addWidget ( m_iconcolor, 3, 1, AlignLeft ); vertLayout-> addStretch ( 10 ); return tab; } void TabDialog::iconSizeClicked ( int s ) { m_sample-> setViewMode ((TabConfig::ViewMode) s ); } void TabDialog::fontClicked ( const QFont &f ) { m_sample-> setViewFont ( f ); } void TabDialog::bgTypeClicked ( int t ) { QString s; if ( m_bgtype-> id ( m_bgtype-> selected ( )) != t ) m_bgtype-> setButton ( t ); m_solidcolor-> setEnabled ( t == TabConfig::SolidColor ); m_imagebrowse-> setEnabled ( t == TabConfig::Image ); if ( t == TabConfig::SolidColor ) s = m_solidcolor-> color ( ). name ( ); else if ( t == TabConfig::Image ) s = Resource::findPixmap ( m_bgimage ); m_sample-> setBackgroundType ((TabConfig::BackgroundType) t, s ); } void TabDialog::bgColorClicked ( const QColor & ) { bgTypeClicked ( TabConfig::SolidColor ); } void TabDialog::iconColorClicked ( const QColor &col ) { m_sample-> setTextColor ( col ); } void TabDialog::bgImageClicked ( ) { // ### use OFileSelector here ### // this is just a quick c&p from the old appearance app MimeTypes types; QStringList list; list << "image/*"; types. insert ( "Images", list ); QString file = OFileDialog::getOpenFileName ( 1, "/", QString::null, types ); if ( !file. isEmpty ( )) { m_bgimage = DocLnk ( file ). file ( ); bgTypeClicked ( TabConfig::Image ); } } void TabDialog::bgDefaultClicked ( ) { m_bgimage = "launcher/opie-background"; bgTypeClicked ( TabConfig::Image ); } void TabDialog::accept ( ) { m_tc. m_view = (TabConfig::ViewMode) m_iconsize-> id ( m_iconsize-> selected ( )); m_tc. m_bg_type = (TabConfig::BackgroundType) m_bgtype-> id ( m_bgtype-> selected ( )); m_tc. m_bg_color = m_solidcolor-> color ( ). name ( ); m_tc. m_bg_image = m_bgimage; m_tc. m_text_color = m_iconcolor-> color ( ). name ( ); m_tc. m_font_use = m_fontuse-> isChecked ( ); if ( m_tc. m_font_use ) { QFont f = m_fontselect-> selectedFont ( ); m_tc. m_font_family = f. family ( ); m_tc. m_font_size = f. pointSize ( ); m_tc. m_font_weight = f. weight ( ); m_tc. m_font_italic = f. italic ( ); } QDialog::accept ( ); } diff --git a/core/settings/launcher/tabssettings.cpp b/core/settings/launcher/tabssettings.cpp index 17a1609..e5a7087 100644 --- a/core/settings/launcher/tabssettings.cpp +++ b/core/settings/launcher/tabssettings.cpp @@ -1,269 +1,269 @@ /* =. This file is part of the OPIE Project .=l. Copyright (c) 2002 Robert Griebl <sandman@handhelds.org> .>+-= _;:, .> :=|. This file is free software; you can .> <`_, > . <= redistribute it and/or modify it under :`=1 )Y*s>-.-- : the terms of the GNU General Public .="- .-=="i, .._ License as published by the Free Software - . .-<_> .<> Foundation; either version 2 of the License, ._= =} : or (at your option) any later version. .%`+i> _;_. .i_,=:_. -<s. This file 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 General ..}^=.= = ; Public License for more details. ++= -. .` .: : = ...= . :.=- You should have received a copy of the GNU -. .:....=;==+<; General Public License along with this file; -_. . . )=. = see the file COPYING. If not, write to the -- :-=` Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include "tabssettings.h" #include <qpe/resource.h> #include <qpe/applnk.h> #include <qpe/mimetype.h> #include <qpe/qcopenvelope_qws.h> #include <qpe/config.h> #include <qpe/qpeapplication.h> #include <qlistbox.h> #include <qpushbutton.h> #include <qlayout.h> #include <qlabel.h> #include <qwhatsthis.h> #include <qcheckbox.h> #include "tabdialog.h" #include <stdlib.h> #include <qmessagebox.h> #define GLOBALID ".global." TabsSettings::TabsSettings ( QWidget *parent, const char *name ) : QWidget ( parent, name ) { QGridLayout *lay = new QGridLayout ( this, 0, 0, 4, 4 ); QLabel *l = new QLabel ( tr( "Launcher Tabs:" ), this ); lay-> addMultiCellWidget ( l, 0, 0, 0, 1 ); m_list = new QListBox ( this ); lay-> addMultiCellWidget ( m_list, 1, 4, 0, 0 ); QWhatsThis::add ( m_list, tr( "foobar" )); QPushButton *p1, *p2, *p3; p1 = new QPushButton ( tr( "New" ), this ); lay-> addWidget ( p1, 1, 1 ); - connect ( p1, SIGNAL( clicked ( )), this, SLOT( newClicked ( ))); + connect ( p1, SIGNAL( clicked()), this, SLOT( newClicked())); p2 = new QPushButton ( tr( "Edit" ), this ); lay-> addWidget ( p2, 2, 1 ); - connect ( p2, SIGNAL( clicked ( )), this, SLOT( editClicked ( ))); + connect ( p2, SIGNAL( clicked()), this, SLOT( editClicked())); p3 = new QPushButton ( tr( "Delete" ), this ); lay-> addWidget ( p3, 3, 1 ); - connect ( p3, SIGNAL( clicked ( )), this, SLOT( deleteClicked ( ))); + connect ( p3, SIGNAL( clicked()), this, SLOT( deleteClicked())); lay-> setRowStretch ( 4, 10 ); m_bigbusy = new QCheckBox( tr( "Enable big busy indicator" ), this ); lay-> addMultiCellWidget ( m_bigbusy, 5, 5, 0, 1 ); m_busyani = new QCheckBox ( tr( "Enable animated busy indicator" ), this ); lay-> addMultiCellWidget ( m_busyani, 6, 6, 0, 1 ); p1-> setEnabled ( false ); p3-> setEnabled ( false ); init ( ); QWhatsThis::add ( m_list, tr( "Select the Launcher Tab you want to edit or delete." )); QWhatsThis::add ( p1, tr( "Adds a new Tab to the Launcher." ) + QString ( "<center><br><i>not yet implemented</i><br>Please use the tabmanager</center>." )); QWhatsThis::add ( p2, tr( "Opens a new dialog to customize the select Tab." )); QWhatsThis::add ( p3, tr( "Deletes a Tab from the Launcher." ) + QString ( "<center><br><i>not yet implemented</i><br>Please use the tabmanager</center>." )); QWhatsThis::add ( m_bigbusy, tr( "Activate this, if you want a big busy indicator in the middle of the screen instead of the one in taskbar." )); QWhatsThis::add ( m_busyani, tr( "Activate this, if you want an animatedbusy indicator for starting applications in the Launcher." )); } void TabsSettings::init ( ) { AppLnkSet rootFolder( MimeType::appsFolderName ( )); QStringList types = rootFolder. types ( ); m_list-> insertItem ( tr( "All Tabs" )); m_ids << GLOBALID; for ( QStringList::Iterator it = types. begin ( ); it != types. end ( ); ++it ) { m_list-> insertItem ( rootFolder. typePixmap ( *it ), rootFolder. typeName ( *it )); m_ids << *it; } QImage img ( Resource::loadImage ( "DocsIcon" )); QPixmap pix; pix = img. smoothScale ( AppLnk::smallIconSize ( ), AppLnk::smallIconSize ( )); m_list-> insertItem ( pix, tr( "Documents" )); m_ids += "Documents"; // No tr Config cfg ( "Launcher" ); readTabSettings ( cfg ); cfg. setGroup ( "GUI" ); m_busyani-> setChecked ( cfg. readEntry ( "BusyType" ). lower ( ) == "animated" ); m_bigbusy->setChecked( cfg. readBoolEntry ( "BigBusy" ) ); } void TabsSettings::readTabSettings ( Config &cfg ) { QString grp ( "Tab %1" ); // No tr m_tabs. clear ( ); TabConfig global_def; global_def. m_view = TabConfig::Icon; global_def. m_bg_type = TabConfig::Ruled; global_def. m_bg_image = "launcher/opie-background"; global_def. m_bg_color = colorGroup ( ). color ( QColorGroup::Base ). name ( ); global_def. m_text_color = colorGroup ( ). color ( QColorGroup::Text ). name ( ); global_def. m_font_use = false; global_def. m_font_family = font ( ). family ( ); global_def. m_font_size = font ( ). pointSize ( ); global_def. m_font_weight = 50; global_def. m_font_italic = false; global_def. m_changed = false; for ( QStringList::Iterator it = m_ids. begin ( ); it != m_ids. end ( ); ++it ) { TabConfig tc = ( it != m_ids. begin ( )) ? m_tabs [GLOBALID] : global_def; cfg. setGroup ( grp. arg ( *it )); QString view = cfg. readEntry ( "View" ); if ( view == "Icon" ) // No tr tc. m_view = TabConfig::Icon; if ( view == "List" ) // No tr tc. m_view = TabConfig::List; QString bgType = cfg. readEntry ( "BackgroundType" ); if ( bgType == "Image" ) tc. m_bg_type = TabConfig::Image; else if ( bgType == "SolidColor" ) tc. m_bg_type = TabConfig::SolidColor; else if ( bgType == "Image" ) // No tr tc. m_bg_type = TabConfig::Image; tc. m_bg_image = cfg. readEntry ( "BackgroundImage", tc. m_bg_image ); tc. m_bg_color = cfg. readEntry ( "BackgroundColor", tc. m_bg_color ); tc. m_text_color = cfg. readEntry ( "TextColor", tc. m_text_color ); QStringList f = cfg. readListEntry ( "Font", ',' ); if ( f. count ( ) == 4 ) { tc. m_font_use = true; tc. m_font_family = f [0]; tc. m_font_size = f [1]. toInt ( ); tc. m_font_weight = f [2]. toInt ( ); tc. m_font_italic = ( f [3]. toInt ( )); } m_tabs [*it] = tc; } // if all tabs have the same config, then initialize the GLOBALID tab to these values TabConfig *first = 0; bool same = true; for ( QStringList::Iterator it = m_ids. begin ( ); it != m_ids. end ( ); ++it ) { if ( *it == GLOBALID ) continue; else if ( !first ) first = &m_tabs [*it]; else same &= ( *first == m_tabs [*it] ); } if ( same ) { m_tabs [GLOBALID] = *first; m_tabs [GLOBALID]. m_changed = true; } } void TabsSettings::accept ( ) { Config cfg ( "Launcher" ); // Launcher Tab QString grp ( "Tab %1" ); // No tr for ( QStringList::Iterator it = m_ids. begin ( ); it != m_ids. end ( ); ++it ) { TabConfig &tc = m_tabs [*it]; if ( !tc. m_changed ) continue; cfg. setGroup ( grp. arg ( *it )); switch ( tc. m_view ) { case TabConfig::Icon: cfg.writeEntry ( "View", "Icon" ); break; case TabConfig::List: cfg.writeEntry ( "View", "List" ); break; } QCopEnvelope e ( "QPE/Launcher", "setTabView(QString,int)" ); e << *it << tc. m_view; cfg. writeEntry ( "BackgroundImage", tc. m_bg_image ); cfg. writeEntry ( "BackgroundColor", tc. m_bg_color ); cfg. writeEntry ( "TextColor", tc. m_text_color ); if ( tc. m_font_use ) { QString f = tc. m_font_family + "," + QString::number ( tc. m_font_size ) + "," + QString::number ( tc. m_font_weight ) + "," + ( tc. m_font_italic ? "1" : "0" ); cfg. writeEntry ( "Font", f ); } else cfg. removeEntry ( "Font" ); QCopEnvelope be ( "QPE/Launcher", "setTabBackground(QString,int,QString)" ); switch ( tc. m_bg_type ) { case TabConfig::Ruled: cfg.writeEntry( "BackgroundType", "Ruled" ); be << *it << tc. m_bg_type << QString(""); break; case TabConfig::SolidColor: cfg.writeEntry( "BackgroundType", "SolidColor" ); be << *it << tc. m_bg_type << tc. m_bg_color; break; case TabConfig::Image: cfg.writeEntry( "BackgroundType", "Image" ); be << *it << tc. m_bg_type << tc. m_bg_image; break; } QCopEnvelope te( "QPE/Launcher", "setTextColor(QString,QString)" ); te << *it << tc. m_text_color; QCopEnvelope fe ( "QPE/Launcher", "setFont(QString,QString,int,int,int)" ); fe << *it; fe << ( tc. m_font_use ? tc. m_font_family : QString::null ); fe << tc. m_font_size; fe << tc. m_font_weight; fe << ( tc. m_font_italic ? 1 : 0 ); tc. m_changed = false; } cfg. setGroup ( "GUI" ); QString busytype = QString ( m_busyani-> isChecked ( ) ? "Animated" : "" ); cfg. writeEntry ( "BusyType", busytype ); diff --git a/core/settings/launcher/taskbarsettings.cpp b/core/settings/launcher/taskbarsettings.cpp index badb98f..43886c9 100644 --- a/core/settings/launcher/taskbarsettings.cpp +++ b/core/settings/launcher/taskbarsettings.cpp @@ -1,172 +1,172 @@ /* This file is part of the OPIE Project =. Copyright (c) 2002 Trolltech AS <info@trolltech.com> .=l. Copyright (c) 2002 Robert Griebl <sandman@handhelds.org> .>+-= _;:, .> :=|. This file is free software; you can .> <`_, > . <= redistribute it and/or modify it under :`=1 )Y*s>-.-- : the terms of the GNU General Public .="- .-=="i, .._ License as published by the Free Software - . .-<_> .<> Foundation; either version 2 of the License, ._= =} : or (at your option) any later version. .%`+i> _;_. .i_,=:_. -<s. This file 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 General ..}^=.= = ; Public License for more details. ++= -. .` .: : = ...= . :.=- You should have received a copy of the GNU -. .:....=;==+<; General Public License along with this file; -_. . . )=. = see the file COPYING. If not, write to the -- :-=` Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include "taskbarsettings.h" #include <qpe/config.h> #include <qpe/qlibrary.h> #include <qpe/qpeapplication.h> #include <qpe/taskbarappletinterface.h> #include <qpe/qcopenvelope_qws.h> #include <qdir.h> #include <qlistview.h> #include <qheader.h> #include <qlayout.h> #include <qlabel.h> #include <qwhatsthis.h> #include <stdlib.h> TaskbarSettings::TaskbarSettings ( QWidget *parent, const char *name ) : QWidget ( parent, name ) { m_applets_changed = false; QBoxLayout *lay = new QVBoxLayout ( this, 4, 4 ); QLabel *l = new QLabel ( tr( "Load applets in Taskbar:" ), this ); lay-> addWidget ( l ); m_list = new QListView ( this ); m_list-> addColumn ( "foobar" ); m_list-> header ( )-> hide ( ); lay-> addWidget ( m_list ); QWhatsThis::add ( m_list, tr( "Check the applets that you want displayed in the Taskbar." )); - connect ( m_list, SIGNAL( clicked ( QListViewItem * )), this, SLOT( appletChanged ( ))); + connect ( m_list, SIGNAL( clicked(QListViewItem*)), this, SLOT( appletChanged())); init ( ); } void TaskbarSettings::init ( ) { Config cfg ( "Taskbar" ); cfg. setGroup ( "Applets" ); QStringList exclude = cfg. readListEntry ( "ExcludeApplets", ',' ); QString path = QPEApplication::qpeDir ( ) + "/plugins/applets"; #ifdef Q_OS_MACX QStringList list = QDir ( path, "lib*.dylib" ). entryList ( ); #else QStringList list = QDir ( path, "lib*.so" ). entryList ( ); #endif /* Q_OS_MACX */ for ( QStringList::Iterator it = list. begin ( ); it != list. end ( ); ++it ) { QString name; QPixmap icon; TaskbarNamedAppletInterface *iface = 0; qWarning("Load applet: %s", (*it).latin1() ); QLibrary *lib = new QLibrary ( path + "/" + *it ); lib-> queryInterface ( IID_TaskbarNamedApplet, (QUnknownInterface**) &iface ); qWarning("<1>"); if ( iface ) { qWarning("<2>"); QString lang = getenv( "LANG" ); QTranslator *trans = new QTranslator ( qApp ); QString type = (*it). left ((*it). find (".")); QString tfn = QPEApplication::qpeDir ( ) + "/i18n/" + lang + "/" + type + ".qm"; if ( trans-> load ( tfn )) qApp-> installTranslator ( trans ); else delete trans; name = iface-> name ( ); icon = iface-> icon ( ); iface-> release ( ); } qWarning("<3>"); if ( !iface ) { qWarning("<4>"); lib-> queryInterface ( IID_TaskbarApplet, (QUnknownInterface**) &iface ); if ( iface ) { qWarning("<5>"); name = (*it). mid ( 3 ); qWarning("Found applet: %s", name.latin1() ); #ifdef Q_OS_MACX int sep = name. find( ".dylib" ); #else int sep = name. find( ".so" ); #endif /* Q_OS_MACX */ if ( sep > 0 ) name. truncate ( sep ); sep = name. find ( "applet" ); if ( sep == (int) name.length ( ) - 6 ) name. truncate ( sep ); name[0] = name[0]. upper ( ); iface-> release ( ); } } qWarning("<6>"); if ( iface ) { qWarning("<7>"); QCheckListItem *item; item = new QCheckListItem ( m_list, name, QCheckListItem::CheckBox ); if ( !icon. isNull ( )) item-> setPixmap ( 0, icon ); item-> setOn ( exclude. find ( *it ) == exclude. end ( )); m_applets [*it] = item; } lib-> unload ( ); delete lib; } } void TaskbarSettings::appletChanged() { m_applets_changed = true; } void TaskbarSettings::accept ( ) { Config cfg ( "Taskbar" ); cfg. setGroup ( "Applets" ); if ( m_applets_changed ) { QStringList exclude; QMap <QString, QCheckListItem *>::Iterator it; for ( it = m_applets. begin ( ); it != m_applets. end ( ); ++it ) { if ( !(*it)-> isOn ( )) exclude << it. key ( ); } cfg. writeEntry ( "ExcludeApplets", exclude, ',' ); } cfg. writeEntry ( "SafeMode", false ); cfg. write ( ); if ( m_applets_changed ) { QCopEnvelope e ( "QPE/TaskBar", "reloadApplets()" ); m_applets_changed = false; } } diff --git a/core/settings/light-and-power/light.cpp b/core/settings/light-and-power/light.cpp index 4baff8e..ce45836 100644 --- a/core/settings/light-and-power/light.cpp +++ b/core/settings/light-and-power/light.cpp @@ -1,313 +1,313 @@ /* This file is part of the OPIE Project =. Copyright (c) 2002 Maximilian Reiss <harlekin@handhelds.org> .=l. Copyright (c) 2002 Robert Griebl <sandman@handhelds.org> .>+-= _;:, .> :=|. This file is free software; you can .> <`_, > . <= redistribute it and/or modify it under :`=1 )Y*s>-.-- : the terms of the GNU General Public .="- .-=="i, .._ License as published by the Free Software - . .-<_> .<> Foundation; either version 2 of the License, ._= =} : or (at your option) any later version. .%`+i> _;_. .i_,=:_. -<s. This file 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 General ..}^=.= = ; Public License for more details. ++= -. .` .: : = ...= . :.=- You should have received a copy of the GNU -. .:....=;==+<; General Public License along with this file; -_. . . )=. = see the file COPYING. If not, write to the -- :-=` Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include "light.h" #include <qpe/config.h> #include <qpe/power.h> #if defined(Q_WS_QWS) && !defined(QT_NO_COP) #include <qpe/qcopenvelope_qws.h> #endif #include <qlabel.h> #include <qcheckbox.h> #include <qtabwidget.h> #include <qslider.h> #include <qspinbox.h> #include <qpushbutton.h> #include <qgroupbox.h> #include <qcombobox.h> #include <opie/odevice.h> #include "sensor.h" using namespace Opie; LightSettings::LightSettings( QWidget* parent, const char* name, WFlags ) : LightSettingsBase( parent, name, false, WStyle_ContextHelp ) { m_bres = ODevice::inst ( )-> displayBrightnessResolution ( ); m_cres = ODevice::inst ( )-> displayContrastResolution ( ); // check whether to show the light sensor stuff if ( !ODevice::inst ( )-> hasLightSensor ( )) { auto_brightness-> hide ( ); CalibrateLightSensor-> hide ( ); auto_brightness_ac-> hide ( ); CalibrateLightSensor_ac-> hide ( ); } // check whether to show the contrast stuff if (m_cres) { GroupLight->setTitle(tr("Backlight && Contrast")); GroupLight_ac->setTitle(GroupLight->title()); } else { contrast->hide(); contrast_ac->hide(); } // check whether to show the cpu frequency stuff QStrList freq = ODevice::inst()->allowedCpuFrequencies(); if ( freq.count() ) { frequency->insertStrList( freq ); frequency_ac->insertStrList( freq ); } else { frequencyLabel->hide(); frequency->hide(); frequencyLabel_ac->hide(); frequency_ac->hide(); } // check whether to show the hinge action stuff if ( !ODevice::inst()->hasHingeSensor() ) { closeHingeLabel->hide(); closeHingeAction->hide(); closeHingeLabel_ac->hide(); closeHingeAction_ac->hide(); } Config config ( "apm" ); config. setGroup ( "Battery" ); // battery spinboxes interval_dim-> setValue ( config. readNumEntry ( "Dim", 30 )); interval_lightoff-> setValue ( config. readNumEntry ( "LightOff", 20 )); interval_suspend-> setValue ( config. readNumEntry ( "Suspend", 60 )); // battery check and slider LcdOffOnly->setChecked ( config. readBoolEntry ( "LcdOffOnly", false )); // CPU frequency frequency->setCurrentItem( config.readNumEntry("Freq", 0) ); // hinge action closeHingeAction->setCurrentItem( config.readNumEntry("CloseHingeAction", 0) ); int bright = config. readNumEntry ( "Brightness", 127 ); int contr = m_oldcontrast = config. readNumEntry ( "Contrast", 127 ); brightness-> setTickInterval ( QMAX( 16, 256 / m_bres )); brightness-> setLineStep ( QMAX( 1, 256 / m_bres )); brightness-> setPageStep ( QMAX( 1, 256 / m_bres )); brightness-> setValue ( bright ); if (m_cres) { contrast-> setTickInterval ( QMAX( 16, 256 / m_cres )); contrast-> setLineStep ( QMAX( 1, 256 / m_cres )); contrast-> setPageStep ( QMAX( 1, 256 / m_cres )); contrast-> setValue ( contr ); } // light sensor auto_brightness-> setChecked ( config. readBoolEntry ( "LightSensor", false )); m_sensordata = config. readListEntry ( "LightSensorData", ';' ); config. setGroup ( "AC" ); // ac spinboxes interval_dim_ac-> setValue ( config. readNumEntry ( "Dim", 60 )); interval_lightoff_ac-> setValue ( config. readNumEntry ( "LightOff", 120 )); interval_suspend_ac-> setValue ( config. readNumEntry ( "Suspend", 0 )); // ac check and slider LcdOffOnly_ac-> setChecked ( config. readBoolEntry ( "LcdOffOnly", false )); // CPU frequency frequency_ac->setCurrentItem( config.readNumEntry("Freq", 0) ); // hinge action closeHingeAction_ac->setCurrentItem( config.readNumEntry("CloseHingeAction", 0) ); bright = config. readNumEntry ( "Brightness", 255 ); brightness_ac-> setTickInterval ( QMAX( 16, 256 / m_bres )); brightness_ac-> setLineStep ( QMAX( 1, 256 / m_bres )); brightness_ac-> setPageStep ( QMAX( 1, 256 / m_bres )); brightness_ac-> setValue ( bright ); if (m_cres) { contr = config. readNumEntry ( "Contrast", 127); contrast_ac-> setTickInterval ( QMAX( 16, 256 / m_cres )); contrast_ac-> setLineStep ( QMAX( 1, 256 / m_cres )); contrast_ac-> setPageStep ( QMAX( 1, 256 / m_cres )); contrast_ac-> setValue ( contr ); } // light sensor auto_brightness_ac-> setChecked ( config. readBoolEntry ( "LightSensor", false )); m_sensordata_ac = config. readListEntry ( "LightSensorData", ';' ); // warnings config. setGroup ( "Warnings" ); warnintervalBox-> setValue ( config. readNumEntry ( "checkinterval", 10000 ) / 1000 ); lowSpinBox-> setValue ( config. readNumEntry ( "powerverylow", 10 ) ); criticalSpinBox-> setValue ( config. readNumEntry ( "powercritical", 5 ) ); m_resettimer = new QTimer ( this ); - connect ( m_resettimer, SIGNAL( timeout ( )), this, SLOT( resetBacklight ( ))); + connect ( m_resettimer, SIGNAL( timeout()), this, SLOT( resetBacklight())); if ( PowerStatusManager::readStatus ( ). acStatus ( ) != PowerStatus::Online ) { tabs-> setCurrentPage ( 0 ); } else { tabs-> setCurrentPage ( 1 ); } - connect ( brightness, SIGNAL( valueChanged ( int )), this, SLOT( setBacklight ( int ))); - connect ( brightness_ac, SIGNAL( valueChanged ( int )), this, SLOT( setBacklight ( int ))); + connect ( brightness, SIGNAL( valueChanged(int)), this, SLOT( setBacklight(int))); + connect ( brightness_ac, SIGNAL( valueChanged(int)), this, SLOT( setBacklight(int))); if (m_cres) { - connect ( contrast, SIGNAL( valueChanged ( int )), this, SLOT( setContrast ( int ))); - connect ( contrast_ac, SIGNAL( valueChanged ( int )), this, SLOT( setContrast ( int ))); + connect ( contrast, SIGNAL( valueChanged(int)), this, SLOT( setContrast(int))); + connect ( contrast_ac, SIGNAL( valueChanged(int)), this, SLOT( setContrast(int))); } connect( frequency, SIGNAL( activated(int) ), this, SLOT( setFrequency(int) ) ); connect( frequency_ac, SIGNAL( activated(int) ), this, SLOT( setFrequency(int) ) ); connect( closeHingeAction, SIGNAL( activated(int) ), this, SLOT( setCloseHingeAction(int) ) ); connect( closeHingeAction_ac, SIGNAL( activated(int) ), this, SLOT( setCloseHingeAction(int) ) ); } LightSettings::~LightSettings ( ) { } void LightSettings::calibrateSensor ( ) { Sensor *s = new Sensor ( m_sensordata, this ); - connect ( s, SIGNAL( viewBacklight ( int )), this, SLOT( setBacklight ( int ))); + connect ( s, SIGNAL( viewBacklight(int)), this, SLOT( setBacklight(int))); QPEApplication::execDialog( s ); delete s; } void LightSettings::calibrateSensorAC ( ) { Sensor *s = new Sensor ( m_sensordata_ac, this ); - connect ( s, SIGNAL( viewBacklight ( int )), this, SLOT( setBacklight ( int ))); + connect ( s, SIGNAL( viewBacklight(int)), this, SLOT( setBacklight(int))); QPEApplication::execDialog ( s ); delete s; } void LightSettings::setBacklight ( int bright ) { QCopEnvelope e ( "QPE/System", "setBacklight(int)" ); e << bright; if ( bright != -1 ) { m_resettimer-> stop ( ); m_resettimer-> start ( 4000, true ); } } void LightSettings::setContrast ( int contr ) { if (contr == -1) contr = m_oldcontrast; ODevice::inst ( )-> setDisplayContrast(contr); } void LightSettings::setFrequency ( int index ) { qWarning("LightSettings::setFrequency(%d)", index); ODevice::inst ( )-> setCurrentCpuFrequency(index); } void LightSettings::resetBacklight ( ) { setBacklight ( -1 ); setContrast ( -1 ); } void LightSettings::setCloseHingeAction ( int index ) { qWarning("LightSettings::setCloseHingeStatus(%d)", index); } void LightSettings::accept ( ) { Config config ( "apm" ); // bat config. setGroup ( "Battery" ); config. writeEntry ( "LcdOffOnly", LcdOffOnly-> isChecked ( )); config. writeEntry ( "Dim", interval_dim-> value ( )); config. writeEntry ( "LightOff", interval_lightoff-> value ( )); config. writeEntry ( "Suspend", interval_suspend-> value ( )); config. writeEntry ( "Brightness", brightness-> value () ); if (m_cres) config. writeEntry ( "Contrast", contrast-> value () ); config. writeEntry ( "Freq", frequency->currentItem() ); config. writeEntry ( "CloseHingeAction", closeHingeAction->currentItem() ); // ac config. setGroup ( "AC" ); config. writeEntry ( "LcdOffOnly", LcdOffOnly_ac-> isChecked ( )); config. writeEntry ( "Dim", interval_dim_ac-> value ( )); config. writeEntry ( "LightOff", interval_lightoff_ac-> value ( )); config. writeEntry ( "Suspend", interval_suspend_ac-> value ( )); config. writeEntry ( "Brightness", brightness_ac-> value () ); if (m_cres) config. writeEntry ( "Contrast", contrast_ac-> value () ); config. writeEntry ( "Freq", frequency_ac->currentItem() ); config. writeEntry ( "CloseHingeAction", closeHingeAction_ac->currentItem() ); // only make light sensor stuff appear if the unit has a sensor if ( ODevice::inst ( )-> hasLightSensor ( )) { config. setGroup ( "Battery" ); config. writeEntry ( "LightSensor", auto_brightness->isChecked() ); config. writeEntry ( "LightSensorData", m_sensordata, ';' ); config. setGroup ( "AC" ); config. writeEntry ( "LightSensor", auto_brightness_ac->isChecked() ); config. writeEntry ( "LightSensorData", m_sensordata_ac, ';' ); } // advanced config. setGroup ( "Warnings" ); config. writeEntry ( "check_interval", warnintervalBox-> value ( ) * 1000 ); config. writeEntry ( "power_verylow", lowSpinBox-> value ( )); config. writeEntry ( "power_critical", criticalSpinBox-> value ( )); config. write ( ); // notify the launcher { QCopEnvelope e ( "QPE/System", "reloadPowerWarnSettings()" ); } { QCopEnvelope e ( "QPE/System", "setScreenSaverInterval(int)" ); e << -1; } LightSettingsBase::accept ( ); } void LightSettings::done ( int r ) { m_resettimer-> stop ( ); resetBacklight ( ); LightSettingsBase::done ( r ); close ( ); } diff --git a/core/settings/light-and-power/sensor.cpp b/core/settings/light-and-power/sensor.cpp index 41de851..013e655 100644 --- a/core/settings/light-and-power/sensor.cpp +++ b/core/settings/light-and-power/sensor.cpp @@ -1,102 +1,102 @@ /* This file is part of the OPIE Project =. Copyright (c) 2002 Maximilian Reiss <harlekin@handhelds.org> .=l. Copyright (c) 2002 Robert Griebl <sandman@handhelds.org> .>+-= _;:, .> :=|. This file is free software; you can .> <`_, > . <= redistribute it and/or modify it under :`=1 )Y*s>-.-- : the terms of the GNU General Public .="- .-=="i, .._ License as published by the Free Software - . .-<_> .<> Foundation; either version 2 of the License, ._= =} : or (at your option) any later version. .%`+i> _;_. .i_,=:_. -<s. This file 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 General ..}^=.= = ; Public License for more details. ++= -. .` .: : = ...= . :.=- You should have received a copy of the GNU -. .:....=;==+<; General Public License along with this file; -_. . . )=. = see the file COPYING. If not, write to the -- :-=` Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include <qlayout.h> #include <qslider.h> #include <qspinbox.h> #include <opie/odevice.h> using namespace Opie; #include "calibration.h" #include "sensor.h" Sensor::Sensor ( QStringList ¶ms, QWidget *parent, const char *name ) : SensorBase ( parent, name, true, WStyle_ContextHelp ), m_params ( params ) { int steps = 12; int inter = 2; int smin = 40; int smax = 215; int lmin = 1; int lmax = 255; switch ( params. count ( )) { case 6: lmax = params [5]. toInt ( ); case 5: lmin = params [4]. toInt ( ); case 4: smax = params [3]. toInt ( ); case 3: smin = params [2]. toInt ( ); case 2: steps = params [1]. toInt ( ); case 1: inter = params [0]. toInt ( ) / 1000; } int xscale = ODevice::inst ( )-> lightSensorResolution ( ); int yscale = ODevice::inst ( )-> displayBrightnessResolution ( ); QVBoxLayout *lay = new QVBoxLayout ( frame ); lay-> setMargin ( 2 ); m_calib = new Calibration ( frame ); lay-> add ( m_calib ); m_calib-> setScale ( QSize ( xscale, yscale )); m_calib-> setLineSteps ( steps ); m_calib-> setInterval ( inter ); m_calib-> setStartPoint ( QPoint ( smin * xscale / 256, lmax * yscale / 256 )); m_calib-> setEndPoint ( QPoint ( smax * xscale / 256, lmin * yscale / 256 )); interval-> setValue ( inter ); linesteps-> setValue ( steps ); - connect ( interval, SIGNAL( valueChanged ( int )), m_calib, SLOT( setInterval ( int ))); - connect ( linesteps, SIGNAL( valueChanged ( int )), m_calib, SLOT( setLineSteps ( int ))); + connect ( interval, SIGNAL( valueChanged(int)), m_calib, SLOT( setInterval(int))); + connect ( linesteps, SIGNAL( valueChanged(int)), m_calib, SLOT( setLineSteps(int))); - connect ( m_calib, SIGNAL( startPointChanged ( const QPoint & )), this, SLOT( pointDrag ( const QPoint & ))); - connect ( m_calib, SIGNAL( endPointChanged ( const QPoint & )), this, SLOT( pointDrag ( const QPoint & ))); + connect ( m_calib, SIGNAL( startPointChanged(const QPoint&)), this, SLOT( pointDrag(const QPoint&))); + connect ( m_calib, SIGNAL( endPointChanged(const QPoint&)), this, SLOT( pointDrag(const QPoint&))); } void Sensor::accept ( ) { int xscale = ODevice::inst ( )-> lightSensorResolution ( ); int yscale = ODevice::inst ( )-> displayBrightnessResolution ( ); m_params. clear ( ); m_params << QString::number ( m_calib-> interval ( ) * 1000 ) << QString::number ( m_calib-> lineSteps ( )) << QString::number ( m_calib-> startPoint ( ). x ( ) * 256 / xscale ) << QString::number ( m_calib-> endPoint ( ). x ( ) * 256 / xscale ) << QString::number ( m_calib-> endPoint ( ). y ( ) * 256 / yscale ) << QString::number ( m_calib-> startPoint ( ). y ( ) * 256 / yscale ); QDialog::accept ( ); } void Sensor::pointDrag ( const QPoint &p ) { emit viewBacklight ( p. y ( )); } diff --git a/core/tools/quicklauncher/main.cpp b/core/tools/quicklauncher/main.cpp index cc411fd..1d6774c 100644 --- a/core/tools/quicklauncher/main.cpp +++ b/core/tools/quicklauncher/main.cpp @@ -1,265 +1,265 @@ /********************************************************************** ** Copyright (C) 2000-2003 Trolltech AS. All rights reserved. ** ** This file is part of the Qtopia Environment. ** ** This file may be distributed and/or modified under the terms of the ** GNU General Public License version 2 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. ** ** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE ** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. ** ** See http://www.trolltech.com/gpl/ for GPL licensing information. ** ** Contact info@trolltech.com if any conditions of this licensing are ** not clear to you. ** **********************************************************************/ #include <qpainter.h> #include <qstrlist.h> #include <qtimer.h> #include <qguardedptr.h> #include <qcopchannel_qws.h> #define QTOPIA_INTERNAL_INITAPP #ifdef private # undef private #endif #define private public #include <qtopia/qpeapplication.h> #undef private #include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include "dropins.h" static QPEApplication *app = 0; static PluginLoader *loader = 0; static ApplicationInterface *appIface = 0; static QGuardedPtr<QWidget> mainWindow; #ifdef _OS_LINUX_ static char **argv0 = 0; static int argv_lth; extern char **environ; #ifndef SPT_BUFSIZE #define SPT_BUFSIZE 2048 #endif #include <stdarg.h> void setproctitle (const char *fmt,...) { int i; char buf[SPT_BUFSIZE]; va_list ap; if (!argv0) return; va_start(ap, fmt); (void) vsnprintf(buf, SPT_BUFSIZE, fmt, ap); va_end(ap); i = strlen (buf); if (i > argv_lth - 2) { i = argv_lth - 2; buf[i] = '\0'; } memset(argv0[0], '\0', argv_lth); /* clear the memory area */ (void) strcpy (argv0[0], buf); argv0[1] = NULL; } #endif class QuickLauncher : public QObject { Q_OBJECT public: QuickLauncher() : QObject() { QCString ch("QPE/QuickLauncher-"); ch += QString::number(getpid()); qlChannel = new QCopChannel( ch, this); - connect( qlChannel, SIGNAL(received(const QCString&, const QByteArray&)), - this, SLOT(message(const QCString&, const QByteArray&)) ); + connect( qlChannel, SIGNAL(received(const QCString&,const QByteArray&)), + this, SLOT(message(const QCString&,const QByteArray&)) ); } static void exec( int /*argc*/, char **argv ) { QString appName = argv[0]; int sep = appName.findRev( '/' ); if ( sep > 0 ) appName = appName.mid( sep+1 ); appIface = 0; if ( loader->queryInterface(appName, IID_QtopiaApplication, (QUnknownInterface**)&appIface) == QS_OK ) { mainWindow = appIface->createMainWindow( appName ); } if ( mainWindow ) { if ( mainWindow->metaObject()->slotNames().contains("setDocument(const QString&)") ) { app->showMainDocumentWidget( mainWindow ); } else { app->showMainWidget( mainWindow ); } } else { qWarning( "Could not create application main window" ); exit(-1); } } private slots: void message(const QCString &msg, const QByteArray & data) { QStrList argList; if ( msg == "execute(QStrList)" ) { delete qlChannel; QDataStream stream( data, IO_ReadOnly ); QStrList argList; stream >> argList; qDebug( "QuickLauncher execute: %s", argList.at(0) ); doQuickLaunch( argList ); delete this; } else if ( msg == "execute(QString)" ) { delete qlChannel; QDataStream stream( data, IO_ReadOnly ); QString arg; stream >> arg; qDebug( "QuickLauncher execute: %s", arg.latin1() ); QStrList argList; argList.append( arg.utf8() ); doQuickLaunch( argList ); delete this; } } private: void doQuickLaunch( QStrList &argList ) { static int myargc = argList.count(); static char **myargv = new char *[myargc + 1]; for ( int j = 0; j < myargc; j++ ) { myargv[j] = new char [strlen(argList.at(j))+1]; strcpy( myargv[j], argList.at(j) ); } myargv[myargc] = NULL; #ifdef _OS_LINUX_ // Change name of process setproctitle(myargv[0]); #endif connect(app, SIGNAL(lastWindowClosed()), app, SLOT(hideOrQuit())); app->exit_loop(); app->initApp( myargc, myargv ); exec( myargc, myargv ); } private: QCopChannel *qlChannel; }; int main( int argc, char** argv ) { app = new QPEApplication( argc, argv ); loader = new PluginLoader( "application" ); unsetenv( "LD_BIND_NOW" ); QCString arg0 = argv[0]; int sep = arg0.findRev( '/' ); if ( sep > 0 ) arg0 = arg0.mid( sep+1 ); if ( arg0 != "quicklauncher" ) { qDebug( "QuickLauncher invoked as: %s", arg0.data() ); QuickLauncher::exec( argc, argv ); } else { #ifdef _OS_LINUX_ // Setup to change proc title int i; char **envp = environ; /* Move the environment so we can reuse the memory. * (Code borrowed from sendmail.) */ for (i = 0; envp[i] != NULL; i++) continue; environ = (char **) malloc(sizeof(char *) * (i + 1)); if (environ == NULL) return -1; for (i = 0; envp[i] != NULL; i++) if ((environ[i] = strdup(envp[i])) == NULL) return -1; environ[i] = NULL; argv0 = argv; if (i > 0) argv_lth = envp[i-1] + strlen(envp[i-1]) - argv0[0]; else argv_lth = argv0[argc-1] + strlen(argv0[argc-1]) - argv0[0]; #endif (void)new QuickLauncher(); qDebug( "QuickLauncher running" ); // Pre-load default fonts QFontMetrics fm( QApplication::font() ); fm.ascent(); // causes font load. QFont f( QApplication::font() ); f.setWeight( QFont::Bold ); QFontMetrics fmb( f ); fmb.ascent(); // causes font load. // Each of the following force internal structures/internal // initialization to be performed. This may mean allocating // memory that is not needed by all applications. #if 0 TimeZone::current().isValid(); // popuplate timezone cache TimeString::currentDateFormat(); // create internal structures TimeString::currentAMPM(); #endif Resource::loadIconSet("new"); // do internal init /* make sure libopie gets lined in */ { OWait item; } // Create a widget to force initialization of title bar images, etc. QObject::disconnect(app, SIGNAL(lastWindowClosed()), app, SLOT(hideOrQuit())); QWidget *w = new QWidget(0,0,Qt::WDestructiveClose|Qt::WStyle_ContextHelp|Qt::WStyle_Tool); w->setGeometry( -100, -100, 10, 10 ); w->show(); QTimer::singleShot( 0, w, SLOT(close()) ); app->enter_loop(); } int rv = app->exec(); if ( mainWindow ) delete (QWidget*)mainWindow; delete app; if ( appIface ) loader->releaseInterface( appIface ); delete loader; // Neither QLibrary nor my Dropin is a QObject and they don't depend // on a qApp so we destroy QWidget::destroyMapper() without // crashing the app // // The problem is there are some 'static' resources not freed // in the apps and on destructing these objects are not available // anymore. In future fix up the apps but for now // we just skip deletion and hope things go well -zecke // delete app; // hack instead -zecke // delete app->pidChannel; // app->pidChannel = 0; return rv; } #include "main.moc" diff --git a/development/keyview/keyview.cpp b/development/keyview/keyview.cpp index 21bbb93..93c84d9 100644 --- a/development/keyview/keyview.cpp +++ b/development/keyview/keyview.cpp @@ -1,69 +1,69 @@ #include "keyview.h" #include <qgrid.h> //#include <iostream.h> #include <qlineedit.h> #include <qlabel.h> Keyview::Keyview( QWidget* parent, const char* name, WFlags fl ) : QGrid ( 2, parent, name, fl ) { setCaption( tr("Keyview") ); setSpacing(3); setMargin(4); QLabel *l; l = new QLabel(QString("unicode:"), this); unicode = new QLineEdit(this); unicode->setReadOnly(1); l = new QLabel(QString("keycode:"), this); keycode = new QLineEdit(this); keycode->setReadOnly(1); l = new QLabel(QString("modifiers:"), this); modifiers = new QLineEdit(this); modifiers->setReadOnly(1); l = new QLabel(QString("isPress:"), this); isPress = new QLineEdit(this); isPress->setReadOnly(1); l = new QLabel(QString("autoRepeat:"), this); autoRepeat = new QLineEdit(this); autoRepeat->setReadOnly(1); // spacer l = new QLabel(QString(""), this); l->setSizePolicy(QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding)); KeyFilter *filter = new KeyFilter(this); QWSServer::setKeyboardFilter(filter); - connect(filter, SIGNAL(keyPressed(int, int, int, bool, bool)), - this, SLOT(updateItems(int, int, int, bool, bool))); + connect(filter, SIGNAL(keyPressed(int,int,int,bool,bool)), + this, SLOT(updateItems(int,int,int,bool,bool))); } Keyview::~Keyview() { } void Keyview::updateItems(int u, int k, int m, bool p, bool a) { unicode->setText("0x" + QString::number(u, 16)); keycode->setText("0x" + QString::number(k, 16)); modifiers->setText("0x" + QString::number(m, 16)); isPress->setText("0x" + QString::number(p, 16)); autoRepeat->setText("0x" + QString::number(a, 16)); } KeyFilter::KeyFilter(QObject * parent, const char *name) : QObject( parent, name ) { } bool KeyFilter::filter(int unicode, int keycode, int modifiers, bool isPress, bool autoRepeat) { emit keyPressed(unicode, keycode, modifiers, isPress, autoRepeat); return 0; // return 1 to stop key emiting } diff --git a/examples/main-tab/simple.cpp b/examples/main-tab/simple.cpp index 69dd00f..c5a6d5a 100644 --- a/examples/main-tab/simple.cpp +++ b/examples/main-tab/simple.cpp @@ -1,211 +1,211 @@ #include <qaction.h> // action #include <qmenubar.h> // menubar #include <qtoolbar.h> // toolbar #include <qlabel.h> // a label #include <qpushbutton.h> // the header file for the QPushButton #include <qlayout.h> #include <qpe/qpeapplication.h> // the QPEApplication #include <qpe/resource.h> #include <qpe/sound.h> #include <opie/oapplicationfactory.h> // a template + macro to save the main method and allow quick launching #include <opie/otabwidget.h> #include "simple.h" /* * implementation of simple */ /* * The factory is used for quicklaunching * It needs a constructor ( c'tor ) with at least QWidget, const char* and WFlags as parameter and a static QString appName() matching the TARGET of the .pro * * Depending on the global quick launch setting this will create * either a main method or one for our component plugin system */ OPIE_EXPORT_APP( OApplicationFactory<MainWindow> ) MainWindow::MainWindow(QWidget *parent, const char* name, WFlags fl ) : QMainWindow( parent, name, fl ) { setCaption(tr("My MainWindow") ); initUI(); /* * Tab widget as central */ OTabWidget *tab = new OTabWidget(this); connect(tab, SIGNAL(currentChanged(QWidget*) ), - this, SLOT( slotCurrentChanged( QWidget* ) ) ); + this, SLOT( slotCurrentChanged(QWidget*) ) ); setCentralWidget( tab ); Simple1 *simple1 = new Simple1( this ); tab->addTab( simple1, "new", tr("Simple1") ); tab->setCurrentTab( tr("Simple1") ); Simple2 *simple2 = new Simple2( this ); tab->addTab( simple2, "trash", tr("Simple2") ); m_oldCurrent = simple1; connect(m_fire, SIGNAL(activated() ), simple1, SLOT(slotFire() ) ); } MainWindow::~MainWindow() { // again nothing to delete because Qt takes care } void MainWindow::setDocument( const QString& /*str*/ ) { } void MainWindow::slotCurrentChanged( QWidget *wid) { disconnect(m_fire, SIGNAL(activated() ), m_oldCurrent, SLOT(slotFire() ) ); connect(m_fire, SIGNAL(activated() ), wid, SLOT(slotFire() ) ); m_oldCurrent = wid; } void MainWindow::initUI() { setToolBarsMovable( false ); QToolBar *menuBarHolder = new QToolBar( this ); menuBarHolder->setHorizontalStretchable( true ); QMenuBar *mb = new QMenuBar( menuBarHolder ); QToolBar *tb = new QToolBar( this ); QPopupMenu *fileMenu = new QPopupMenu( this ); QAction *a = new QAction( tr("Quit"), Resource::loadIconSet("quit_icon"), QString::null, 0, this, "quit_action" ); /* * Connect quit to the QApplication quit slot */ connect(a, SIGNAL(activated() ), qApp, SLOT(quit() ) ); a->addTo( fileMenu ); a = new QAction(tr("Fire"), Resource::loadIconSet("new"), QString::null, 0, this, "fire_button"); /* see the power? */ a->addTo( fileMenu ); a->addTo( tb ); m_fire = a; mb->insertItem(tr("File"), fileMenu ); } Simple1::Simple1( QWidget* parent, const char* name, WFlags fl ) : QWidget( parent, name, fl ) { QVBoxLayout *layout = new QVBoxLayout( this ); layout->setSpacing( 8 ); layout->setMargin( 11 ); QLabel *lbl = new QLabel( this, "a name for the label" ); lbl->setText( tr("Click on the button or follow the white rabbit") ); layout->addWidget( lbl ); m_button = new QPushButton(this); m_button->setText( tr("Fire", "translatable quit string" ) ); layout->addWidget( m_button ); connect( m_button, SIGNAL(clicked() ), this, SLOT( slotFire() ) ); } Simple1::~Simple1() { } void Simple1::slotFire() { /* * NOTE: Simple is now a child window of MainWindow * close will hide() Simple and not delete it. But as * the mainwindow is shown all children will be shown as well */ close(); } Simple2::Simple2( QWidget* parent, const char* name, WFlags fl ) : QWidget( parent, name, fl ) { /* * sets the caption of this toplevel widget * put all translatable string into tr() */ setCaption(tr("My Simple Application") ); /* * A simple vertical layout * either call layout->setAutoAdd( true ) * or use layout->addWidget( wid ) to add widgets */ QVBoxLayout *layout = new QVBoxLayout( this ); layout->setSpacing( 8 ); layout->setMargin( 11 ); /* * creates a label * The first parameter is this widget so the Label is a child * of us and will be deleted when we're deleted. */ QLabel *lbl = new QLabel( this, "a name for the label" ); /* * Resource will search hard for a Pixmap in $OPIEDIR/pics * to find 'logo/opielogo' You need to pass the subdir * but not the ending */ lbl->setPixmap( Resource::loadPixmap("logo/opielogo") ); layout->addWidget( lbl ); /* creates a button as child of this widget */ m_button = new QPushButton(this); /* * another way to call tr. The first parameter is the string * to translate and the second a hint to the translator */ m_button->setText( tr("Fire", "translatable fire string" ) ); layout->addWidget( m_button ); connect( m_button, SIGNAL(clicked() ), this, SLOT( slotQuit() ) ); } Simple2::~Simple2() { } void Simple2::slotFire() { /* * We will fire up a sound * Note that Sound will use Resource as well * and we do not need to supply an ending * sounds are found in $OPIEDIR/sounds */ Sound snd("hit_target01"); snd.play(); } diff --git a/examples/simple-pim/simple.cpp b/examples/simple-pim/simple.cpp index 3e9fcd3..029e71b 100644 --- a/examples/simple-pim/simple.cpp +++ b/examples/simple-pim/simple.cpp @@ -1,445 +1,445 @@ #include <qaction.h> // action #include <qmenubar.h> // menubar #include <qtoolbar.h> // toolbar #include <qlabel.h> // a label #include <qpushbutton.h> // the header file for the QPushButton #include <qlayout.h> #include <qtimer.h> // we use it for the singleShot #include <qdatetime.h> // for QDate #include <qtextview.h> // a rich text widget #include <qdialog.h> #include <qwhatsthis.h> // for whats this #include <qpe/qpeapplication.h> // the QPEApplication #include <qpe/resource.h> #include <qpe/sound.h> #include <qpe/qcopenvelope_qws.h> #include <qpe/datebookmonth.h> #include <qpe/timestring.h> #include <opie/oapplicationfactory.h> // a template + macro to save the main method and allow quick launching #include <opie/otabwidget.h> #include <opie/owait.h> #include "simple.h" /* * implementation of simple */ /* * The factory is used for quicklaunching * It needs a constructor ( c'tor ) with at least QWidget, const char* and WFlags as parameter and a static QString appName() matching the TARGET of the .pro * * Depending on the global quick launch setting this will create * either a main method or one for our component plugin system */ OPIE_EXPORT_APP( OApplicationFactory<MainWindow> ) MainWindow::MainWindow(QWidget *parent, const char* name, WFlags fl ) : QMainWindow( parent, name, fl ) { setCaption(tr("My MainWindow") ); m_desktopChannel = 0; m_loading = 0; initUI(); /* * Tab widget as central */ m_tab = new OTabWidget(this); setCentralWidget( m_tab ); m_todoView = new PIMListView(m_tab, "Todo view" ); m_tab->addTab( m_todoView,"todo/TodoList", tr("Todos") ); m_dateView = new PIMListView(m_tab, "Datebook view" ); m_tab->addTab( m_dateView, "datebook/DateBook", tr("Events") ); /* now connect the actions */ /* * we connect the activated to our show * and on activation we will show a detailed * summary of the record */ connect(m_fire, SIGNAL(activated() ), this, SLOT(slotShow() ) ); /* * We will change the date */ connect(m_dateAction, SIGNAL(activated() ), this, SLOT(slotDate() ) ); /* * connect the show signal of the PIMListView * to a slot to show a dialog */ - connect(m_todoView, SIGNAL(showRecord(const OPimRecord& ) ), - this, SLOT(slotShowRecord(const OPimRecord& ) ) ); - connect(m_dateView, SIGNAL(showRecord(const OPimRecord& ) ), - this, SLOT(slotShowRecord(const OPimRecord& ) ) ); + connect(m_todoView, SIGNAL(showRecord(const OPimRecord&) ), + this, SLOT(slotShowRecord(const OPimRecord&) ) ); + connect(m_dateView, SIGNAL(showRecord(const OPimRecord&) ), + this, SLOT(slotShowRecord(const OPimRecord&) ) ); /* * Now comes the important lines of code for this example * We do not directly call load but delay loading until * all Events are dispatches and handled. * SO we will load once our window is mapped to screen * to achieve that we use a QTimer::singleShot * After 10 milli seconds the timer fires and on TimerEvent * out slot slotLoad will be called * Remember this a Constructor to construct your object and not * to load */ QTimer::singleShot( 10, this, SLOT(slotLoad() ) ); } MainWindow::~MainWindow() { // again nothing to delete because Qt takes care } void MainWindow::setDocument( const QString& /*str*/ ) { } void MainWindow::initUI() { setToolBarsMovable( false ); QToolBar *menuBarHolder = new QToolBar( this ); menuBarHolder->setHorizontalStretchable( true ); QMenuBar *mb = new QMenuBar( menuBarHolder ); QToolBar *tb = new QToolBar( this ); QPopupMenu *fileMenu = new QPopupMenu( this ); QAction *a = new QAction( tr("Quit"), Resource::loadIconSet("quit_icon"), QString::null, 0, this, "quit_action" ); /* * Connect quit to the QApplication quit slot */ connect(a, SIGNAL(activated() ), qApp, SLOT(quit() ) ); a->addTo( fileMenu ); a = new QAction(tr("View Current"), Resource::loadIconSet("zoom"), QString::null, 0, this, "view current"); /* a simple whats this online explanation of out button */ a->setWhatsThis(tr("Views the current record") ); /* or QWhatsThis::add(widget, "description" ); */ /* see the power? */ a->addTo( fileMenu ); a->addTo( tb ); m_fire = a; a = new QAction(tr("Choose Date"), Resource::loadIconSet("day"), QString::null, 0, this, "choose date" ); a->addTo( fileMenu ); a->addTo( tb ); m_dateAction = a; mb->insertItem(tr("File"), fileMenu ); } void MainWindow::slotLoad() { /* * There is no real shared access in the PIM API * It wasn't finish cause of health problems of one * of the authors so we do something fancy and use QCOP * the IPC system to get a current copy */ /* NOTES to QCOP: QCOP operates over channels and use QDataStream * to send data. You can check if a channel isRegistered or hook * yourself to that channel. A Channel is QCString and normally * prefix with QPE/ and then the system in example QPE/System, * QPE/Desktop a special channel is the application channel * it QPE/Application/appname this channel gets created on app * startup by QPEApplication. QCOP is asynchronous * * To send you'll use QCopEnevelope * */ /* * What we will do is first is get to know if either * datebook or todolist are running if so we will kindly * asked to save the data for us. * If neither are running we can load directly */ if (!QCopChannel::isRegistered("QPE/Application/todolist") && !QCopChannel::isRegistered("QPE/Application/datebook") ) { m_db.load(); m_tb.load(); return slotLoadForDay( QDate::currentDate() ); } /* * prepare our answer machine the QCopChannel * QPE/Desktop will send "flushDone(QString)" when * the flush is done it emits a signal on receive */ m_desktopChannel = new QCopChannel("QPE/Desktop"); - connect(m_desktopChannel, SIGNAL(received(const QCString&, const QByteArray& ) ), - this, SLOT(slotDesktopReceive(const QCString&, const QByteArray& ) ) ); + connect(m_desktopChannel, SIGNAL(received(const QCString&,const QByteArray&) ), + this, SLOT(slotDesktopReceive(const QCString&,const QByteArray&) ) ); /* the numberof synced channels will be set to zero */ m_synced = 0; /* * We use {} around the QCopEnvelope because it sends its * data on destruction of QCopEnvelope with */ /* check again if not present increment synced*/ if ( QCopChannel::isRegistered("QPE/Application/todolist") ) { QCopEnvelope env("QPE/Application/todolist", "flush()" ); // env << data; but we do not have any parameters here }else m_synced++; if ( QCopChannel::isRegistered("QPE/Application/datebook") ) { QCopEnvelope env("QPE/Application/datebook", "flush()" ); }else m_synced++; /* we will provide a wait scrren */ m_loading = new OWait(this, "wait screen" ); } void MainWindow::slotDesktopReceive(const QCString& cmd, const QByteArray& data ) { /* the bytearray was filled with the QDataStream now * we open it read only to get the value(s) */ QDataStream stream(data, IO_ReadOnly ); /* * we're only interested in the flushDone */ if ( cmd == "flushDone(QString)" ) { QString appname; stream >> appname; // get the first argument out of stream if (appname == QString::fromLatin1("datebook") || appname == QString::fromLatin1("todolist") ) m_synced++; } /* * If we synced both we can go ahead * In future this is not needed anymore when we finally * implemented X-Ref and other PIM features */ if (m_synced >= 2 ) { delete m_loading; delete m_desktopChannel; /* now we finally can start doing the actual loading */ m_tb.load(); m_db.load(); { /* tell the applications to reload */ QCopEnvelope("QPE/Application/todolist", "reload()"); QCopEnvelope("QPE/Application/datebook", "reload()"); } slotLoadForDay( QDate::currentDate() ); } } /* overloaded member for shortcoming of libqpe */ void MainWindow::slotLoadForDay(int y, int m, int d) { /* year,month, day */ slotLoadForDay( QDate(y, m, d ) ); } void MainWindow::slotLoadForDay(const QDate& date) { /* all todos for today including the ones without dueDate */ m_todoView->set( m_tb.effectiveToDos(date, date ) ); m_dateView->set( m_db.effectiveEvents( date, date ) ); } /* we want to show the current record */ void MainWindow::slotShow() { /* we only added PIMListViews so we can safely cast */ PIMListView *view = static_cast<PIMListView*>(m_tab->currentWidget() ); /* ask the view to send a signal */ view->showCurrentRecord(); } /* as answer this slot will be called */ void MainWindow::slotShowRecord( const OPimRecord& rec) { /* got a parent but still is a toplevel MODAL dialog */ QDialog* dia = new QDialog(this,"dialog",TRUE ); QVBoxLayout *box = new QVBoxLayout( dia ); dia->setCaption( tr("View Record") ); QTextView *view = new QTextView(dia ); view->setText( rec.toRichText() ); box->addWidget( view ); /* * execute via QPEApplication * this allows QPEApplication to make a sane decision * on the size */ dia->showMaximized(); QPEApplication::execDialog( dia ); delete dia; } void MainWindow::slotDate() { /* * called by the action we will show a Popup * at the current mouse position with a DateChooser * to select the day */ qWarning("slot Date"); QPopupMenu *menu = new QPopupMenu(); /* A Month to select a date from TRUE for auto close */ DateBookMonth *month = new DateBookMonth(menu, 0, true ); - connect(month, SIGNAL(dateClicked(int, int, int) ), - this, SLOT(slotLoadForDay(int, int, int) ) ); + connect(month, SIGNAL(dateClicked(int,int,int) ), + this, SLOT(slotLoadForDay(int,int,int) ) ); menu->insertItem( month ); menu->exec( QCursor::pos() ); /* * we do not need to delete month because * we delete its parent menu */ delete menu; } /* * An anonymous namespace this symbol is only available here * so truely private */ namespace { /* not static cause namespace does that what static would do */ const int RTTI = 5050; /* * every ListView got Items. we've special pim items * holding ownership and the pointer to a pim record * it can't hold a pimrecord directly because this * would introduce slicing... any break */ /* * A struct is a special class. Everything is public by * default. */ struct PIMListViewItem : public QListViewItem { /* *currently no hierachies are planed for the example * so only one constructor with a QListView as parent */ PIMListViewItem( QListView*, OPimRecord* record ); ~PIMListViewItem(); /* used by the QListViewItem to easily allow identifiying of different * items. Values greater than 1000 should be used */ int rtti()const; OPimRecord* record()const; private: OPimRecord* m_record; }; PIMListViewItem::PIMListViewItem( QListView *p, OPimRecord* rec ) : QListViewItem(p), m_record( rec ) { } PIMListViewItem::~PIMListViewItem() { /* we've the onwership so we need to delete it */ delete m_record; } OPimRecord* PIMListViewItem::record()const { return m_record; } } PIMListView::PIMListView( QWidget* widget, const char* name, WFlags fl ) : QListView(widget, name, fl ) { addColumn("Summary"); } PIMListView::~PIMListView() { } void PIMListView::set( OTodoAccess::List list ) { /* clear first and then add new items */ clear(); OTodoAccess::List::Iterator it; for (it = list.begin(); it != list.end(); ++it ) { /* * make a new item which automatically gets added to the listview * and call the copy c'tor to create a new OTodo */ PIMListViewItem *i = new PIMListViewItem(this, new OTodo( *it ) ); i->setText(0, (*it).summary() ); } } void PIMListView::set( const OEffectiveEvent::ValueList& lst ) { /* clear first and then add items */ clear(); OEffectiveEvent::ValueList::ConstIterator it; for ( it = lst.begin(); it != lst.end(); ++it ) { PIMListViewItem *i = new PIMListViewItem(this, new OEvent( (*it).event() ) ); i->setText( 0, PIMListView::makeString( (*it) ) ); } } void PIMListView::showCurrentRecord() { /* it could be possible that their is no currentItem */ if (!currentItem() ) return; /* * we only add PIMListViewItems so it is save * to do this case. If this would not be the case * use rtti() to check in a switch() case */ PIMListViewItem *item = static_cast<PIMListViewItem*>( currentItem() ); /* finally you see how to emit a signal */ emit showRecord( (*item->record() ) ); } QString PIMListView::makeString( const OEffectiveEvent& ev ) { QString str; str += ev.description(); if ( !ev.event().isAllDay() ) { if ( ev.startDate() != ev.endDate() ) { str += tr("Start ") + TimeString::timeString( ev.event().startDateTime().time() ); str += " - " + TimeString::longDateString( ev.startDate() ); str += tr("End ") + TimeString::timeString( ev.event().endDateTime().time() ); str += " - " + TimeString::longDateString( ev.endDate() ); }else{ str += tr("Time ") + TimeString::timeString( ev.startTime() ); str += " - " + TimeString::timeString( ev.endTime() ); } }else str += tr(" This is an All-Day Event"); return str; } diff --git a/inputmethods/handwriting/qimpenhelp.cpp b/inputmethods/handwriting/qimpenhelp.cpp index a294301..0727931 100644 --- a/inputmethods/handwriting/qimpenhelp.cpp +++ b/inputmethods/handwriting/qimpenhelp.cpp @@ -1,386 +1,386 @@ /********************************************************************** ** Copyright (C) 2000-2002 Trolltech AS. All rights reserved. ** ** This file is part of the Qtopia Environment. ** ** This file may be distributed and/or modified under the terms of the ** GNU General Public License version 2 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. ** ** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE ** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. ** ** See http://www.trolltech.com/gpl/ for GPL licensing information. ** ** Contact info@trolltech.com if any conditions of this licensing are ** not clear to you. ** **********************************************************************/ #include "qimpenwidget.h" #include "qimpencombining.h" #include "qimpenmatch.h" #include "qimpenhelp.h" #include <qpe/qpeapplication.h> #include <qpe/global.h> #include <qpe/config.h> #include <qpe/stringutil.h> #include <qtextview.h> #include <qlabel.h> #include <qlistbox.h> #include <qcombobox.h> #include <qpushbutton.h> #include <qlayout.h> #include <qtimer.h> #include <qtextstream.h> /* XPM */ static const char * const left_xpm[] = { "16 16 2 1", " c None", ". c #000000", " ", " ", " ", " . ", " .. ", " ... ", " .... ", " ..... ", " ...... ", " ..... ", " .... ", " ... ", " .. ", " . ", " ", " "}; /* XPM */ static const char * const right_xpm[] = { "16 16 2 1", " c None", ". c #000000", " ", " ", " ", " . ", " .. ", " ... ", " .... ", " ..... ", " ...... ", " ..... ", " .... ", " ... ", " .. ", " . ", " ", " "}; class CharListItem : public QListBoxText { public: CharListItem( const QString &text, uint c ) : QListBoxText( text ) { _code = c; } uint code() const { return _code; } protected: uint _code; }; HandwritingHelp::HandwritingHelp( QIMPenProfile *p, QWidget *parent, const char *name, WFlags f ) : QTabWidget( parent, name, f ) { setCaption( tr("Handwriting Help") ); QTextView *help = new QTextView( this ); help->setFrameStyle( QFrame::NoFrame ); help->setText( tr( "<ul><li>When you start to use the handwriting recogniser " "write slowly, accurately and firmly." "<li>Use the guide lines when drawing your characters." "<li>When drawing a character with multiple strokes, each " "successive stroke must be drawn before the grayed strokes are erased." "<li>Practice your handwriting using the handwriting trainer." "<li>When adding your own character templates make sure they " "are sufficiently different from other characters' templates." "</ul>") ); addTab( help, tr("Tips") ); HandwritingTrainer *trainer = new HandwritingTrainer( p, this ); addTab( trainer, tr("Trainer") ); } void HandwritingHelp::showEvent( QShowEvent * ) { Global::hideInputMethod(); } void HandwritingHelp::hideEvent( QHideEvent * ) { Global::showInputMethod(); } //--------------------------------------------------------------------------- HandwritingTrainer::HandwritingTrainer( QIMPenProfile *p, QWidget *parent, const char *name ) : QWidget( parent, name ), profile(p) { QGridLayout *gl = new QGridLayout( this, 4, 2, 0, 4 ); gl->setColStretch( 1, 1 ); gl->setRowStretch(3, 1); charSetCombo = new QComboBox( this ); gl->addMultiCellWidget( charSetCombo, 0, 0, 0, 1 ); connect( charSetCombo, SIGNAL(activated(int)), SLOT(selectCharSet(int))); QIMPenCharSetIterator it( profile->charSets() ); for ( ; it.current(); ++it ) { charSetCombo->insertItem( it.current()->description() ); } charList = new QListBox( this ); charList->setHScrollBarMode( QListBox::AlwaysOff ); charList->setFixedWidth(80); connect( charList, SIGNAL(highlighted(int)), this, SLOT(selectChar(int)) ); gl->addWidget(charList, 1, 0); result = new QLabel( this ); result->setAlignment(AlignLeft | AlignVCenter | WordBreak); result->setText( tr( "Select a reference character from the list. Practice writing in " "the area on the right.")); gl->addMultiCellWidget(result, 1, 2, 1, 1); matcher = new QIMPenMatch( this ); matcher->setCharSet( currentSet ); connect( matcher, SIGNAL(noMatch()), this, SLOT(noMatch()) ); - connect( matcher, SIGNAL(matchedCharacters(const QIMPenCharMatchList &)), - this, SLOT(matched(const QIMPenCharMatchList &)) ); + connect( matcher, SIGNAL(matchedCharacters(const QIMPenCharMatchList&)), + this, SLOT(matched(const QIMPenCharMatchList&)) ); QHBoxLayout *hb = new QHBoxLayout(); gl->addLayout( hb, 2, 0 ); prevBtn = new QPushButton( this ); prevBtn->setPixmap( QPixmap( (const char **)left_xpm ) ); connect( prevBtn, SIGNAL(clicked()), SLOT(prevChar())); hb->addWidget( prevBtn ); nextBtn = new QPushButton( this ); nextBtn->setPixmap( QPixmap( (const char **)right_xpm ) ); connect( nextBtn, SIGNAL(clicked()), SLOT(nextChar())); hb->addWidget( nextBtn ); refPw = new QIMPenWidget( this ); refPw->setReadOnly( TRUE ); gl->addWidget( refPw, 3, 0 ); pracPw = new QIMPenWidget( this ); connect( matcher, SIGNAL(removeStroke()), pracPw, SLOT(removeStroke()) ); connect( pracPw, SIGNAL(beginStroke()), this, SLOT(beginStroke()) ); - connect( pracPw, SIGNAL(stroke( QIMPenStroke * )), - this, SLOT(strokeEntered( QIMPenStroke * )) ); + connect( pracPw, SIGNAL(stroke(QIMPenStroke*)), + this, SLOT(strokeEntered(QIMPenStroke*)) ); connect( pracPw, SIGNAL(beginStroke()), matcher, SLOT(beginStroke()) ); - connect( pracPw, SIGNAL(stroke( QIMPenStroke * )), - matcher, SLOT(strokeEntered( QIMPenStroke * )) ); + connect( pracPw, SIGNAL(stroke(QIMPenStroke*)), + matcher, SLOT(strokeEntered(QIMPenStroke*)) ); gl->addWidget( pracPw, 3, 1 ); redrawTimer = new QTimer( this ); connect( redrawTimer, SIGNAL(timeout()), this, SLOT(redrawChar()) ); redrawTimer->start( 5000 ); currentSet = 0; charSetCombo->setCurrentItem( 1 ); selectCharSet( 1 ); } HandwritingTrainer::~HandwritingTrainer() { } void HandwritingTrainer::showEvent( QShowEvent * ) { redrawChar(); redrawTimer->start( 5000 ); } void HandwritingTrainer::setCurrentChar( QIMPenChar *c ) { currentChar = c; refPw->showCharacter( currentChar ); pracPw->clear(); if ( currentChar ) { prevBtn->setEnabled( findPrev() != 0 ); nextBtn->setEnabled( findNext() != 0 ); } redrawTimer->start( 5000 ); } void HandwritingTrainer::selectChar( int i ) { static int last_char = 0; if (last_char != i) { result->setText(""); } currentChar = 0; currentCode = ((CharListItem *)charList->item(i))->code(); QIMPenCharIterator it(currentSet->characters() ); for ( ; it.current(); ++it ) { if ( it.current()->character() == currentCode && !it.current()->testFlag( QIMPenChar::Deleted ) ) { setCurrentChar( it.current() ); break; } } if ( !it.current() ) setCurrentChar( 0 ); } void HandwritingTrainer::selectCharSet( int i ) { if ( currentSet ) { refPw->removeCharSet( 0 ); pracPw->removeCharSet( 0 ); result->setText(""); } currentSet = profile->charSets().at( i ); fillCharList(); refPw->insertCharSet( currentSet ); pracPw->insertCharSet( currentSet ); matcher->setCharSet( currentSet ); if ( charList->count() ) { charList->setSelected( 0, TRUE ); selectChar(0); } } void HandwritingTrainer::noMatch() { result->setText( tr("No match") ); } void HandwritingTrainer::matched( const QIMPenCharMatchList &ml ) { int maxErr = 20000 + (*ml.begin()).penChar->strokeLength(0) * 1000; int baseErr = (*ml.begin()).penChar->strokeLength(0) * 250; unsigned int numStrokes = (*ml.begin()).penChar->strokeCount(); QIMPenCharMatchList::ConstIterator it; /* for ( it = ml.begin(); it != ml.end(); ++it ) { if ( (*it).penChar->strokeCount() == numStrokes ) { if ( (*it).error > maxErr ) maxErr = (*it).error; } } */ int i; QString res; QTextStream ts(&res, IO_WriteOnly); ts << "<qt>" << tr("Matched: "); for ( i = 0, it = ml.begin(); it != ml.end() && i < 4; ++it, i++ ) { if ( (*it).penChar->strokeCount() == numStrokes ) { int rate = 100 - ( ((*it).error - baseErr) * 100 ) / maxErr; if ( it != ml.begin() ) { if ( rate < -10 ) continue; ts << "<br>"; ts << tr("Similar to: "); } ts << "<big>"; if ( (*it).penChar->character() == currentChar->character() ) ts << "<b>"; ts << Qtopia::escapeString((*it).penChar->name()); ts << " (" << rateString(rate) << ")"; if ( (*it).penChar->character() == currentChar->character() ) ts << "</b>"; ts << "</big>"; } } ts << "</qt>"; result->setText( res ); } QString HandwritingTrainer::rateString( int rate ) const { if ( rate < 1 ) rate = 1; if ( rate > 100 ) rate = 100; return tr("%1%").arg(rate); } void HandwritingTrainer::prevChar() { QIMPenChar *pc = findPrev(); if ( pc ) setCurrentChar( pc ); } void HandwritingTrainer::nextChar() { QIMPenChar *pc = findNext(); if ( pc ) setCurrentChar( pc ); } void HandwritingTrainer::redrawChar() { if ( currentChar ) refPw->showCharacter( currentChar ); } void HandwritingTrainer::beginStroke() { redrawTimer->start( 5000 ); } void HandwritingTrainer::strokeEntered( QIMPenStroke * ) { pracPw->greyStroke(); } QIMPenChar *HandwritingTrainer::findPrev() { if ( !currentChar ) return 0; QIMPenCharIterator it( currentSet->characters() ); bool found = FALSE; for ( it.toLast(); it.current(); --it ) { if ( !found && it.current() == currentChar ) found = TRUE; else if ( found && it.current()->character() == currentCode && !it.current()->testFlag( QIMPenChar::Deleted ) ) { return it.current(); } } return 0; } QIMPenChar *HandwritingTrainer::findNext() { if ( !currentChar ) return 0; QIMPenCharIterator it( currentSet->characters() ); bool found = FALSE; for ( ; it.current(); ++it ) { if ( !found && it.current() == currentChar ) found = TRUE; else if ( found && it.current()->character() == currentCode && !it.current()->testFlag( QIMPenChar::Deleted ) ) { return it.current(); } } return 0; diff --git a/inputmethods/handwriting/qimpeninput.cpp b/inputmethods/handwriting/qimpeninput.cpp index db33c9b..d073cdf 100644 --- a/inputmethods/handwriting/qimpeninput.cpp +++ b/inputmethods/handwriting/qimpeninput.cpp @@ -1,404 +1,404 @@ /********************************************************************** ** Copyright (C) 2000-2002 Trolltech AS. All rights reserved. ** ** This file is part of the Qtopia Environment. ** ** This file may be distributed and/or modified under the terms of the ** GNU General Public License version 2 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. ** ** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE ** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. ** ** See http://www.trolltech.com/gpl/ for GPL licensing information. ** ** Contact info@trolltech.com if any conditions of this licensing are ** not clear to you. ** **********************************************************************/ #include "qimpenwidget.h" #include "qimpensetup.h" #include "qimpeninput.h" #include "qimpencombining.h" #include "qimpenwordpick.h" #include "qimpenmatch.h" #include "qimpenhelp.h" #include <qpe/qpeapplication.h> #include <qpe/qdawg.h> #include <qpe/config.h> #include <qpe/global.h> #include <qlayout.h> #include <qpushbutton.h> #include <qlabel.h> #include <qtimer.h> #include <qdir.h> #include <limits.h> // We'll use little pixmaps for the buttons to save screen space. /* XPM */ static const char * const pen_xpm[] = { "12 12 4 1", " c None", ". c #000000", "+ c #FFFFFF", "@ c #808080", " . ", " .+. ", " ..@@.", " .+@.. ", " .+@@. ", " .+@@. ", " .+@@. ", " .@.@. ", " .@@. ", " .... ", " .. ", " "}; /* XPM */ static char * bs_xpm[] = { "12 12 5 1", " c None", ". c #333333", "+ c #000000", "@ c #FFFFFF", "# c #666666", " ", " ", " ", " . ", " ++ ", " +@#+++++. ", " +@@@@@@@@+ ", " +@#+++++. ", " ++ ", " . ", " ", " "}; /* XPM */ static char * enter_xpm[] = { "12 12 5 1", " c None", ". c #333333", "+ c #000000", "@ c #FFFFFF", "# c #666666", " ", " .+. ", " +@+ ", " . +@+ ", " ++ +@+ ", " +@#++++@+ ", " +@@@@@@@@+ ", " +@#+++++. ", " ++ ", " . ", " ", " "}; /* XPM */ static char * help_xpm[] = { "12 12 5 1", " c None", ". c #000000", "+ c #FFFFFF", "@ c #666666", "# c #333333", " ", " ... ", " .+++. ", " .+..@+. ", " #.# .+. ", " .+. ", " .+. ", " .+. ", " .+. ", " #.# ", " .+. ", " #.# "}; /*! \class QIMPenInput qimpeninput.h Pen input widget. */ QIMPenInput::QIMPenInput( QWidget *parent, const char *name, WFlags wf ) : QFrame( parent, name, wf ), helpDlg(0), profile(0) { setFrameStyle( Box | Plain ); profileList.setAutoDelete( true ); matcher = new QIMPenMatch( this ); connect( matcher, SIGNAL(keypress(uint)), this, SLOT(keypress(uint)) ); connect( matcher, SIGNAL(erase()), this, SLOT(erase()) ); QGridLayout *gl = new QGridLayout( this, 5, 2, 1, 0 ); gl->setColStretch( 0, 1 ); wordPicker = new QIMPenWordPick( this ); - connect( wordPicker, SIGNAL(wordClicked(const QString &)), - this, SLOT(wordPicked(const QString &)) ); - connect( matcher, SIGNAL(matchedCharacters(const QIMPenCharMatchList &)), - this, SLOT(matchedCharacters(const QIMPenCharMatchList &)) ); + connect( wordPicker, SIGNAL(wordClicked(const QString&)), + this, SLOT(wordPicked(const QString&)) ); + connect( matcher, SIGNAL(matchedCharacters(const QIMPenCharMatchList&)), + this, SLOT(matchedCharacters(const QIMPenCharMatchList&)) ); connect( matcher, SIGNAL(matchedWords(const QIMPenMatch::MatchWordList&)), wordPicker, SLOT(setWords(const QIMPenMatch::MatchWordList&)) ); QFont f("smallsmooth",9); QFontInfo fi( f ); wordPicker->setFont( f ); wordPicker->setBackgroundColor( white ); gl->addMultiCellWidget( wordPicker, 0, 0, 0, 1 ); if ( !Global::fixedDawg().root() || !matcher->isWordMatchingEnabled() ) wordPicker->hide(); pw = new QIMPenWidget( this ); gl->addMultiCellWidget( pw, 1, 4, 0, 0 ); int bh = pw->sizeHint().height()/4; QPushButton *b = new QPushButton( this ); b->setFocusPolicy( NoFocus ); b->setPixmap( QPixmap( (const char **)bs_xpm ) ); b->setFixedHeight(pw->sizeHint().height()-3*bh); // left-over space goes here b->setAutoRepeat( TRUE ); gl->addWidget( b, 1, 1 ); connect( b, SIGNAL(clicked()), SLOT(backspace())); b = new QPushButton( this ); b->setFocusPolicy( NoFocus ); b->setPixmap( QPixmap( (const char **)enter_xpm ) ); b->setFixedHeight(bh); b->setAutoRepeat( TRUE ); gl->addWidget( b, 2, 1 ); connect( b, SIGNAL(clicked()), SLOT(enter())); helpBtn = new QPushButton( this ); helpBtn->setFocusPolicy( NoFocus ); helpBtn->setPixmap( QPixmap( (const char **)help_xpm ) ); helpBtn->setFixedHeight(bh); gl->addWidget( helpBtn, 3, 1 ); connect( helpBtn, SIGNAL(clicked()), SLOT(help())); QPixmap pm( (const char **)pen_xpm ); setupBtn = new QPushButton( this ); setupBtn->setFocusPolicy( NoFocus ); setupBtn->setPixmap( pm ); setupBtn->setFixedHeight(bh); gl->addWidget( setupBtn, 4, 1 ); connect( setupBtn, SIGNAL(clicked()), SLOT(setup())); connect( matcher, SIGNAL(removeStroke()), pw, SLOT(removeStroke()) ); - connect( pw, SIGNAL(changeCharSet( QIMPenCharSet * )), - matcher, SLOT(setCharSet( QIMPenCharSet * )) ); - connect( pw, SIGNAL(changeCharSet( int )), - this, SLOT(selectCharSet( int )) ); + connect( pw, SIGNAL(changeCharSet(QIMPenCharSet*)), + matcher, SLOT(setCharSet(QIMPenCharSet*)) ); + connect( pw, SIGNAL(changeCharSet(int)), + this, SLOT(selectCharSet(int)) ); connect( pw, SIGNAL(beginStroke()), matcher, SLOT(beginStroke()) ); - connect( pw, SIGNAL(stroke( QIMPenStroke * )), - this, SLOT(strokeEntered( QIMPenStroke * )) ); - connect( pw, SIGNAL(stroke( QIMPenStroke * )), - matcher, SLOT(strokeEntered( QIMPenStroke * )) ); + connect( pw, SIGNAL(stroke(QIMPenStroke*)), + this, SLOT(strokeEntered(QIMPenStroke*)) ); + connect( pw, SIGNAL(stroke(QIMPenStroke*)), + matcher, SLOT(strokeEntered(QIMPenStroke*)) ); shortcutCharSet = 0; currCharSet = 0; setupDlg = 0; profile = 0; mode = Normal; loadProfiles(); } QIMPenInput::~QIMPenInput() { delete (HandwritingHelp*) helpDlg; } QSize QIMPenInput::sizeHint() const { int fw = frameWidth(); int ps = wordPicker->isHidden() ? 0 : wordPicker->sizeHint().height(); return pw->sizeHint() + QSize( fw*2, fw*2+ps ); } void QIMPenInput::loadProfiles() { profileList.clear(); profile = 0; delete shortcutCharSet; shortcutCharSet = new QIMPenCharSet(); shortcutCharSet->setTitle( tr("Shortcut") ); QString path = QPEApplication::qpeDir() + "etc/qimpen"; QDir dir( path, "*.conf" ); QStringList list = dir.entryList(); QStringList::Iterator it; for ( it = list.begin(); it != list.end(); ++it ) { QIMPenProfile *p = new QIMPenProfile( path + "/" + *it ); profileList.append( p ); if ( p->shortcut() ) { QIMPenCharIterator it( p->shortcut()->characters() ); for ( ; it.current(); ++it ) { shortcutCharSet->addChar( new QIMPenChar(*it.current()) ); } } } Config config( "handwriting" ); config.setGroup( "Settings" ); QString prof = config.readEntry( "Profile", "Default" ); selectProfile( prof ); } void QIMPenInput::selectProfile( const QString &name ) { QListIterator<QIMPenProfile> it( profileList ); for ( ; it.current(); ++it ) { if ( it.current()->name() == name ) { profile = it.current(); break; } } if ( !it.current() ) return; pw->clearCharSets(); baseSets.clear(); matcher->setMultiStrokeTimeout( profile->multiStrokeTimeout() ); matcher->setWordMatchingEnabled( profile->matchWords() ); if ( !Global::fixedDawg().root() || !matcher->isWordMatchingEnabled() ) wordPicker->hide(); else wordPicker->show(); if ( profile->uppercase() && profile->style() == QIMPenProfile::BothCases ) { baseSets.append( profile->uppercase() ); pw->insertCharSet( profile->uppercase() ); } if ( profile->lowercase() ) { baseSets.append( profile->lowercase() ); pw->insertCharSet( profile->lowercase(), profile->style() == QIMPenProfile::BothCases ? 1 : 2 ); } if ( profile->numeric() ) { baseSets.append( profile->numeric() ); pw->insertCharSet( profile->numeric() ); } if ( helpDlg ) delete (HandwritingHelp*) helpDlg; } void QIMPenInput::wordPicked( const QString &w ) { int bs = matcher->word().length(); for ( int i = 0; i < bs; i++ ) keypress( Qt::Key_Backspace << 16 ); for ( unsigned int i = 0; i < w.length(); i++ ) keypress( w[i].unicode() ); matcher->resetState(); wordPicker->clear(); } void QIMPenInput::selectCharSet( int idx ) { if ( mode == Switch ) { //qDebug( "Switch back to normal" ); pw->changeCharSet( baseSets.at(currCharSet), currCharSet ); mode = Normal; } currCharSet = idx; } void QIMPenInput::beginStroke() { } void QIMPenInput::strokeEntered( QIMPenStroke * ) { pw->greyStroke(); } void QIMPenInput::erase() { keypress( Qt::Key_Backspace << 16 ); } void QIMPenInput::matchedCharacters( const QIMPenCharMatchList &cl ) { const QIMPenChar *ch = cl.first().penChar; int scan = ch->character() >> 16; if ( scan < QIMPenChar::ModeBase ) return; // We matched a special character... switch ( scan ) { case QIMPenChar::Caps: if ( profile->style() == QIMPenProfile::ToggleCases ) { // qDebug( "Caps" ); if ( mode == SwitchLock ) { // qDebug( "Switch to normal" ); pw->changeCharSet( profile->lowercase(), currCharSet ); mode = Switch; } else { // qDebug( "Switch to upper" ); pw->changeCharSet( profile->uppercase(), currCharSet ); mode = Switch; } } break; case QIMPenChar::CapsLock: if ( profile->style() == QIMPenProfile::ToggleCases ) { // qDebug( "CapsLock" ); if ( mode == Switch && baseSets.at(currCharSet) == profile->uppercase() ) { // qDebug( "Switch to normal" ); pw->changeCharSet( profile->lowercase(), currCharSet ); // change our base set back to lower. baseSets.remove( currCharSet ); baseSets.insert( currCharSet, profile->lowercase() ); mode = Normal; } else { // qDebug( "Switch to caps lock" ); pw->changeCharSet( profile->uppercase(), currCharSet ); // change our base set to upper. baseSets.remove( currCharSet ); baseSets.insert( currCharSet, profile->uppercase() ); mode = SwitchLock; } } break; case QIMPenChar::Punctuation: if ( profile->punctuation() ) { //qDebug( "Switch to punctuation" ); pw->changeCharSet( profile->punctuation(), currCharSet ); mode = Switch; } break; case QIMPenChar::Symbol: if ( profile->symbol() ) { //qDebug( "Switch to symbol" ); pw->changeCharSet( profile->symbol(), currCharSet ); mode = Switch; } break; case QIMPenChar::Shortcut: if ( shortcutCharSet ) { diff --git a/inputmethods/handwriting/qimpensetup.cpp b/inputmethods/handwriting/qimpensetup.cpp index d0f9ffd..d1297a9 100644 --- a/inputmethods/handwriting/qimpensetup.cpp +++ b/inputmethods/handwriting/qimpensetup.cpp @@ -1,536 +1,536 @@ /********************************************************************** ** Copyright (C) 2000-2002 Trolltech AS. All rights reserved. ** ** This file is part of the Qtopia Environment. ** ** This file may be distributed and/or modified under the terms of the ** GNU General Public License version 2 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. ** ** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE ** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. ** ** See http://www.trolltech.com/gpl/ for GPL licensing information. ** ** Contact info@trolltech.com if any conditions of this licensing are ** not clear to you. ** **********************************************************************/ #include "qimpenwidget.h" #include "qimpenprefbase.h" #include "qimpensetup.h" #include <qpe/qpeapplication.h> #include <qpe/config.h> #include <qcombobox.h> #include <qlistbox.h> #include <qlabel.h> #include <qpushbutton.h> #include <qlayout.h> #include <qpixmap.h> #include <qbuttongroup.h> #include <qslider.h> #include <qtabwidget.h> #include <qdir.h> #include <qmessagebox.h> /* XPM */ static const char * const left_xpm[] = { "16 16 2 1", " c None", ". c #000000", " ", " ", " ", " . ", " .. ", " ... ", " .... ", " ..... ", " ...... ", " ..... ", " .... ", " ... ", " .. ", " . ", " ", " "}; /* XPM */ static const char * const right_xpm[] = { "16 16 2 1", " c None", ". c #000000", " ", " ", " ", " . ", " .. ", " ... ", " .... ", " ..... ", " ...... ", " ..... ", " .... ", " ... ", " .. ", " . ", " ", " "}; QIMPenSetup::QIMPenSetup( QIMPenProfile *p, QWidget *parent, const char *name, bool modal, int WFlags ) : QDialog( parent, name, modal, WFlags ), profileCombo(0), profile(p) { setCaption( tr("Setup Handwriting Input") ); QVBoxLayout *vb = new QVBoxLayout( this ); #define MULTIPROFILE #ifdef MULTIPROFILE profileList.setAutoDelete( true ); QHBoxLayout *hb = new QHBoxLayout( vb ); hb->setMargin( 6 ); QLabel *l = new QLabel( tr("Character Profile:"), this ); hb->addWidget( l ); profileCombo = new QComboBox( this ); - connect( profileCombo, SIGNAL(activated(const QString &)), - this, SLOT(selectProfile(const QString &)) ); + connect( profileCombo, SIGNAL(activated(const QString&)), + this, SLOT(selectProfile(const QString&)) ); hb->addWidget( profileCombo ); #else profileList.append( profile ); #endif qWarning("profiles: %d", profileList.count()); QTabWidget *tw = new QTabWidget( this ); vb->addWidget( tw ); pref = new QIMPenPrefBase( this ); tw->addTab( pref, tr("Preferences") ); pref->inputStyle->setExclusive( TRUE ); style = profile->style() == QIMPenProfile::ToggleCases ? 1 : 0; pref->inputStyle->setButton( style ); connect( pref->inputStyle, SIGNAL(clicked(int)), this, SLOT(styleClicked(int)) ); pref->inputStyle->setEnabled( profile->canSelectStyle() ); multiTimeout = profile->multiStrokeTimeout(); pref->multiStrokeSlider->setValue( multiTimeout ); multiTimeoutChanged( multiTimeout ); connect( pref->multiStrokeSlider, SIGNAL(valueChanged(int)), this, SLOT(multiTimeoutChanged(int)) ); edit = new QIMPenEdit( p, tw ); tw->addTab( edit, tr("Customize") ); #ifdef MULTIPROFILE loadProfiles(); #endif } void QIMPenSetup::loadProfiles() { QString path = QPEApplication::qpeDir() + "etc/qimpen"; QDir dir( path, "*.conf" ); QStringList list = dir.entryList(); QStringList::Iterator it; for ( it = list.begin(); it != list.end(); ++it ) { QIMPenProfile *p = new QIMPenProfile( path + "/" + *it ); profileList.append( p ); profileCombo->insertItem( p->name() ); if ( p->name() == profile->name() ) { profileCombo->setCurrentItem( profileCombo->count()-1 ); profile = p; edit->setProfile( profile ); } } } void QIMPenSetup::styleClicked( int id ) { style = id; } void QIMPenSetup::multiTimeoutChanged( int v ) { multiTimeout = v; pref->multiStrokeLabel->setText( tr("%1 ms").arg(v) ); } void QIMPenSetup::selectProfile( const QString &p ) { if ( p == profile->name() ) return; profile->setStyle( style ? QIMPenProfile::ToggleCases : QIMPenProfile::BothCases ); profile->setMultiStrokeTimeout( multiTimeout ); for ( int i = 0; i < (int)profileList.count(); i++ ) { if ( profileList.at(i)->name() == p ) { profile = profileList.at(i); style = profile->style() == QIMPenProfile::ToggleCases ? 1 : 0; pref->inputStyle->setButton( style ); pref->inputStyle->setEnabled( profile->canSelectStyle() ); multiTimeout = profile->multiStrokeTimeout(); pref->multiStrokeSlider->setValue( multiTimeout ); multiTimeoutChanged( multiTimeout ); edit->setProfile( profile ); break; } } } void QIMPenSetup::accept() { profile->setStyle( style ? QIMPenProfile::ToggleCases : QIMPenProfile::BothCases ); profile->setMultiStrokeTimeout( multiTimeout ); // Save current profile if ( profileCombo ) { Config config( "handwriting" ); config.setGroup( "Settings" ); config.writeEntry( "Profile", profileCombo->currentText() ); } // Save charsets bool ok = TRUE; for ( int i = 0; i < (int)profileList.count(); i++ ) { QIMPenProfile *prof = profileList.at(i); QIMPenCharSetIterator it(prof->charSets()); for ( ; it.current(); ++it ) { if ( !(it.current()->save( QIMPenCharSet::User )) ) { ok = FALSE; break; } } } if ( !ok ) { if ( QMessageBox::critical( 0, tr( "Out of space" ), tr("Unable to save information.\n" "Free up some space\n" "and try again.\n" "\nQuit anyway?"), QMessageBox::Yes|QMessageBox::Escape, QMessageBox::No|QMessageBox::Default ) != QMessageBox::No ) { QDialog::accept(); } } else { QDialog::accept(); } } //--------------------------------------------------------------------------- QIMPenInputCharDlg::QIMPenInputCharDlg( QWidget *parent, const char *name, bool modal, int WFlags) : QDialog( parent, name, modal, WFlags ) { setCaption( tr("Enter new character") ); uni = 0; QVBoxLayout *vb = new QVBoxLayout( this, 10 ); QHBoxLayout *hb = new QHBoxLayout(); vb->addLayout( hb ); QLabel *label = new QLabel( tr("Character:"), this ); hb->addWidget( label ); QComboBox *cb = new QComboBox( TRUE, this ); connect( cb, SIGNAL(activated(int)), SLOT(setSpecial(int)) ); - connect( cb, SIGNAL(textChanged(const QString &)), - SLOT(setCharacter(const QString &)) ); + connect( cb, SIGNAL(textChanged(const QString&)), + SLOT(setCharacter(const QString&)) ); addSpecial( cb ); cb->setEditText( "" ); hb->addWidget( cb ); hb = new QHBoxLayout(); vb->addLayout( hb ); QPushButton *pb = new QPushButton( "OK", this ); connect( pb, SIGNAL(clicked()), SLOT(accept())); hb->addWidget( pb ); pb = new QPushButton( "Cancel", this ); connect( pb, SIGNAL(clicked()), SLOT(reject())); hb->addWidget( pb ); cb->setFocus(); } void QIMPenInputCharDlg::addSpecial( QComboBox *cb ) { int i = 0; while ( qimpen_specialKeys[i].code != Key_unknown ) { cb->insertItem( qimpen_specialKeys[i].name ); i++; } } void QIMPenInputCharDlg::setSpecial( int sp ) { uni = qimpen_specialKeys[sp].code << 16; } void QIMPenInputCharDlg::setCharacter( const QString &string ) { uni = string[0].unicode(); } //--------------------------------------------------------------------------- class CharListItem : public QListBoxText { public: CharListItem( const QString &text, uint c ) : QListBoxText( text ) { _code = c; } uint code() const { return _code; } protected: uint _code; }; /*! \class QIMPenEdit qimpensetup.h Class to allow users to input totally useless character definitions which could match any number of the default set. */ QIMPenEdit::QIMPenEdit( QIMPenProfile *p, QWidget *parent, const char *name ) : QWidget( parent, name ), profile(p) { currentChar = 0; currentCode = 0; inputChar = new QIMPenChar(); QVBoxLayout *tvb = new QVBoxLayout( this, 5 ); QGridLayout *gl = new QGridLayout( tvb, 4, 2 ); gl->setRowStretch( 1, 1 ); gl->addRowSpacing( 2, 35 ); gl->addRowSpacing( 3, 35 ); charSetCombo = new QComboBox( this ); gl->addMultiCellWidget( charSetCombo, 0, 0, 0, 1 ); connect( charSetCombo, SIGNAL(activated(int)), SLOT(selectCharSet(int))); QIMPenCharSetIterator it( profile->charSets() ); for ( ; it.current(); ++it ) { charSetCombo->insertItem( it.current()->description() ); } charList = new QListBox( this ); charList->setMinimumHeight( charList->sizeHint().height() ); connect( charList, SIGNAL(highlighted(int)), SLOT(selectChar(int)) ); gl->addWidget( charList, 1, 0 ); pw = new QIMPenWidget( this ); pw->setFixedHeight( 75 ); gl->addMultiCellWidget( pw, 2, 3, 0, 0 ); - connect( pw, SIGNAL(stroke(QIMPenStroke *)), - SLOT(newStroke(QIMPenStroke *)) ); + connect( pw, SIGNAL(stroke(QIMPenStroke*)), + SLOT(newStroke(QIMPenStroke*)) ); QVBoxLayout *vb = new QVBoxLayout(); gl->addLayout( vb, 1, 1 ); newBtn = new QPushButton( tr("New..."), this ); connect( newBtn, SIGNAL(clicked()), SLOT(addNewChar()) ); vb->addWidget( newBtn ); addBtn = new QPushButton( tr("Add"), this ); connect( addBtn, SIGNAL(clicked()), SLOT(addChar()) ); vb->addWidget( addBtn ); removeBtn = new QPushButton( tr("Remove"), this ); connect( removeBtn, SIGNAL(clicked()), SLOT(removeChar()) ); vb->addWidget( removeBtn ); QPushButton *pb = new QPushButton( tr("Default"), this ); connect( pb, SIGNAL(clicked()), SLOT(defaultChars()) ); vb->addWidget( pb ); QHBoxLayout *hb = new QHBoxLayout(); gl->addLayout( hb, 2, 1 ); prevBtn = new QPushButton( this ); prevBtn->setPixmap( QPixmap( (const char **)left_xpm ) ); connect( prevBtn, SIGNAL(clicked()), SLOT(prevChar())); hb->addWidget( prevBtn ); nextBtn = new QPushButton( this ); nextBtn->setPixmap( QPixmap( (const char **)right_xpm ) ); connect( nextBtn, SIGNAL(clicked()), SLOT(nextChar())); hb->addWidget( nextBtn ); pb = new QPushButton( tr("Clear"), this ); connect( pb, SIGNAL(clicked()), SLOT(clearChar()) ); gl->addWidget( pb, 3, 1 ); //-- #if !defined(Q_WS_QWS) hb = new QHBoxLayout( tvb ); pb = new QPushButton( tr("OK"), this ); connect( pb, SIGNAL(clicked()), SLOT(accept()) ); hb->addWidget( pb ); pb = new QPushButton( tr("Cancel"), this ); connect( pb, SIGNAL(clicked()), SLOT(reject()) ); hb->addWidget( pb ); #endif selectCharSet( 0 ); charList->setFocus(); resize( minimumSize() ); enableButtons(); } void QIMPenEdit::setProfile( QIMPenProfile *p ) { profile = p; charSetCombo->clear(); QIMPenCharSetIterator it( profile->charSets() ); for ( ; it.current(); ++it ) { if ( ! it.current()->hidden() ) charSetCombo->insertItem( it.current()->description() ); } selectCharSet( 0 ); charList->setFocus(); enableButtons(); } void QIMPenEdit::selectCharSet( QIMPenCharSet *c ) { int i = 0; QIMPenCharSetIterator it( profile->charSets() ); for ( ; it.current(); ++it, i++ ) { if ( it.current() == c ) { charSetCombo->setCurrentItem( i ); selectCharSet( i ); } } } /*! Fill the character list box with the characters. Duplicates are not inserted. */ void QIMPenEdit::fillCharList() { charList->clear(); QIMPenCharIterator it( currentSet->characters() ); CharListItem *li = 0; for ( ; it.current(); ++it ) { uint ch = it.current()->character(); QString n = it.current()->name(); if ( !n.isEmpty() ) li = new CharListItem( n, ch ); if ( li ) { CharListItem *i = (CharListItem *)charList->findItem( li->text() ); if ( !i || i->code() != ch ) { charList->insertItem( li ); } else { delete li; li = 0; } } } currentChar = 0; } void QIMPenEdit::enableButtons() { bool add = !inputChar->isEmpty(); newBtn->setEnabled( add ); addBtn->setEnabled( add ); removeBtn->setEnabled( currentChar ); } /*! Find the previous character with the same code as the current one. returns 0 if there is no previous character. */ QIMPenChar *QIMPenEdit::findPrev() { if ( !currentChar ) return 0; QIMPenCharIterator it( currentSet->characters() ); bool found = FALSE; for ( it.toLast(); it.current(); --it ) { if ( !found && it.current() == currentChar ) found = TRUE; else if ( found && it.current()->character() == currentCode && !it.current()->testFlag( QIMPenChar::Deleted ) ) { return it.current(); } } return 0; } /*! Find the next character with the same code as the current one. returns 0 if there is no next character. */ QIMPenChar *QIMPenEdit::findNext() { if ( !currentChar ) return 0; QIMPenCharIterator it( currentSet->characters() ); bool found = FALSE; for ( ; it.current(); ++it ) { if ( !found && it.current() == currentChar ) found = TRUE; else if ( found && it.current()->character() == currentCode && !it.current()->testFlag( QIMPenChar::Deleted ) ) { return it.current(); } } return 0; } void QIMPenEdit::setCurrentChar( QIMPenChar *pc ) { currentChar = pc; pw->showCharacter( currentChar ); if ( currentChar ) { prevBtn->setEnabled( findPrev() != 0 ); nextBtn->setEnabled( findNext() != 0 ); } } void QIMPenEdit::prevChar() { QIMPenChar *pc = findPrev(); if ( pc ) setCurrentChar( pc ); } void QIMPenEdit::nextChar() { QIMPenChar *pc = findNext(); if ( pc ) setCurrentChar( pc ); } void QIMPenEdit::clearChar() { inputChar->clear(); pw->clear(); enableButtons(); } void QIMPenEdit::selectChar( int i ) { diff --git a/inputmethods/multikey/keyboard.cpp b/inputmethods/multikey/keyboard.cpp index aec0ad3..4f4f25f 100644 --- a/inputmethods/multikey/keyboard.cpp +++ b/inputmethods/multikey/keyboard.cpp @@ -1,291 +1,291 @@ /********************************************************************** ** Copyright (C) 2000 Trolltech AS. All rights reserved. ** ** This file is part of Qtopia Environment. ** ** This file may be distributed and/or modified under the terms of the ** GNU General Public License version 2 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. ** ** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE ** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. ** ** See http://www.trolltech.com/gpl/ for GPL licensing information. ** ** Contact info@trolltech.com if any conditions of this licensing are ** not clear to you. ** **********************************************************************/ #include "keyboard.h" #include "configdlg.h" #include <qpe/global.h> #include <qpe/qcopenvelope_qws.h> #include <qwindowsystem_qws.h> #include <qpainter.h> #include <qfontmetrics.h> #include <qtimer.h> #include <qpe/qpeapplication.h> #include <qpe/config.h> #include <ctype.h> #include <qdir.h> #include <qtextstream.h> #include <qstringlist.h> #include <sys/utsname.h> using namespace MultiKey; static const char * const kb_config_xpm[] = { "13 7 2 1", " c None", ". c #000000", " ", " . ", " ... ", " ..... ", " . ", " . ", " "}; /* Keyboard::Keyboard {{{1 */ Keyboard::Keyboard(QWidget* parent, const char* _name, WFlags f) : QFrame(parent, _name, f), shift(0), lock(0), ctrl(0), alt(0), meta(0), circumflex(0), diaeresis(0), baccent(0), accent(0), useLargeKeys(TRUE), usePicks(0), useRepeat(0), pressedKeyRow(-1), pressedKeyCol(-1), unicode(-1), qkeycode(0), modifiers(0), schar(0), mchar(0), echar(0), configdlg(0) { // get the default font Config *config = new Config( "qpe" ); config->setGroup( "Appearance" ); QString familyStr = config->readEntry( "FontFamily", "smallsmooth" ); delete config; config = new Config("multikey"); config->setGroup ("general"); usePicks = config->readBoolEntry ("usePickboard", 0); // default closed useRepeat = config->readBoolEntry ("useRepeat", 1); delete config; setFont( QFont( familyStr, 10 ) ); picks = new KeyboardPicks( this ); picks->setFont( QFont( familyStr, 10 ) ); picks->initialise(); if (usePicks) { QObject::connect( picks, SIGNAL(key(ushort,ushort,ushort,bool,bool) ), this, SIGNAL(key(ushort,ushort,ushort,bool,bool)) ); } else picks->hide(); loadKeyboardColors(); keys = new Keys(); repeatTimer = new QTimer( this ); connect( repeatTimer, SIGNAL(timeout()), this, SLOT(repeat()) ); QCopChannel* kbdChannel = new QCopChannel("MultiKey/Keyboard", this); - connect(kbdChannel, SIGNAL(received(const QCString &, const QByteArray &)), - this, SLOT(receive(const QCString &, const QByteArray &))); + connect(kbdChannel, SIGNAL(received(const QCString&,const QByteArray&)), + this, SLOT(receive(const QCString&,const QByteArray&))); } Keyboard::~Keyboard() { if ( configdlg ) { delete configdlg; configdlg = 0; } } /* Keyboard::resizeEvent {{{1 */ void Keyboard::resizeEvent(QResizeEvent*) { int ph = picks->sizeHint().height(); picks->setGeometry( 0, 0, width(), ph ); keyHeight = (height()-(usePicks ? ph : 0))/(keys->rows()?keys->rows():1); int nk; // number of keys? if ( useLargeKeys ) { nk = 15; } else { nk = 19; } defaultKeyWidth = (width()/nk)/2; xoffs = (width()-defaultKeyWidth*nk)/2; // empty key spaces? } /* KeyboardPicks::initialize {{{1 */ void KeyboardPicks::initialise() { setSizePolicy(QSizePolicy(QSizePolicy::Expanding,QSizePolicy::Fixed)); mode = 0; dc = new KeyboardConfig(this); configs.append(dc); } /* KeyboardPicks::sizeHint {{{1 */ QSize KeyboardPicks::sizeHint() const { return QSize(240,fontMetrics().lineSpacing()); } /* KeyboardConfig::generateText {{{1 */ void KeyboardConfig::generateText(const QString &s) { #if defined(Q_WS_QWS) || defined(_WS_QWS_) for (int i=0; i<(int)backspaces; i++) { parent->emitKey( 0, Qt::Key_Backspace, 0, true, false ); parent->emitKey( 0, Qt::Key_Backspace, 0, false, false ); } for (int i=0; i<(int)s.length(); i++) { parent->emitKey( s[i].unicode(), 0, 0, true, false ); parent->emitKey( s[i].unicode(), 0, 0, false, false ); } parent->emitKey( 0, Qt::Key_Space, 0, true, false ); parent->emitKey( 0, Qt::Key_Space, 0, false, false ); backspaces = 0; #endif } /* Keyboard::paintEvent {{{1 */ void Keyboard::paintEvent(QPaintEvent* e) { QPainter painter(this); painter.setClipRect(e->rect()); drawKeyboard( painter ); picks->dc->draw( &painter ); } /* Keyboard::drawKeyboard {{{1 */ void Keyboard::drawKeyboard(QPainter &p, int row, int col) { if (row != -1 && col != -1) { //just redraw one key int x = 0; for (int i = 0; i < col; i++) { x += keys->width(row, i) * defaultKeyWidth; } int y = (row - 1) * keyHeight + (usePicks ? picks->height() : 0); int keyWidth = keys->width(row, col); p.fillRect(x + 1, y + 1, keyWidth * defaultKeyWidth - 1, keyHeight - 1, pressed || keys->pressed(row, col) ? keycolor_pressed : keycolor); QImage *pix = keys->pix(row,col); ushort c = keys->uni(row, col); p.setPen(textcolor); if (!pix) { if ((shift || lock) && keys->shift(c)) if (circumflex && keys->circumflex(keys->shift(c))) c = keys->circumflex(keys->shift(c)); else if (diaeresis && keys->diaeresis(keys->shift(c))) c = keys->diaeresis(keys->shift(c)); else if (baccent && keys->baccent(keys->shift(c))) c = keys->baccent(keys->shift(c)); else if (accent && keys->accent(keys->shift(c))) c = keys->accent(keys->shift(c)); else if (meta && keys->meta(keys->shift(c))) c = keys->meta(keys->shift(c)); else c = keys->shift(c); else if (meta && keys->meta(c)) c = keys->meta(c); else if (circumflex && keys->circumflex(c)) c = keys->circumflex(c); else if (baccent && keys->baccent(c)) c = keys->baccent(c); else if (accent && keys->accent(c)) c = keys->accent(c); else if (diaeresis && (keys->diaeresis(c) || c == 0x2c6)) { // the diaeresis key itself has to be in the diaeresisMap, // or just do this to make it display the diaeresis char. if (c == 0x2c6) c = 0xa8; else c = keys->diaeresis(c); } p.drawText(x, y, defaultKeyWidth * keyWidth + 3, keyHeight, AlignCenter, (QChar)c); } else // center the image in the middle of the key p.drawImage( x + (defaultKeyWidth * keyWidth - pix->width())/2 + 1, y + (keyHeight - pix->height())/2 + 1, *pix ); // this fixes the problem that the very right end of the board's vertical line // gets painted over, because it's one pixel shorter than all other keys p.setPen(keycolor_lines); p.drawLine(width() - 1, 0, width() - 1, height()); } else { p.fillRect(0, 0, width(), height(), keycolor); for (row = 1; row <= keys->rows(); row++) { int x = 0; int y = (row - 1) * keyHeight + (usePicks ? picks->height() : 0); p.setPen(keycolor_lines); p.drawLine(x, y, x + width(), y); for (int col = 0; col < keys->numKeys(row); col++) { QImage *pix = keys->pix(row, col); int keyWidth = keys->width(row, col); int keyWidthPix = defaultKeyWidth * keyWidth; if (keys->pressed(row, col)) p.fillRect(x+1, y+1, keyWidthPix - 1, keyHeight - 1, keycolor_pressed); ushort c = keys->uni(row, col); p.setPen(textcolor); if (!pix) { if ((shift || lock) && keys->shift(c)) if (circumflex && keys->circumflex(keys->shift(c))) c = keys->circumflex(keys->shift(c)); else if (diaeresis && keys->diaeresis(keys->shift(c))) c = keys->diaeresis(keys->shift(c)); else if (baccent && keys->baccent(keys->shift(c))) c = keys->baccent(keys->shift(c)); else if (accent && keys->accent(keys->shift(c))) c = keys->accent(keys->shift(c)); else if (meta && keys->meta(keys->shift(c))) diff --git a/libopie/big-screen/example/osplitter_mail.cpp b/libopie/big-screen/example/osplitter_mail.cpp index 4eaf3a9..4356baa 100644 --- a/libopie/big-screen/example/osplitter_mail.cpp +++ b/libopie/big-screen/example/osplitter_mail.cpp @@ -1,82 +1,82 @@ #include <qstring.h> #include <qlabel.h> #include <qheader.h> #include <qlayout.h> #include <qpe/qpeapplication.h> #include <opie/oapplicationfactory.h> #include "../osplitter.h" #include "osplitter_mail.h" OPIE_EXPORT_APP( OApplicationFactory<ListViews> ) class Folder { int dummy; }; // ----------------------------------------------------------------- ListViews::ListViews( QWidget* p, const char* name, WFlags fl ) : QWidget( p, name, fl ) { qApp->installEventFilter( this ); m_lstFolders.setAutoDelete( true ); QHBoxLayout *lay = new QHBoxLayout(this); m_splitter = new OSplitter( Horizontal, this, "SPlitter 1" ); lay->addWidget( m_splitter ); - connect(m_splitter, SIGNAL(sizeChange(bool, const QSize& ) ), - this, SLOT(slotSizeChange(bool, const QSize& ) ) ); + connect(m_splitter, SIGNAL(sizeChange(bool,const QSize&) ), + this, SLOT(slotSizeChange(bool,const QSize&) ) ); m_overview = new QListView( m_splitter ); m_overview->header()->setClickEnabled( FALSE ); m_overview->addColumn( tr("Folder") ); m_overview->setMaximumWidth( 200 ); m_splitter->addWidget( m_overview, "zoom", tr("Folder Overview") ); m_splitter->setSizeChange( 300 ); /* OSplitter starts with the small mode */ m_messages = 0; m_message = m_attach = 0; splitti = new OSplitter( Vertical, m_splitter, "Splitti2" ); splitti->setSizeChange( 300 ); splitti->setSizePolicy( QSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding ) ); QLabel *lbl = new QLabel(splitti); lbl->setTextFormat ( Qt::RichText ); lbl->setText("<br><br><b>Test Test Test</b><br><br><p>Fooooo hjhh</p>"); m_messages = new QListView( splitti ); m_messages->addColumn(" Messages "); folder1 = new QListView( splitti ); folder1->addColumn( "Messages 2 " ); splitti->addWidget(m_messages, "mail", tr("Mails") ); splitti->addWidget(folder1, "folder", tr("Folder") ); splitti->addWidget( lbl, "logo", tr("Label") ); m_message = lbl; m_splitter->addWidget( splitti ); } ListViews::~ListViews() { } bool ListViews::eventFilter( QObject* obj, QEvent* ev ) { if (!obj->isWidgetType() ) return false; if ( ev->type() == QEvent::MouseButtonRelease ) { qWarning(" name %s, class %s", obj->name(), obj->className() ); } return false; } diff --git a/libopie/colordialog.cpp b/libopie/colordialog.cpp index d46da41..b2854a6 100644 --- a/libopie/colordialog.cpp +++ b/libopie/colordialog.cpp @@ -283,388 +283,388 @@ void QColorPicker::setCol( int h, int s ) } void QColorPicker::mouseMoveEvent( QMouseEvent *m ) { QPoint p = m->pos() - contentsRect().topLeft(); setCol( p ); emit newCol( hue, sat ); } void QColorPicker::mousePressEvent( QMouseEvent *m ) { QPoint p = m->pos() - contentsRect().topLeft(); setCol( p ); emit newCol( hue, sat ); } void QColorPicker::drawContents(QPainter* p) { QRect r = contentsRect(); p->drawPixmap( r.topLeft(), *pix ); QPoint pt = colPt() + r.topLeft(); p->setPen( QPen(black) ); p->fillRect( pt.x()-9, pt.y(), 20, 2, black ); p->fillRect( pt.x(), pt.y()-9, 2, 20, black ); } class QColorShowLabel; class QColIntValidator: public QIntValidator { public: QColIntValidator( int bottom, int top, QWidget * parent, const char *name = 0 ) :QIntValidator( bottom, top, parent, name ) {} QValidator::State validate( QString &, int & ) const; }; QValidator::State QColIntValidator::validate( QString &s, int &pos ) const { State state = QIntValidator::validate(s,pos); if ( state == Valid ) { long int val = s.toLong(); // This is not a general solution, assumes that top() > 0 and // bottom >= 0 if ( val < 0 ) { s = "0"; pos = 1; } else if ( val > top() ) { s.setNum( top() ); pos = s.length(); } } return state; } class QColNumLineEdit : public QLineEdit { public: QColNumLineEdit( QWidget *parent, const char* name = 0 ) : QLineEdit( parent, name ) { setMaxLength( 3 );} QSize sizeHint() const { return QSize( 30, //##### QLineEdit::sizeHint().height() ); } void setNum( int i ) { QString s; s.setNum(i); bool block = signalsBlocked(); blockSignals(TRUE); setText( s ); blockSignals(block); } int val() const { return text().toInt(); } }; class QColorShower : public QWidget { Q_OBJECT public: QColorShower( QWidget *parent, const char *name = 0 ); //things that don't emit signals void setHsv( int h, int s, int v ); int currentAlpha() const { return alphaEd->val(); } void setCurrentAlpha( int a ) { alphaEd->setNum( a ); } void showAlpha( bool b ); QRgb currentColor() const { return curCol; } public slots: void setRgb( QRgb rgb ); signals: void newCol( QRgb rgb ); private slots: void rgbEd(); void hsvEd(); private: void showCurrentColor(); int hue, sat, val; QRgb curCol; QColNumLineEdit *hEd; QColNumLineEdit *sEd; QColNumLineEdit *vEd; QColNumLineEdit *rEd; QColNumLineEdit *gEd; QColNumLineEdit *bEd; QColNumLineEdit *alphaEd; QLabel *alphaLab; QColorShowLabel *lab; bool rgbOriginal; }; class QColorShowLabel : public QFrame { Q_OBJECT public: QColorShowLabel( QWidget *parent ) :QFrame( parent ) { setFrameStyle( QFrame::Panel|QFrame::Sunken ); setBackgroundMode( PaletteBackground ); setAcceptDrops( TRUE ); mousePressed = FALSE; } void setColor( QColor c ) { col = c; } signals: void colorDropped( QRgb ); protected: void drawContents( QPainter *p ); void mousePressEvent( QMouseEvent *e ); void mouseReleaseEvent( QMouseEvent *e ); private: QColor col; bool mousePressed; QPoint pressPos; }; void QColorShowLabel::drawContents( QPainter *p ) { p->fillRect( contentsRect(), col ); } void QColorShower::showAlpha( bool b ) { if ( b ) { alphaLab->show(); alphaEd->show(); } else { alphaLab->hide(); alphaEd->hide(); } } void QColorShowLabel::mousePressEvent( QMouseEvent *e ) { mousePressed = TRUE; pressPos = e->pos(); } void QColorShowLabel::mouseReleaseEvent( QMouseEvent * ) { if ( !mousePressed ) return; mousePressed = FALSE; } QColorShower::QColorShower( QWidget *parent, const char *name ) :QWidget( parent, name) { curCol = qRgb( -1, -1, -1 ); QColIntValidator *val256 = new QColIntValidator( 0, 255, this ); QColIntValidator *val360 = new QColIntValidator( 0, 360, this ); QGridLayout *gl = new QGridLayout( this, 1, 1, 2 ); gl->setMargin( 0 ); lab = new QColorShowLabel( this ); lab->setMinimumWidth( 60 ); //### gl->addMultiCellWidget(lab, 0,-1,0,0); - connect( lab, SIGNAL( colorDropped( QRgb ) ), - this, SIGNAL( newCol( QRgb ) ) ); - connect( lab, SIGNAL( colorDropped( QRgb ) ), - this, SLOT( setRgb( QRgb ) ) ); + connect( lab, SIGNAL( colorDropped(QRgb) ), + this, SIGNAL( newCol(QRgb) ) ); + connect( lab, SIGNAL( colorDropped(QRgb) ), + this, SLOT( setRgb(QRgb) ) ); hEd = new QColNumLineEdit( this ); hEd->setValidator( val360 ); QLabel *l = new QLabel( hEd, OColorDialog::tr("Hue:"), this ); l->setAlignment( AlignRight|AlignVCenter ); gl->addWidget( l, 0, 1 ); gl->addWidget( hEd, 0, 2 ); sEd = new QColNumLineEdit( this ); sEd->setValidator( val256 ); l = new QLabel( sEd, OColorDialog::tr("Sat:"), this ); l->setAlignment( AlignRight|AlignVCenter ); gl->addWidget( l, 1, 1 ); gl->addWidget( sEd, 1, 2 ); vEd = new QColNumLineEdit( this ); vEd->setValidator( val256 ); l = new QLabel( vEd, OColorDialog::tr("Val:"), this ); l->setAlignment( AlignRight|AlignVCenter ); gl->addWidget( l, 2, 1 ); gl->addWidget( vEd, 2, 2 ); rEd = new QColNumLineEdit( this ); rEd->setValidator( val256 ); l = new QLabel( rEd, OColorDialog::tr("Red:"), this ); l->setAlignment( AlignRight|AlignVCenter ); gl->addWidget( l, 0, 3 ); gl->addWidget( rEd, 0, 4 ); gEd = new QColNumLineEdit( this ); gEd->setValidator( val256 ); l = new QLabel( gEd, OColorDialog::tr("Green:"), this ); l->setAlignment( AlignRight|AlignVCenter ); gl->addWidget( l, 1, 3 ); gl->addWidget( gEd, 1, 4 ); bEd = new QColNumLineEdit( this ); bEd->setValidator( val256 ); l = new QLabel( bEd, OColorDialog::tr("Blue:"), this ); l->setAlignment( AlignRight|AlignVCenter ); gl->addWidget( l, 2, 3 ); gl->addWidget( bEd, 2, 4 ); alphaEd = new QColNumLineEdit( this ); alphaEd->setValidator( val256 ); alphaLab = new QLabel( alphaEd, OColorDialog::tr("Alpha channel:"), this ); alphaLab->setAlignment( AlignRight|AlignVCenter ); gl->addMultiCellWidget( alphaLab, 3, 3, 1, 3 ); gl->addWidget( alphaEd, 3, 4 ); alphaEd->hide(); alphaLab->hide(); connect( hEd, SIGNAL(textChanged(const QString&)), this, SLOT(hsvEd()) ); connect( sEd, SIGNAL(textChanged(const QString&)), this, SLOT(hsvEd()) ); connect( vEd, SIGNAL(textChanged(const QString&)), this, SLOT(hsvEd()) ); connect( rEd, SIGNAL(textChanged(const QString&)), this, SLOT(rgbEd()) ); connect( gEd, SIGNAL(textChanged(const QString&)), this, SLOT(rgbEd()) ); connect( bEd, SIGNAL(textChanged(const QString&)), this, SLOT(rgbEd()) ); } void QColorShower::showCurrentColor() { lab->setColor( currentColor() ); lab->repaint(FALSE); //### } void QColorShower::rgbEd() { rgbOriginal = TRUE; curCol = qRgb( rEd->val(), gEd->val(), bEd->val() ); rgb2hsv(currentColor(), hue, sat, val ); hEd->setNum( hue ); sEd->setNum( sat ); vEd->setNum( val ); showCurrentColor(); emit newCol( currentColor() ); } void QColorShower::hsvEd() { rgbOriginal = FALSE; hue = hEd->val(); sat = sEd->val(); val = vEd->val(); curCol = QColor( hue, sat, val, QColor::Hsv ).rgb(); rEd->setNum( qRed(currentColor()) ); gEd->setNum( qGreen(currentColor()) ); bEd->setNum( qBlue(currentColor()) ); showCurrentColor(); emit newCol( currentColor() ); } void QColorShower::setRgb( QRgb rgb ) { rgbOriginal = TRUE; curCol = rgb; rgb2hsv( currentColor(), hue, sat, val ); hEd->setNum( hue ); sEd->setNum( sat ); vEd->setNum( val ); rEd->setNum( qRed(currentColor()) ); gEd->setNum( qGreen(currentColor()) ); bEd->setNum( qBlue(currentColor()) ); showCurrentColor(); } void QColorShower::setHsv( int h, int s, int v ) { rgbOriginal = FALSE; hue = h; val = v; sat = s; //Range check### curCol = QColor( hue, sat, val, QColor::Hsv ).rgb(); hEd->setNum( hue ); sEd->setNum( sat ); vEd->setNum( val ); rEd->setNum( qRed(currentColor()) ); gEd->setNum( qGreen(currentColor()) ); bEd->setNum( qBlue(currentColor()) ); showCurrentColor(); } } class OColorDialogPrivate : public QObject { Q_OBJECT public: OColorDialogPrivate( OColorDialog *p ); QRgb currentColor() const { return cs->currentColor(); } void setCurrentColor( const QRgb& rgb ); int currentAlpha() const { return cs->currentAlpha(); } void setCurrentAlpha( int a ) { cs->setCurrentAlpha( a ); } void showAlpha( bool b ) { cs->showAlpha( b ); } private slots: void newHsv( int h, int s, int v ); void newColorTypedIn( QRgb rgb ); private: QColorPicker *cp; QColorLuminancePicker *lp; QColorShower *cs; }; //sets all widgets to display h,s,v void OColorDialogPrivate::newHsv( int h, int s, int v ) { cs->setHsv( h, s, v ); cp->setCol( h, s ); lp->setCol( h, s, v ); } //sets all widgets to display rgb void OColorDialogPrivate::setCurrentColor( const QRgb& rgb ) { cs->setRgb( rgb ); newColorTypedIn( rgb ); } //sets all widgets exept cs to display rgb void OColorDialogPrivate::newColorTypedIn( QRgb rgb ) { int h, s, v; rgb2hsv(rgb, h, s, v ); cp->setCol( h, s ); lp->setCol( h, s, v); } OColorDialogPrivate::OColorDialogPrivate( OColorDialog *dialog ) : QObject(dialog) { int border = 2; QVBoxLayout *topLay = new QVBoxLayout( dialog, border, 2 ); QHBoxLayout *pickLay = new QHBoxLayout( topLay ); cp = new QColorPicker( dialog ); cp->setFrameStyle( QFrame::Panel + QFrame::Sunken ); diff --git a/libopie/colorpopupmenu.cpp b/libopie/colorpopupmenu.cpp index 0d66fba..03ad233 100644 --- a/libopie/colorpopupmenu.cpp +++ b/libopie/colorpopupmenu.cpp @@ -1,172 +1,172 @@ /* This file is part of the Opie Project Copyright (c) 2002 S. Prud'homme <prudhomme@laposte.net> Dan Williams <williamsdr@acm.org> =. .=l. .>+-= _;:, .> :=|. This program is free software; you can .> <`_, > . <= redistribute it and/or modify it under :`=1 )Y*s>-.-- : the terms of the GNU Library General Public .="- .-=="i, .._ License as published by the Free Software - . .-<_> .<> Foundation; either version 2 of the License, ._= =} : or (at your option) any later version. .%`+i> _;_. .i_,=:_. -<s. This program 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 "colorpopupmenu.h" #include "colordialog.h" #include <qlayout.h> #include <qpainter.h> OColorPanelButton::OColorPanelButton( const QColor& color, QWidget* parent, const char* name ) : QFrame( parent, name ) { m_color = color; setFixedSize( 16, 16 ); setActive( FALSE ); } OColorPanelButton::~OColorPanelButton() { } void OColorPanelButton::setActive( bool active ) { m_active = active; if ( m_active ) { setFrameStyle( Panel | Sunken ); } else { setFrameStyle( NoFrame ); } } void OColorPanelButton::enterEvent( QEvent* ) { if ( !m_active ) { setFrameStyle( Panel | Sunken ); } } void OColorPanelButton::leaveEvent( QEvent* ) { if ( !m_active ) { setFrameStyle( NoFrame ); } } void OColorPanelButton::paintEvent( QPaintEvent* e ) { QFrame::paintEvent( e ); QPainter painter; painter.begin( this ); painter.fillRect( 2, 2, 12, 12, m_color ); painter.setPen( Qt::black ); painter.drawRect( 2, 2, 12, 12 ); painter.end(); } void OColorPanelButton::mouseReleaseEvent( QMouseEvent* ) { emit selected( m_color ); } OColorPopupMenu::OColorPopupMenu( const QColor& color, QWidget* parent, const char* name ) : QPopupMenu( parent, name ) { m_color = color; colorPanel = new QWidget( this ); colorLayout = new QGridLayout(colorPanel, 5, 6); addColor(QColor(255, 255, 255), 0, 1); addColor(QColor(192, 192, 192), 0, 2); addColor(QColor(128, 128, 128), 0, 3); addColor(QColor(64, 64, 64), 0, 4); addColor(QColor(0, 0, 0), 0, 5); addColor(QColor(255, 0, 0), 1, 0); addColor(QColor(255, 128, 0), 1, 1); addColor(QColor(255, 255, 0), 1, 2); addColor(QColor(128, 255, 0), 1, 3); addColor(QColor(0, 255, 0), 1, 4); addColor(QColor(0, 255, 128), 1, 5); addColor(QColor(128, 0, 0), 2, 0); addColor(QColor(128, 64, 0), 2, 1); addColor(QColor(128, 128, 0), 2, 2); addColor(QColor(64, 128, 0), 2, 3); addColor(QColor(0, 128, 0), 2, 4); addColor(QColor(0, 128, 64), 2, 5); addColor(QColor(0, 255, 255), 3, 0); addColor(QColor(0, 128, 255), 3, 1); addColor(QColor(0, 0, 255), 3, 2); addColor(QColor(128, 0, 255), 3, 3); addColor(QColor(255, 0, 255), 3, 4); addColor(QColor(255, 0, 128), 3, 5); addColor(QColor(0, 128, 128), 4, 0); addColor(QColor(0, 64, 128), 4, 1); addColor(QColor(0, 0, 128), 4, 2); addColor(QColor(64, 0, 128), 4, 3); addColor(QColor(128, 0, 128), 4, 4); addColor(QColor(128, 0, 64), 4, 5); insertItem( colorPanel ); insertSeparator(); insertItem(tr("More"),this,SLOT( moreColorClicked())); /* QAction* chooseColorAction = new QAction( tr( "More" ), tr( "More..." ), 0, colorPanel, "More" ); connect( chooseColorAction, SIGNAL( activated() ), this, SLOT( moreColorClicked() ) ); chooseColorAction->addTo( this ); */ activateItemAt( 0 ); } OColorPopupMenu::~OColorPopupMenu() { } void OColorPopupMenu::addColor( const QColor& color, int row, int col ) { OColorPanelButton* panelButton = new OColorPanelButton( color, colorPanel ); - connect( panelButton, SIGNAL( selected( const QColor& ) ), this, SLOT( buttonSelected( const QColor& ) ) ); + connect( panelButton, SIGNAL( selected(const QColor&) ), this, SLOT( buttonSelected(const QColor&) ) ); colorLayout->addWidget( panelButton, row, col ); } void OColorPopupMenu::buttonSelected( const QColor& color ) { m_color = color; emit colorSelected( color ); hide(); } void OColorPopupMenu::moreColorClicked() { QColor color = OColorDialog::getColor( m_color ); m_color = color; emit colorSelected( color ); hide(); } diff --git a/libopie/ocolorbutton.cpp b/libopie/ocolorbutton.cpp index 93fe5d0..298dba2 100644 --- a/libopie/ocolorbutton.cpp +++ b/libopie/ocolorbutton.cpp @@ -1,139 +1,139 @@ /* =. This file is part of the OPIE Project .=l. Copyright (c) 2002 Robert Griebl <sandman@handhelds.org> .>+-= _;:, .> :=|. This library is free software; you can .> <`_, > . <= redistribute it and/or modify it under :`=1 )Y*s>-.-- : the terms of the GNU Library General Public .="- .-=="i, .._ License as published by the Free Software - . .-<_> .<> Foundation; either version 2 of the License, ._= =} : or (at your option) any later version. .%`+i> _;_. .i_,=:_. -<s. 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 <opie/colorpopupmenu.h> #include <opie/ocolorbutton.h> #include <qpe/resource.h> struct OColorButtonPrivate { QPopupMenu *m_menu; QColor m_color; }; /** * This concstructs a Color Button with @param color as the start color * It'll use a OColorPopupMenu internally * * @param parent The parent of the Color Button * @param color The color from where to start on * @param name @see QObject */ OColorButton::OColorButton ( QWidget *parent, const QColor &color, const char *name ) : QPushButton ( parent, name ) { d = new OColorButtonPrivate; d-> m_menu = new OColorPopupMenu ( color, 0, 0 ); setPopup ( d-> m_menu ); // setPopupDelay ( 0 ); - connect ( d-> m_menu, SIGNAL( colorSelected ( const QColor & )), this, SLOT( updateColor ( const QColor & ))); + connect ( d-> m_menu, SIGNAL( colorSelected(const QColor&)), this, SLOT( updateColor(const QColor&))); updateColor ( color ); QSize s = sizeHint ( ) + QSize ( 12, 0 ); setMinimumSize ( s ); setMaximumSize ( s. width ( ) * 2, s. height ( )); } /** * This destructs the object */ OColorButton::~OColorButton ( ) { delete d; } /** * @return Returns the current color of the button */ QColor OColorButton::color ( ) const { return d-> m_color; } /** * This method sets the color of the button * @param c The color to be set. */ void OColorButton::setColor ( const QColor &c ) { updateColor ( c ); } /** * @internal */ void OColorButton::updateColor ( const QColor &c ) { d-> m_color = c; QImage img ( 16, 16, 32 ); img. fill ( 0 ); int r, g, b; c. rgb ( &r, &g, &b ); int w = img. width ( ); int h = img. height ( ); int dx = w * 20 / 100; // 15% int dy = h * 20 / 100; for ( int y = 0; y < h; y++ ) { for ( int x = 0; x < w; x++ ) { double alpha = 1.0; if ( x < dx ) alpha *= ( double ( x + 1 ) / dx ); else if ( x >= w - dx ) alpha *= ( double ( w - x ) / dx ); if ( y < dy ) alpha *= ( double ( y + 1 ) / dy ); else if ( y >= h - dy ) alpha *= ( double ( h - y ) / dy ); int a = int ( alpha * 255.0 ); if ( a < 0 ) a = 0; if ( a > 255 ) a = 255; img. setPixel ( x, y, qRgba ( r, g, b, a )); } } img. setAlphaBuffer ( true ); QPixmap pix; pix. convertFromImage ( img ); setPixmap ( pix ); emit colorSelected ( c ); } diff --git a/libopie/odevice.cpp b/libopie/odevice.cpp index c0b6efa..4258d60 100644 --- a/libopie/odevice.cpp +++ b/libopie/odevice.cpp @@ -343,385 +343,385 @@ struct s_button { { Model_SIMpad_CL4 | Model_SIMpad_SL4 | Model_SIMpad_SLC | Model_SIMpad_TSinus, Qt::Key_F6, QT_TRANSLATE_NOOP("Button", "Upper+Down"), "devicebuttons/simpad_upper_down", "addressbook", "raise()", "addressbook", "beamBusinessCard()" }, { Model_SIMpad_CL4 | Model_SIMpad_SL4 | Model_SIMpad_SLC | Model_SIMpad_TSinus, Qt::Key_F7, QT_TRANSLATE_NOOP("Button", "Upper+Right"), "devicebuttons/simpad_upper_right", "QPE/TaskBar", "toggleMenu()", "QPE/TaskBar", "toggleStartMenu()" }, { Model_SIMpad_CL4 | Model_SIMpad_SL4 | Model_SIMpad_SLC | Model_SIMpad_TSinus, Qt::Key_F13, QT_TRANSLATE_NOOP("Button", "Upper+Left"), "devicebuttons/simpad_upper_left", "QPE/Rotation", "flip()", "QPE/Rotation", "flip()" }, /* { Model_SIMpad_CL4 | Model_SIMpad_SL4 | Model_SIMpad_SLC | Model_SIMpad_TSinus, Qt::Key_F12, QT_TRANSLATE_NOOP("Button", "Lower+Upper"), "devicebuttons/simpad_lower_upper", "QPE/Launcher", "home()", "buttonsettings", "raise()" }, { Model_SIMpad_CL4 | Model_SIMpad_SL4 | Model_SIMpad_SLC | Model_SIMpad_TSinus, Qt::Key_F12, QT_TRANSLATE_NOOP("Button", "Lower+Upper"), "devicebuttons/simpad_upper_lower", "QPE/Launcher", "home()", "buttonsettings", "raise()" }, */ }; struct r_button { uint model; Qt::Key code; char *utext; char *pix; char *fpressedservice; char *fpressedaction; char *fheldservice; char *fheldaction; } ramses_buttons [] = { { Model_Ramses_MNCI, Qt::Key_F11, QT_TRANSLATE_NOOP("Button", "Menu Button"), "devicebuttons/z_menu", "QPE/TaskBar", "toggleMenu()", "QPE/TaskBar", "toggleStartMenu()" }, { Model_Ramses_MNCI, Qt::Key_F12, QT_TRANSLATE_NOOP("Button", "Home Button"), "devicebuttons/ipaq_home", "QPE/Launcher", "home()", "buttonsettings", "raise()" }, }; class Yopy : public ODevice { protected: virtual void init ( ); virtual void initButtons ( ); public: virtual bool suspend ( ); virtual bool setDisplayBrightness ( int b ); virtual int displayBrightnessResolution ( ) const; static bool isYopy ( ); }; struct yopy_button { Qt::Key code; char *utext; char *pix; char *fpressedservice; char *fpressedaction; char *fheldservice; char *fheldaction; } yopy_buttons [] = { { Qt::Key_F10, QT_TRANSLATE_NOOP("Button", "Action Button"), "devicebuttons/yopy_action", "datebook", "nextView()", "today", "raise()" }, { Qt::Key_F11, QT_TRANSLATE_NOOP("Button", "OK Button"), "devicebuttons/yopy_ok", "addressbook", "raise()", "addressbook", "beamBusinessCard()" }, { Qt::Key_F12, QT_TRANSLATE_NOOP("Button", "End Button"), "devicebuttons/yopy_end", "QPE/Launcher", "home()", "buttonsettings", "raise()" }, }; static QCString makeChannel ( const char *str ) { if ( str && !::strchr ( str, '/' )) return QCString ( "QPE/Application/" ) + str; else return str; } static inline bool isQWS() { return qApp ? ( qApp-> type ( ) == QApplication::GuiServer ) : false; } ODevice *ODevice::inst ( ) { static ODevice *dev = 0; if ( !dev ) { if ( QFile::exists ( "/proc/hal/model" )) dev = new iPAQ ( ); else if ( Zaurus::isZaurus() ) dev = new Zaurus ( ); else if ( QFile::exists ( "/proc/ucb1x00" ) && QFile::exists ( "/proc/cs3" )) dev = new SIMpad ( ); else if ( QFile::exists ( "/proc/sys/board/name" )) dev = new Ramses ( ); else if ( Yopy::isYopy() ) dev = new Yopy ( ); else if ( Jornada::isJornada() ) dev = new Jornada ( ); else dev = new ODevice ( ); dev-> init ( ); } return dev; } /************************************************** * * common * **************************************************/ ODevice::ODevice ( ) { d = new ODeviceData; d-> m_modelstr = "Unknown"; d-> m_model = Model_Unknown; d-> m_vendorstr = "Unknown"; d-> m_vendor = Vendor_Unknown; d-> m_systemstr = "Unknown"; d-> m_system = System_Unknown; d-> m_sysverstr = "0.0"; d-> m_rotation = Rot0; d-> m_direction = CW; d-> m_holdtime = 1000; // 1000ms d-> m_buttons = 0; d-> m_cpu_frequencies = new QStrList; } void ODevice::systemMessage ( const QCString &msg, const QByteArray & ) { if ( msg == "deviceButtonMappingChanged()" ) { reloadButtonMapping ( ); } } void ODevice::init ( ) { } /** * This method initialises the button mapping */ void ODevice::initButtons ( ) { if ( d-> m_buttons ) return; // Simulation uses iPAQ 3660 device buttons qDebug ( "init Buttons" ); d-> m_buttons = new QValueList <ODeviceButton>; for ( uint i = 0; i < ( sizeof( ipaq_buttons ) / sizeof( i_button )); i++ ) { i_button *ib = ipaq_buttons + i; ODeviceButton b; if (( ib-> model & Model_iPAQ_H36xx ) == Model_iPAQ_H36xx ) { b. setKeycode ( ib-> code ); b. setUserText ( QObject::tr ( "Button", ib-> utext )); b. setPixmap ( Resource::loadPixmap ( ib-> pix )); b. setFactoryPresetPressedAction ( OQCopMessage ( makeChannel ( ib-> fpressedservice ), ib-> fpressedaction )); b. setFactoryPresetHeldAction ( OQCopMessage ( makeChannel ( ib-> fheldservice ), ib-> fheldaction )); d-> m_buttons-> append ( b ); } } reloadButtonMapping ( ); QCopChannel *sysch = new QCopChannel ( "QPE/System", this ); - connect ( sysch, SIGNAL( received( const QCString &, const QByteArray & )), this, SLOT( systemMessage ( const QCString &, const QByteArray & ))); + connect ( sysch, SIGNAL( received(const QCString&,const QByteArray&)), this, SLOT( systemMessage(const QCString&,const QByteArray&))); } ODevice::~ODevice ( ) { // we leak m_devicebuttons and m_cpu_frequency // but it's a singleton and it is not so importantant // -zecke delete d; } bool ODevice::setSoftSuspend ( bool /*soft*/ ) { return false; } //#include <linux/apm_bios.h> #define APM_IOC_SUSPEND OD_IO( 'A', 2 ) /** * This method will try to suspend the device * It only works if the user is the QWS Server and the apm application * is installed. * It tries to suspend and then waits some time cause some distributions * do have asynchronus apm implementations. * This method will either fail and return false or it'll suspend the * device and return once the device got woken up * * @return if the device got suspended */ bool ODevice::suspend ( ) { qDebug("ODevice::suspend"); if ( !isQWS( ) ) // only qwsserver is allowed to suspend return false; if ( d-> m_model == Model_Unknown ) // better don't suspend in qvfb / on unkown devices return false; bool res = false; struct timeval tvs, tvn; ::gettimeofday ( &tvs, 0 ); ::sync ( ); // flush fs caches res = ( ::system ( "apm --suspend" ) == 0 ); // This is needed because the iPAQ apm implementation is asynchronous and we // can not be sure when exactly the device is really suspended // This can be deleted as soon as a stable familiar with a synchronous apm implementation exists. if ( res ) { do { // wait at most 1.5 sec: either suspend didn't work or the device resumed ::usleep ( 200 * 1000 ); ::gettimeofday ( &tvn, 0 ); } while ((( tvn. tv_sec - tvs. tv_sec ) * 1000 + ( tvn. tv_usec - tvs. tv_usec ) / 1000 ) < 1500 ); } return res; } //#include <linux/fb.h> better not rely on kernel headers in userspace ... #define FBIOBLANK OD_IO( 'F', 0x11 ) // 0x4611 /* VESA Blanking Levels */ #define VESA_NO_BLANKING 0 #define VESA_VSYNC_SUSPEND 1 #define VESA_HSYNC_SUSPEND 2 #define VESA_POWERDOWN 3 /** * This sets the display on or off */ bool ODevice::setDisplayStatus ( bool on ) { qDebug("ODevice::setDisplayStatus(%d)", on); if ( d-> m_model == Model_Unknown ) return false; bool res = false; int fd; if (( fd = ::open ( "/dev/fb0", O_RDWR )) >= 0 ) { res = ( ::ioctl ( fd, FBIOBLANK, on ? VESA_NO_BLANKING : VESA_POWERDOWN ) == 0 ); ::close ( fd ); } return res; } /** * This sets the display brightness * * @param p The brightness to be set on a scale from 0 to 255 * @return success or failure */ bool ODevice::setDisplayBrightness ( int p) { Q_UNUSED( p ) return false; } /** * @return returns the number of steppings on the brightness slider * in the Light-'n-Power settings. */ int ODevice::displayBrightnessResolution ( ) const { return 16; } /** * This sets the display contrast * @param p The contrast to be set on a scale from 0 to 255 * @return success or failure */ bool ODevice::setDisplayContrast ( int p) { Q_UNUSED( p ) return false; } /** * @return return the max value for the brightness settings slider * or 0 if the device doesn't support setting of a contrast */ int ODevice::displayContrastResolution ( ) const { return 0; } /** * This returns the vendor as string * @return Vendor as QString */ QString ODevice::vendorString ( ) const { return d-> m_vendorstr; } /** * This returns the vendor as one of the values of OVendor * @return OVendor */ OVendor ODevice::vendor ( ) const { return d-> m_vendor; } /** * This returns the model as a string * @return A string representing the model */ QString ODevice::modelString ( ) const { return d-> m_modelstr; } /** * This does return the OModel used */ OModel ODevice::model ( ) const { return d-> m_model; } /** * This does return the systen name */ QString ODevice::systemString ( ) const { return d-> m_systemstr; } /** * Return System as OSystem value */ OSystem ODevice::system ( ) const { return d-> m_system; } /** * @return the version string of the base system */ QString ODevice::systemVersionString ( ) const { return d-> m_sysverstr; } /** @@ -923,534 +923,534 @@ uint ODevice::buttonHoldTime ( ) const return d-> m_holdtime; } /** * This method return a ODeviceButton for a key code * or 0 if no special hardware button is available for the device * * @return The devicebutton or 0l * @see ODeviceButton */ const ODeviceButton *ODevice::buttonForKeycode ( ushort code ) { initButtons ( ); for ( QValueListConstIterator<ODeviceButton> it = d-> m_buttons-> begin ( ); it != d-> m_buttons-> end ( ); ++it ) { if ( (*it). keycode ( ) == code ) return &(*it); } return 0; } void ODevice::reloadButtonMapping ( ) { initButtons ( ); Config cfg ( "ButtonSettings" ); for ( uint i = 0; i < d-> m_buttons-> count ( ); i++ ) { ODeviceButton &b = ( *d-> m_buttons ) [i]; QString group = "Button" + QString::number ( i ); QCString pch, hch; QCString pm, hm; QByteArray pdata, hdata; if ( cfg. hasGroup ( group )) { cfg. setGroup ( group ); pch = cfg. readEntry ( "PressedActionChannel" ). latin1 ( ); pm = cfg. readEntry ( "PressedActionMessage" ). latin1 ( ); // pdata = decodeBase64 ( buttonFile. readEntry ( "PressedActionArgs" )); hch = cfg. readEntry ( "HeldActionChannel" ). latin1 ( ); hm = cfg. readEntry ( "HeldActionMessage" ). latin1 ( ); // hdata = decodeBase64 ( buttonFile. readEntry ( "HeldActionArgs" )); } b. setPressedAction ( OQCopMessage ( pch, pm, pdata )); b. setHeldAction ( OQCopMessage ( hch, hm, hdata )); } } void ODevice::remapPressedAction ( int button, const OQCopMessage &action ) { initButtons ( ); QString mb_chan; if ( button >= (int) d-> m_buttons-> count ( )) return; ODeviceButton &b = ( *d-> m_buttons ) [button]; b. setPressedAction ( action ); mb_chan=b. pressedAction ( ). channel ( ); Config buttonFile ( "ButtonSettings" ); buttonFile. setGroup ( "Button" + QString::number ( button )); buttonFile. writeEntry ( "PressedActionChannel", (const char*) mb_chan); buttonFile. writeEntry ( "PressedActionMessage", (const char*) b. pressedAction ( ). message ( )); // buttonFile. writeEntry ( "PressedActionArgs", encodeBase64 ( b. pressedAction ( ). data ( ))); QCopEnvelope ( "QPE/System", "deviceButtonMappingChanged()" ); } void ODevice::remapHeldAction ( int button, const OQCopMessage &action ) { initButtons ( ); if ( button >= (int) d-> m_buttons-> count ( )) return; ODeviceButton &b = ( *d-> m_buttons ) [button]; b. setHeldAction ( action ); Config buttonFile ( "ButtonSettings" ); buttonFile. setGroup ( "Button" + QString::number ( button )); buttonFile. writeEntry ( "HeldActionChannel", (const char *) b. heldAction ( ). channel ( )); buttonFile. writeEntry ( "HeldActionMessage", (const char *) b. heldAction ( ). message ( )); // buttonFile. writeEntry ( "HeldActionArgs", decodeBase64 ( b. heldAction ( ). data ( ))); QCopEnvelope ( "QPE/System", "deviceButtonMappingChanged()" ); } void ODevice::virtual_hook(int id, void* data){ switch( id ) { case VIRTUAL_ROTATION:{ VirtRotation* rot = reinterpret_cast<VirtRotation*>( data ); rot->trans = d->m_rotation; break; } case VIRTUAL_DIRECTION:{ VirtDirection *dir = reinterpret_cast<VirtDirection*>( data ); dir->direct = d->m_direction; break; } case VIRTUAL_HAS_HINGE:{ VirtHasHinge *hin = reinterpret_cast<VirtHasHinge*>( data ); hin->hasHinge = false; break; } case VIRTUAL_HINGE:{ VirtHingeStatus *hin = reinterpret_cast<VirtHingeStatus*>( data ); hin->hingeStat = CASE_UNKNOWN; break; } } } /************************************************** * * Yopy 3500/3700 * **************************************************/ bool Yopy::isYopy ( ) { QFile f( "/proc/cpuinfo" ); if ( f. open ( IO_ReadOnly ) ) { QTextStream ts ( &f ); QString line; while( line = ts. readLine ( ) ) { if ( line. left ( 8 ) == "Hardware" ) { int loc = line. find ( ":" ); if ( loc != -1 ) { QString model = line. mid ( loc + 2 ). simplifyWhiteSpace( ); return ( model == "Yopy" ); } } } } return false; } void Yopy::init ( ) { d-> m_vendorstr = "G.Mate"; d-> m_vendor = Vendor_GMate; d-> m_modelstr = "Yopy3700"; d-> m_model = Model_Yopy_3700; d-> m_rotation = Rot0; d-> m_systemstr = "Linupy"; d-> m_system = System_Linupy; QFile f ( "/etc/issue" ); if ( f. open ( IO_ReadOnly )) { QTextStream ts ( &f ); ts.readLine(); d-> m_sysverstr = ts. readLine ( ); f. close ( ); } } void Yopy::initButtons ( ) { if ( d-> m_buttons ) return; d-> m_buttons = new QValueList <ODeviceButton>; for (uint i = 0; i < ( sizeof( yopy_buttons ) / sizeof(yopy_button)); i++) { yopy_button *ib = yopy_buttons + i; ODeviceButton b; b. setKeycode ( ib-> code ); b. setUserText ( QObject::tr ( "Button", ib-> utext )); b. setPixmap ( Resource::loadPixmap ( ib-> pix )); b. setFactoryPresetPressedAction (OQCopMessage(makeChannel(ib->fpressedservice), ib->fpressedaction)); b. setFactoryPresetHeldAction (OQCopMessage(makeChannel(ib->fheldservice), ib->fheldaction)); d-> m_buttons-> append ( b ); } reloadButtonMapping ( ); QCopChannel *sysch = new QCopChannel("QPE/System", this); - connect(sysch, SIGNAL(received(const QCString &, const QByteArray & )), - this, SLOT(systemMessage(const QCString &, const QByteArray & ))); + connect(sysch, SIGNAL(received(const QCString&,const QByteArray&)), + this, SLOT(systemMessage(const QCString&,const QByteArray&))); } bool Yopy::suspend() { /* Opie for Yopy does not implement its own power management at the moment. The public version runs parallel to X, and relies on the existing power management features. */ return false; } bool Yopy::setDisplayBrightness(int bright) { /* The code here works, but is disabled as the current version runs parallel to X, and relies on the existing backlight demon. */ #if 0 if ( QFile::exists("/proc/sys/pm/light") ) { int fd = ::open("/proc/sys/pm/light", O_WRONLY); if (fd >= 0 ) { if (bright) ::write(fd, "1\n", 2); else ::write(fd, "0\n", 2); ::close(fd); return true; } } #endif return false; } int Yopy::displayBrightnessResolution() const { return 2; } /************************************************** * * iPAQ * **************************************************/ void iPAQ::init ( ) { d-> m_vendorstr = "HP"; d-> m_vendor = Vendor_HP; QFile f ( "/proc/hal/model" ); if ( f. open ( IO_ReadOnly )) { QTextStream ts ( &f ); d-> m_modelstr = "H" + ts. readLine ( ); if ( d-> m_modelstr == "H3100" ) d-> m_model = Model_iPAQ_H31xx; else if ( d-> m_modelstr == "H3600" ) d-> m_model = Model_iPAQ_H36xx; else if ( d-> m_modelstr == "H3700" ) d-> m_model = Model_iPAQ_H37xx; else if ( d-> m_modelstr == "H3800" ) d-> m_model = Model_iPAQ_H38xx; else if ( d-> m_modelstr == "H3900" ) d-> m_model = Model_iPAQ_H39xx; else if ( d-> m_modelstr == "H5400" ) d-> m_model = Model_iPAQ_H5xxx; else d-> m_model = Model_Unknown; f. close ( ); } switch ( d-> m_model ) { case Model_iPAQ_H31xx: case Model_iPAQ_H38xx: d-> m_rotation = Rot90; break; case Model_iPAQ_H36xx: case Model_iPAQ_H37xx: case Model_iPAQ_H39xx: default: d-> m_rotation = Rot270; break; case Model_iPAQ_H5xxx: d-> m_rotation = Rot0; } f. setName ( "/etc/familiar-version" ); if ( f. open ( IO_ReadOnly )) { d-> m_systemstr = "Familiar"; d-> m_system = System_Familiar; QTextStream ts ( &f ); d-> m_sysverstr = ts. readLine ( ). mid ( 10 ); f. close ( ); } else { f. setName ( "/etc/oz_version" ); if ( f. open ( IO_ReadOnly )) { d-> m_systemstr = "OpenEmbedded/iPaq"; d-> m_system = System_Familiar; QTextStream ts ( &f ); ts.setDevice ( &f ); d-> m_sysverstr = ts. readLine ( ); f. close ( ); } } m_leds [0] = m_leds [1] = Led_Off; m_power_timer = 0; } void iPAQ::initButtons ( ) { if ( d-> m_buttons ) return; if ( isQWS( ) ) QWSServer::setKeyboardFilter ( this ); d-> m_buttons = new QValueList <ODeviceButton>; for ( uint i = 0; i < ( sizeof( ipaq_buttons ) / sizeof( i_button )); i++ ) { i_button *ib = ipaq_buttons + i; ODeviceButton b; if (( ib-> model & d-> m_model ) == d-> m_model ) { b. setKeycode ( ib-> code ); b. setUserText ( QObject::tr ( "Button", ib-> utext )); b. setPixmap ( Resource::loadPixmap ( ib-> pix )); b. setFactoryPresetPressedAction ( OQCopMessage ( makeChannel ( ib-> fpressedservice ), ib-> fpressedaction )); b. setFactoryPresetHeldAction ( OQCopMessage ( makeChannel ( ib-> fheldservice ), ib-> fheldaction )); d-> m_buttons-> append ( b ); } } reloadButtonMapping ( ); QCopChannel *sysch = new QCopChannel ( "QPE/System", this ); - connect ( sysch, SIGNAL( received( const QCString &, const QByteArray & )), this, SLOT( systemMessage ( const QCString &, const QByteArray & ))); + connect ( sysch, SIGNAL( received(const QCString&,const QByteArray&)), this, SLOT( systemMessage(const QCString&,const QByteArray&))); } //#include <linux/h3600_ts.h> // including kernel headers is evil ... typedef struct { unsigned char OffOnBlink; /* 0=off 1=on 2=Blink */ unsigned char TotalTime; /* Units of 5 seconds */ unsigned char OnTime; /* units of 100m/s */ unsigned char OffTime; /* units of 100m/s */ } LED_IN; typedef struct { unsigned char mode; unsigned char pwr; unsigned char brightness; } FLITE_IN; #define LED_ON OD_IOW( 'f', 5, LED_IN ) #define FLITE_ON OD_IOW( 'f', 7, FLITE_IN ) QValueList <OLed> iPAQ::ledList ( ) const { QValueList <OLed> vl; vl << Led_Power; if ( d-> m_model == Model_iPAQ_H38xx ) vl << Led_BlueTooth; return vl; } QValueList <OLedState> iPAQ::ledStateList ( OLed l ) const { QValueList <OLedState> vl; if ( l == Led_Power ) vl << Led_Off << Led_On << Led_BlinkSlow << Led_BlinkFast; else if ( l == Led_BlueTooth && d-> m_model == Model_iPAQ_H38xx ) vl << Led_Off; // << Led_On << ??? return vl; } OLedState iPAQ::ledState ( OLed l ) const { switch ( l ) { case Led_Power: return m_leds [0]; case Led_BlueTooth: return m_leds [1]; default: return Led_Off; } } bool iPAQ::setLedState ( OLed l, OLedState st ) { static int fd = ::open ( "/dev/touchscreen/0", O_RDWR | O_NONBLOCK ); if ( l == Led_Power ) { if ( fd >= 0 ) { LED_IN leds; ::memset ( &leds, 0, sizeof( leds )); leds. TotalTime = 0; leds. OnTime = 0; leds. OffTime = 1; leds. OffOnBlink = 2; switch ( st ) { case Led_Off : leds. OffOnBlink = 0; break; case Led_On : leds. OffOnBlink = 1; break; case Led_BlinkSlow: leds. OnTime = 10; leds. OffTime = 10; break; case Led_BlinkFast: leds. OnTime = 5; leds. OffTime = 5; break; } if ( ::ioctl ( fd, LED_ON, &leds ) >= 0 ) { m_leds [0] = st; return true; } } } return false; } bool iPAQ::filter ( int /*unicode*/, int keycode, int modifiers, bool isPress, bool autoRepeat ) { int newkeycode = keycode; switch ( keycode ) { // H38xx/H39xx have no "Q" key anymore - this is now the Mail key case HardKey_Menu: { if (( d-> m_model == Model_iPAQ_H38xx ) || ( d-> m_model == Model_iPAQ_H39xx ) || ( d-> m_model == Model_iPAQ_H5xxx)) { newkeycode = HardKey_Mail; } break; } // Rotate cursor keys 180° or 270° case Key_Left : case Key_Right: case Key_Up : case Key_Down : { if (( d-> m_model == Model_iPAQ_H31xx ) || ( d-> m_model == Model_iPAQ_H38xx )) { newkeycode = Key_Left + ( keycode - Key_Left + 2 ) % 4; } // Rotate the cursor keys by 270° // keycode - Key_Left = position of the button starting from left clockwise // add the rotation to it and modolo. No we've the original offset // add the offset to the Key_Left key if ( d-> m_model == Model_iPAQ_H5xxx ) newkeycode = Key_Left + ( keycode - Key_Left + 3 ) % 4; break; } // map Power Button short/long press to F34/F35 case Key_SysReq: { if ( isPress ) { if ( m_power_timer ) killTimer ( m_power_timer ); m_power_timer = startTimer ( 500 ); } else if ( m_power_timer ) { killTimer ( m_power_timer ); m_power_timer = 0; QWSServer::sendKeyEvent ( -1, HardKey_Suspend, 0, true, false ); QWSServer::sendKeyEvent ( -1, HardKey_Suspend, 0, false, false ); } newkeycode = Key_unknown; break; } } if ( newkeycode != keycode ) { if ( newkeycode != Key_unknown ) QWSServer::sendKeyEvent ( -1, newkeycode, modifiers, isPress, autoRepeat ); return true; } else return false; } void iPAQ::timerEvent ( QTimerEvent * ) { killTimer ( m_power_timer ); m_power_timer = 0; QWSServer::sendKeyEvent ( -1, HardKey_Backlight, 0, true, false ); QWSServer::sendKeyEvent ( -1, HardKey_Backlight, 0, false, false ); } void iPAQ::alarmSound ( ) { #ifndef QT_NO_SOUND static Sound snd ( "alarm" ); int fd; int vol; bool vol_reset = false; if (( fd = ::open ( "/dev/sound/mixer", O_RDWR )) >= 0 ) { if ( ::ioctl ( fd, MIXER_READ( 0 ), &vol ) >= 0 ) { Config cfg ( "qpe" ); cfg. setGroup ( "Volume" ); int volalarm = cfg. readNumEntry ( "AlarmPercent", 50 ); if ( volalarm < 0 ) volalarm = 0; else if ( volalarm > 100 ) volalarm = 100; volalarm |= ( volalarm << 8 ); if ( ::ioctl ( fd, MIXER_WRITE( 0 ), &volalarm ) >= 0 ) vol_reset = true; } } snd. play ( ); while ( !snd. isFinished ( )) qApp-> processEvents ( ); if ( fd >= 0 ) { if ( vol_reset ) ::ioctl ( fd, MIXER_WRITE( 0 ), &vol ); ::close ( fd ); } #endif } @@ -1558,386 +1558,386 @@ int iPAQ::lightSensorResolution ( ) const // Check whether this device is the sharp zaurus.. // FIXME This gets unnecessary complicated. We should think about splitting the Zaurus // class up into individual classes. We need three classes // // Zaurus-Collie (SA-model w/ 320x240 lcd, for SL5500 and SL5000) // Zaurus-Poodle (PXA-model w/ 320x240 lcd, for SL5600) // Zaurus-Corgi (PXA-model w/ 640x480 lcd, for C700, C750, C760, and C860) // // Only question right now is: Do we really need to do it? Because as soon // as the OpenZaurus kernel is ready, there will be a unified interface for all // Zaurus models (concerning apm, backlight, buttons, etc.) // // Comments? - mickeyl. bool Zaurus::isZaurus() { // If the special devices by embedix exist, it is quite simple: it is a Zaurus ! if ( QFile::exists ( "/dev/sharp_buz" ) || QFile::exists ( "/dev/sharp_led" ) ){ return true; } // On non-embedix kernels, we have to look closer. bool is_zaurus = false; QFile f ( "/proc/cpuinfo" ); if ( f. open ( IO_ReadOnly ) ) { QString model; QFile f ( "/proc/cpuinfo" ); QTextStream ts ( &f ); QString line; while( line = ts. readLine ( ) ) { if ( line. left ( 8 ) == "Hardware" ) break; } int loc = line. find ( ":" ); if ( loc != -1 ) model = line. mid ( loc + 2 ). simplifyWhiteSpace( ); if ( model == "Sharp-Collie" || model == "Collie" || model == "SHARP Corgi" || model == "SHARP Shepherd" || model == "SHARP Poodle" || model == "SHARP Husky" ) is_zaurus = true; } return is_zaurus; } void Zaurus::init ( ) { d-> m_vendorstr = "Sharp"; d-> m_vendor = Vendor_Sharp; m_embedix = true; // Not openzaurus means: It has an embedix kernel ! // QFile f ( "/proc/filesystems" ); QString model; // It isn't a good idea to check the system configuration to // detect the distribution ! // Otherwise it may happen that any other distribution is detected as openzaurus, just // because it uses a jffs2 filesystem.. // (eilers) // if ( f. open ( IO_ReadOnly ) && ( QTextStream ( &f ). read ( ). find ( "\tjffs2\n" ) >= 0 )) { QFile f ("/etc/oz_version"); if ( f.exists() ){ d-> m_vendorstr = "OpenZaurus Team"; d-> m_systemstr = "OpenZaurus"; d-> m_system = System_OpenZaurus; if ( f. open ( IO_ReadOnly )) { QTextStream ts ( &f ); d-> m_sysverstr = ts. readLine ( );//. mid ( 10 ); f. close ( ); } // Openzaurus sometimes uses the embedix kernel! // => Check whether this is an embedix kernel FILE *uname = popen("uname -r", "r"); QString line; if ( f.open(IO_ReadOnly, uname) ) { QTextStream ts ( &f ); line = ts. readLine ( ); int loc = line. find ( "embedix" ); if ( loc != -1 ) m_embedix = true; else m_embedix = false; f. close ( ); } pclose(uname); } else { d-> m_systemstr = "Zaurus"; d-> m_system = System_Zaurus; } f. setName ( "/proc/cpuinfo" ); if ( f. open ( IO_ReadOnly ) ) { QTextStream ts ( &f ); QString line; while( line = ts. readLine ( ) ) { if ( line. left ( 8 ) == "Hardware" ) break; } int loc = line. find ( ":" ); if ( loc != -1 ) model = line. mid ( loc + 2 ). simplifyWhiteSpace( ); } if ( model == "SHARP Corgi" ) { d-> m_model = Model_Zaurus_SLC7x0; d-> m_modelstr = "Zaurus SL-C700"; } else if ( model == "SHARP Shepherd" ) { d-> m_model = Model_Zaurus_SLC7x0; d-> m_modelstr = "Zaurus SL-C750"; } else if ( model == "SHARP Husky" ) { d-> m_model = Model_Zaurus_SLC7x0; d-> m_modelstr = "Zaurus SL-C760"; } else if ( model == "SHARP Poodle" ) { d-> m_model = Model_Zaurus_SLB600; d-> m_modelstr = "Zaurus SL-B500 or SL-5600"; } else if ( model == "Sharp-Collie" || model == "Collie" ) { d-> m_model = Model_Zaurus_SL5500; d-> m_modelstr = "Zaurus SL-5500 or SL-5000d"; } else { d-> m_model = Model_Zaurus_SL5500; d-> m_modelstr = "Zaurus (Model unknown)"; } bool flipstate = false; switch ( d-> m_model ) { case Model_Zaurus_SLA300: d-> m_rotation = Rot0; break; case Model_Zaurus_SLC7x0: d-> m_rotation = rotation(); d-> m_direction = direction(); break; case Model_Zaurus_SLB600: case Model_Zaurus_SL5500: case Model_Zaurus_SL5000: default: d-> m_rotation = Rot270; break; } m_leds [0] = Led_Off; } void Zaurus::initButtons ( ) { if ( d-> m_buttons ) return; d-> m_buttons = new QValueList <ODeviceButton>; struct z_button * pz_buttons; int buttoncount; switch ( d-> m_model ) { case Model_Zaurus_SLC7x0: pz_buttons = z_buttons_c700; buttoncount = ARRAY_SIZE(z_buttons_c700); break; default: pz_buttons = z_buttons; buttoncount = ARRAY_SIZE(z_buttons); break; } for ( int i = 0; i < buttoncount; i++ ) { struct z_button *zb = pz_buttons + i; ODeviceButton b; b. setKeycode ( zb-> code ); b. setUserText ( QObject::tr ( "Button", zb-> utext )); b. setPixmap ( Resource::loadPixmap ( zb-> pix )); b. setFactoryPresetPressedAction ( OQCopMessage ( makeChannel ( zb-> fpressedservice ), zb-> fpressedaction )); b. setFactoryPresetHeldAction ( OQCopMessage ( makeChannel ( zb-> fheldservice ), zb-> fheldaction )); d-> m_buttons-> append ( b ); } reloadButtonMapping ( ); QCopChannel *sysch = new QCopChannel ( "QPE/System", this ); - connect ( sysch, SIGNAL( received( const QCString &, const QByteArray & )), - this, SLOT( systemMessage ( const QCString &, const QByteArray & ))); + connect ( sysch, SIGNAL( received(const QCString&,const QByteArray&)), + this, SLOT( systemMessage(const QCString&,const QByteArray&))); } #include <unistd.h> #include <fcntl.h> #include <sys/ioctl.h> //#include <asm/sharp_char.h> // including kernel headers is evil ... #define SHARP_DEV_IOCTL_COMMAND_START 0x5680 #define SHARP_BUZZER_IOCTL_START (SHARP_DEV_IOCTL_COMMAND_START) #define SHARP_BUZZER_MAKESOUND (SHARP_BUZZER_IOCTL_START) #define SHARP_BUZ_TOUCHSOUND 1 /* touch panel sound */ #define SHARP_BUZ_KEYSOUND 2 /* key sound */ #define SHARP_BUZ_SCHEDULE_ALARM 11 /* schedule alarm */ /* --- for SHARP_BUZZER device --- */ //#define SHARP_BUZZER_IOCTL_START (SHARP_DEV_IOCTL_COMMAND_START) //#define SHARP_BUZZER_MAKESOUND (SHARP_BUZZER_IOCTL_START) #define SHARP_BUZZER_SETVOLUME (SHARP_BUZZER_IOCTL_START+1) #define SHARP_BUZZER_GETVOLUME (SHARP_BUZZER_IOCTL_START+2) #define SHARP_BUZZER_ISSUPPORTED (SHARP_BUZZER_IOCTL_START+3) #define SHARP_BUZZER_SETMUTE (SHARP_BUZZER_IOCTL_START+4) #define SHARP_BUZZER_STOPSOUND (SHARP_BUZZER_IOCTL_START+5) //#define SHARP_BUZ_TOUCHSOUND 1 /* touch panel sound */ //#define SHARP_BUZ_KEYSOUND 2 /* key sound */ //#define SHARP_PDA_ILLCLICKSOUND 3 /* illegal click */ //#define SHARP_PDA_WARNSOUND 4 /* warning occurred */ //#define SHARP_PDA_ERRORSOUND 5 /* error occurred */ //#define SHARP_PDA_CRITICALSOUND 6 /* critical error occurred */ //#define SHARP_PDA_SYSSTARTSOUND 7 /* system start */ //#define SHARP_PDA_SYSTEMENDSOUND 8 /* system shutdown */ //#define SHARP_PDA_APPSTART 9 /* application start */ //#define SHARP_PDA_APPQUIT 10 /* application ends */ //#define SHARP_BUZ_SCHEDULE_ALARM 11 /* schedule alarm */ //#define SHARP_BUZ_DAILY_ALARM 12 /* daily alarm */ //#define SHARP_BUZ_GOT_PHONE_CALL 13 /* phone call sound */ //#define SHARP_BUZ_GOT_MAIL 14 /* mail sound */ // #define SHARP_LED_IOCTL_START (SHARP_DEV_IOCTL_COMMAND_START) #define SHARP_LED_SETSTATUS (SHARP_LED_IOCTL_START+1) #define SHARP_IOCTL_GET_ROTATION 0x413c typedef struct sharp_led_status { int which; /* select which LED status is wanted. */ int status; /* set new led status if you call SHARP_LED_SETSTATUS */ } sharp_led_status; #define SHARP_LED_MAIL_EXISTS 9 /* mail status (exists or not) */ #define LED_MAIL_NO_UNREAD_MAIL 0 /* for SHARP_LED_MAIL_EXISTS */ #define LED_MAIL_NEWMAIL_EXISTS 1 /* for SHARP_LED_MAIL_EXISTS */ #define LED_MAIL_UNREAD_MAIL_EX 2 /* for SHARP_LED_MAIL_EXISTS */ // #include <asm/sharp_apm.h> // including kernel headers is evil ... #define APM_IOCGEVTSRC OD_IOR( 'A', 203, int ) #define APM_IOCSEVTSRC OD_IORW( 'A', 204, int ) #define APM_EVT_POWER_BUTTON (1 << 0) #define FL_IOCTL_STEP_CONTRAST 100 void Zaurus::buzzer ( int sound ) { #ifndef QT_NO_SOUND QString soundname; // Not all devices have real sound if ( d->m_model == Model_Zaurus_SLC7x0 || d->m_model == Model_Zaurus_SLB600 ){ switch ( sound ){ case SHARP_BUZ_SCHEDULE_ALARM: soundname = "alarm"; break; case SHARP_BUZ_TOUCHSOUND: soundname = "touchsound"; break; case SHARP_BUZ_KEYSOUND: soundname = "keysound"; break; default: soundname = "alarm"; } } // If a soundname is defined, we expect that this device has // sound capabilities.. Otherwise we expect to have the buzzer // device.. if ( !soundname.isEmpty() ){ int fd; int vol; bool vol_reset = false; Sound snd ( soundname ); if (( fd = ::open ( "/dev/sound/mixer", O_RDWR )) >= 0 ) { if ( ::ioctl ( fd, MIXER_READ( 0 ), &vol ) >= 0 ) { Config cfg ( "qpe" ); cfg. setGroup ( "Volume" ); int volalarm = cfg. readNumEntry ( "AlarmPercent", 50 ); if ( volalarm < 0 ) volalarm = 0; else if ( volalarm > 100 ) volalarm = 100; volalarm |= ( volalarm << 8 ); if ( ::ioctl ( fd, MIXER_WRITE( 0 ), &volalarm ) >= 0 ) vol_reset = true; } } snd. play ( ); while ( !snd. isFinished ( )) qApp-> processEvents ( ); if ( fd >= 0 ) { if ( vol_reset ) ::ioctl ( fd, MIXER_WRITE( 0 ), &vol ); ::close ( fd ); } } else { int fd = ::open ( "/dev/sharp_buz", O_WRONLY|O_NONBLOCK ); if ( fd >= 0 ) { ::ioctl ( fd, SHARP_BUZZER_MAKESOUND, sound ); ::close ( fd ); } } #endif } void Zaurus::alarmSound ( ) { buzzer ( SHARP_BUZ_SCHEDULE_ALARM ); } void Zaurus::touchSound ( ) { buzzer ( SHARP_BUZ_TOUCHSOUND ); } void Zaurus::keySound ( ) { buzzer ( SHARP_BUZ_KEYSOUND ); } QValueList <OLed> Zaurus::ledList ( ) const { QValueList <OLed> vl; vl << Led_Mail; return vl; } QValueList <OLedState> Zaurus::ledStateList ( OLed l ) const { QValueList <OLedState> vl; if ( l == Led_Mail ) vl << Led_Off << Led_On << Led_BlinkSlow; return vl; } OLedState Zaurus::ledState ( OLed which ) const { if ( which == Led_Mail ) return m_leds [0]; else return Led_Off; } bool Zaurus::setLedState ( OLed which, OLedState st ) { if (!m_embedix) // Currently not supported on non_embedix kernels return false; static int fd = ::open ( "/dev/sharp_led", O_RDWR|O_NONBLOCK ); @@ -2109,385 +2109,385 @@ Transformation Zaurus::rotation ( ) const case Model_Zaurus_SLB600: case Model_Zaurus_SL5500: case Model_Zaurus_SL5000: default: rot = d-> m_rotation; break; } return rot; } ODirection Zaurus::direction ( ) const { ODirection dir; int handle = 0; int retval = 0; switch ( d-> m_model ) { case Model_Zaurus_SLC7x0: handle = ::open("/dev/apm_bios", O_RDWR|O_NONBLOCK); if (handle == -1) { dir = CW; } else { retval = ::ioctl(handle, SHARP_IOCTL_GET_ROTATION); ::close (handle); if (retval == 2 ) dir = CCW; else dir = CW; } break; case Model_Zaurus_SLA300: case Model_Zaurus_SLB600: case Model_Zaurus_SL5500: case Model_Zaurus_SL5000: default: dir = d-> m_direction; break; } return dir; } int Zaurus::displayBrightnessResolution ( ) const { if (m_embedix) return d->m_model == Model_Zaurus_SLC7x0 ? 18 : 5; else return 256; } bool Zaurus::hasHingeSensor() const { return d->m_model == Model_Zaurus_SLC7x0; } OHingeStatus Zaurus::readHingeSensor() { int handle = ::open("/dev/apm_bios", O_RDWR|O_NONBLOCK); if (handle == -1) { qWarning("Zaurus::readHingeSensor() - failed (%s)", "unknown reason" ); //FIXME: use strerror return CASE_UNKNOWN; } else { int retval = ::ioctl(handle, SHARP_IOCTL_GET_ROTATION); ::close (handle); if ( retval == CASE_CLOSED || retval == CASE_PORTRAIT || retval == CASE_LANDSCAPE ) { qDebug( "Zaurus::readHingeSensor() - result = %d", retval ); return static_cast<OHingeStatus>( retval ); } else { qWarning("Zaurus::readHingeSensor() - couldn't compute hinge status!" ); return CASE_UNKNOWN; } } } void Zaurus::virtual_hook( int id, void *data ) { switch( id ) { case VIRTUAL_ROTATION:{ VirtRotation* rot = reinterpret_cast<VirtRotation*>( data ); rot->trans = rotation(); break; } case VIRTUAL_DIRECTION:{ VirtDirection *dir = reinterpret_cast<VirtDirection*>( data ); dir->direct = direction(); break; } case VIRTUAL_HAS_HINGE:{ VirtHasHinge *hin = reinterpret_cast<VirtHasHinge*>( data ); hin->hasHinge = hasHingeSensor(); break; } case VIRTUAL_HINGE:{ VirtHingeStatus *hin = reinterpret_cast<VirtHingeStatus*>( data ); hin->hingeStat = readHingeSensor(); break; } default: ODevice::virtual_hook( id, data ); break; } } /************************************************** * * SIMpad * **************************************************/ void SIMpad::init ( ) { d-> m_vendorstr = "SIEMENS"; d-> m_vendor = Vendor_SIEMENS; QFile f ( "/proc/hal/model" ); //TODO Implement model checking //FIXME For now we assume an SL4 d-> m_modelstr = "SL4"; d-> m_model = Model_SIMpad_SL4; switch ( d-> m_model ) { default: d-> m_rotation = Rot0; d-> m_direction = CCW; d-> m_holdtime = 1000; // 1000ms break; } f. setName ( "/etc/familiar-version" ); if ( f. open ( IO_ReadOnly )) { d-> m_systemstr = "Familiar"; d-> m_system = System_Familiar; QTextStream ts ( &f ); d-> m_sysverstr = ts. readLine ( ). mid ( 10 ); f. close ( ); } else { f. setName ( "/etc/oz_version" ); if ( f. open ( IO_ReadOnly )) { d-> m_systemstr = "OpenEmbedded/SIMpad"; d-> m_system = System_OpenZaurus; QTextStream ts ( &f ); ts.setDevice ( &f ); d-> m_sysverstr = ts. readLine ( ); f. close ( ); } } m_leds [0] = m_leds [1] = Led_Off; m_power_timer = 0; } void SIMpad::initButtons ( ) { if ( d-> m_buttons ) return; if ( isQWS( ) ) QWSServer::setKeyboardFilter ( this ); d-> m_buttons = new QValueList <ODeviceButton>; for ( uint i = 0; i < ( sizeof( simpad_buttons ) / sizeof( s_button )); i++ ) { s_button *sb = simpad_buttons + i; ODeviceButton b; if (( sb-> model & d-> m_model ) == d-> m_model ) { b. setKeycode ( sb-> code ); b. setUserText ( QObject::tr ( "Button", sb-> utext )); b. setPixmap ( Resource::loadPixmap ( sb-> pix )); b. setFactoryPresetPressedAction ( OQCopMessage ( makeChannel ( sb-> fpressedservice ), sb-> fpressedaction )); b. setFactoryPresetHeldAction ( OQCopMessage ( makeChannel ( sb-> fheldservice ), sb-> fheldaction )); d-> m_buttons-> append ( b ); } } reloadButtonMapping ( ); QCopChannel *sysch = new QCopChannel ( "QPE/System", this ); - connect ( sysch, SIGNAL( received( const QCString &, const QByteArray & )), this, SLOT( systemMessage ( const QCString &, const QByteArray & ))); + connect ( sysch, SIGNAL( received(const QCString&,const QByteArray&)), this, SLOT( systemMessage(const QCString&,const QByteArray&))); } // SIMpad boardcontrol register CS3 #define SIMPAD_BOARDCONTROL "/proc/cs3" #define SIMPAD_VCC_5V_EN 0x0001 // For 5V PCMCIA #define SIMPAD_VCC_3V_EN 0x0002 // FOR 3.3V PCMCIA #define SIMPAD_EN1 0x0004 // This is only for EPROM's #define SIMPAD_EN0 0x0008 // Both should be enable for 3.3V or 5V #define SIMPAD_DISPLAY_ON 0x0010 #define SIMPAD_PCMCIA_BUFF_DIS 0x0020 #define SIMPAD_MQ_RESET 0x0040 #define SIMPAD_PCMCIA_RESET 0x0080 #define SIMPAD_DECT_POWER_ON 0x0100 #define SIMPAD_IRDA_SD 0x0200 // Shutdown for powersave #define SIMPAD_RS232_ON 0x0400 #define SIMPAD_SD_MEDIAQ 0x0800 // Shutdown for powersave #define SIMPAD_LED2_ON 0x1000 #define SIMPAD_IRDA_MODE 0x2000 // Fast/Slow IrDA mode #define SIMPAD_ENABLE_5V 0x4000 // Enable 5V circuit #define SIMPAD_RESET_SIMCARD 0x8000 //SIMpad touchscreen backlight strength control #define SIMPAD_BACKLIGHT_CONTROL "/proc/driver/mq200/registers/PWM_CONTROL" #define SIMPAD_BACKLIGHT_MASK 0x00a10044 QValueList <OLed> SIMpad::ledList ( ) const { QValueList <OLed> vl; vl << Led_Power; //FIXME which LED is LED2 ? The green one or the amber one? //vl << Led_Mail; //TODO find out if LED1 is accessible anyway return vl; } QValueList <OLedState> SIMpad::ledStateList ( OLed l ) const { QValueList <OLedState> vl; if ( l == Led_Power ) //FIXME which LED is LED2 ? The green one or the amber one? vl << Led_Off << Led_On; //else if ( l == Led_Mail ) //TODO find out if LED1 is accessible anyway //vl << Led_Off; return vl; } OLedState SIMpad::ledState ( OLed l ) const { switch ( l ) { case Led_Power: return m_leds [0]; //case Led_Mail: // return m_leds [1]; default: return Led_Off; } } bool SIMpad::setLedState ( OLed l, OLedState st ) { static int fd = ::open ( SIMPAD_BOARDCONTROL, O_RDWR | O_NONBLOCK ); if ( l == Led_Power ) { if ( fd >= 0 ) { LED_IN leds; ::memset ( &leds, 0, sizeof( leds )); leds. TotalTime = 0; leds. OnTime = 0; leds. OffTime = 1; leds. OffOnBlink = 2; switch ( st ) { case Led_Off : leds. OffOnBlink = 0; break; case Led_On : leds. OffOnBlink = 1; break; case Led_BlinkSlow: leds. OnTime = 10; leds. OffTime = 10; break; case Led_BlinkFast: leds. OnTime = 5; leds. OffTime = 5; break; } { /*TODO Implement this like that: read from cs3 && with SIMPAD_LED2_ON write to cs3 */ m_leds [0] = st; return true; } } } return false; } bool SIMpad::filter ( int /*unicode*/, int keycode, int modifiers, bool isPress, bool autoRepeat ) { //TODO return false; } void SIMpad::timerEvent ( QTimerEvent * ) { killTimer ( m_power_timer ); m_power_timer = 0; QWSServer::sendKeyEvent ( -1, HardKey_Backlight, 0, true, false ); QWSServer::sendKeyEvent ( -1, HardKey_Backlight, 0, false, false ); } void SIMpad::alarmSound ( ) { #ifndef QT_NO_SOUND static Sound snd ( "alarm" ); int fd; int vol; bool vol_reset = false; if (( fd = ::open ( "/dev/sound/mixer", O_RDWR )) >= 0 ) { if ( ::ioctl ( fd, MIXER_READ( 0 ), &vol ) >= 0 ) { Config cfg ( "qpe" ); cfg. setGroup ( "Volume" ); int volalarm = cfg. readNumEntry ( "AlarmPercent", 50 ); if ( volalarm < 0 ) volalarm = 0; else if ( volalarm > 100 ) volalarm = 100; volalarm |= ( volalarm << 8 ); if ( ::ioctl ( fd, MIXER_WRITE( 0 ), &volalarm ) >= 0 ) vol_reset = true; } } snd. play ( ); while ( !snd. isFinished ( )) qApp-> processEvents ( ); if ( fd >= 0 ) { if ( vol_reset ) ::ioctl ( fd, MIXER_WRITE( 0 ), &vol ); ::close ( fd ); } #endif } bool SIMpad::suspend ( ) // Must override because SIMpad does NOT have apm { qDebug( "ODevice for SIMpad: suspend()" ); if ( !isQWS( ) ) // only qwsserver is allowed to suspend return false; bool res = false; struct timeval tvs, tvn; ::gettimeofday ( &tvs, 0 ); ::sync ( ); // flush fs caches res = ( ::system ( "cat /dev/fb/0 >/tmp/.buffer; echo > /proc/sys/pm/suspend; cat /tmp/.buffer >/dev/fb/0" ) == 0 ); //TODO make better :) return res; } bool SIMpad::setSoftSuspend ( bool soft ) { qDebug( "ODevice for SIMpad: UNHANDLED setSoftSuspend(%s)", soft? "on" : "off" ); return false; } bool SIMpad::setDisplayStatus ( bool on ) { qDebug( "ODevice for SIMpad: setDisplayStatus(%s)", on? "on" : "off" ); bool res = false; int fd; QString cmdline = QString().sprintf( "echo %s > /proc/cs3", on ? "0xd41a" : "0xd40a" ); //TODO make better :) res = ( ::system( (const char*) cmdline ) == 0 ); return res; } bool SIMpad::setDisplayBrightness ( int bright ) { qDebug( "ODevice for SIMpad: setDisplayBrightness( %d )", bright ); bool res = false; int fd; if ( bright > 255 ) bright = 255; if ( bright < 1 ) @@ -2609,238 +2609,238 @@ bool Ramses::setSoftSuspend(bool soft) perror("APM_IOCGEVTSRC"); } else perror("APM_IOCGEVTSRC"); ::close(fd); } else perror("/dev/apm_bios or /dev/misc/apm_bios"); return res; #else return true; #endif } bool Ramses::suspend ( ) { qDebug("Ramses::suspend"); return false; } /** * This sets the display on or off */ bool Ramses::setDisplayStatus(bool on) { qDebug("Ramses::setDisplayStatus(%d)", on); #if 0 bool res = false; int fd; if ((fd = ::open ("/dev/fb/0", O_RDWR)) >= 0) { res = (::ioctl(fd, FBIOBLANK, on ? VESA_NO_BLANKING : VESA_POWERDOWN) == 0); ::close(fd); } return res; #else return true; #endif } /* * We get something between 0..255 into us */ bool Ramses::setDisplayBrightness(int bright) { qDebug("Ramses::setDisplayBrightness(%d)", bright); bool res = false; int fd; // pwm1 brighness: 20 steps 500..0 (dunkel->hell) if (bright > 255 ) bright = 255; if (bright < 0) bright = 0; // Turn backlight completely off if ((fd = ::open("/proc/sys/board/lcd_backlight", O_WRONLY)) >= 0) { char writeCommand[10]; const int count = sprintf(writeCommand, "%d\n", bright ? 1 : 0); res = (::write(fd, writeCommand, count) != -1); ::close(fd); } // scale backlight brightness to hardware bright = 500-(bright * 500 / 255); if ((fd = ::open("/proc/sys/board/pwm1", O_WRONLY)) >= 0) { qDebug(" %d -> pwm1", bright); char writeCommand[100]; const int count = sprintf(writeCommand, "%d\n", bright); res = (::write(fd, writeCommand, count) != -1); ::close(fd); } return res; } int Ramses::displayBrightnessResolution() const { return 32; } bool Ramses::setDisplayContrast(int contr) { qDebug("Ramses::setDisplayContrast(%d)", contr); bool res = false; int fd; // pwm0 contrast: 20 steps 79..90 (dunkel->hell) if (contr > 255 ) contr = 255; if (contr < 0) contr = 0; contr = 90 - (contr * 20 / 255); if ((fd = ::open("/proc/sys/board/pwm0", O_WRONLY)) >= 0) { qDebug(" %d -> pwm0", contr); char writeCommand[100]; const int count = sprintf(writeCommand, "%d\n", contr); res = (::write(fd, writeCommand, count) != -1); res = true; ::close(fd); } return res; } int Ramses::displayContrastResolution() const { return 20; } /************************************************** * * * Jornada * * * **************************************************/ bool Jornada::isJornada ( ) { QFile f( "/proc/cpuinfo" ); if ( f. open ( IO_ReadOnly ) ) { QTextStream ts ( &f ); QString line; while( line = ts. readLine ( ) ) { if ( line. left ( 8 ) == "Hardware" ) { int loc = line. find ( ":" ); if ( loc != -1 ) { QString model = line. mid ( loc + 2 ). simplifyWhiteSpace( ); return ( model == "HP Jornada 56x" ); } } } } return false; } void Jornada::init ( ) { d-> m_vendorstr = "HP"; d-> m_vendor = Vendor_HP; d-> m_modelstr = "Jornada 56x"; d-> m_model = Model_Jornada_56x; d-> m_systemstr = "Familiar"; d-> m_system = System_Familiar; d-> m_rotation = Rot0; QFile f ( "/etc/familiar-version" ); f. setName ( "/etc/familiar-version" ); if ( f. open ( IO_ReadOnly )) { QTextStream ts ( &f ); d-> m_sysverstr = ts. readLine ( ). mid ( 10 ); f. close ( ); } } #if 0 void Jornada::initButtons ( ) { if ( d-> m_buttons ) return; // Simulation uses iPAQ 3660 device buttons qDebug ( "init Buttons" ); d-> m_buttons = new QValueList <ODeviceButton>; for ( uint i = 0; i < ( sizeof( ipaq_buttons ) / sizeof( i_button )); i++ ) { i_button *ib = ipaq_buttons + i; ODeviceButton b; if (( ib-> model & Model_iPAQ_H36xx ) == Model_iPAQ_H36xx ) { b. setKeycode ( ib-> code ); b. setUserText ( QObject::tr ( "Button", ib-> utext )); b. setPixmap ( Resource::loadPixmap ( ib-> pix )); b. setFactoryPresetPressedAction ( OQCopMessage ( makeChannel ( ib-> fpressedservice ), ib-> fpressedaction )); b. setFactoryPresetHeldAction ( OQCopMessage ( makeChannel ( ib-> fheldservice ), ib-> fheldaction )); d-> m_buttons-> append ( b ); } } reloadButtonMapping ( ); QCopChannel *sysch = new QCopChannel ( "QPE/System", this ); - connect ( sysch, SIGNAL( received( const QCString &, const QByteArray & )), this, SLOT( systemMessage ( const QCString &, const QByteArray & ))); + connect ( sysch, SIGNAL( received(const QCString&,const QByteArray&)), this, SLOT( systemMessage(const QCString&,const QByteArray&))); } #endif int Jornada::displayBrightnessResolution ( ) const { } bool Jornada::setDisplayBrightness ( int bright ) { bool res = false; int fd; if ( bright > 255 ) bright = 255; if ( bright < 0 ) bright = 0; if (( fd = ::open ( "/dev/touchscreen/0", O_WRONLY )) >= 0 ) { FLITE_IN bl; bl. mode = 1; bl. pwr = bright ? 1 : 0; bl. brightness = ( bright * ( displayBrightnessResolution ( ) - 1 ) + 127 ) / 255; res = ( ::ioctl ( fd, FLITE_ON, &bl ) == 0 ); ::close ( fd ); } return res; } bool Jornada::setSoftSuspend ( bool soft ) { bool res = false; int fd; if (( fd = ::open ( "/proc/sys/ts/suspend_button_mode", O_WRONLY )) >= 0 ) { if ( ::write ( fd, soft ? "1" : "0", 1 ) == 1 ) res = true; else ::perror ( "write to /proc/sys/ts/suspend_button_mode" ); ::close ( fd ); } else ::perror ( "/proc/sys/ts/suspend_button_mode" ); return res; } diff --git a/libopie/ofileselector.cpp b/libopie/ofileselector.cpp index 1ba94ae..2a6aed0 100644 --- a/libopie/ofileselector.cpp +++ b/libopie/ofileselector.cpp @@ -1,584 +1,584 @@ #include <qcombobox.h> #include <qdir.h> #include <qlabel.h> #include <qlayout.h> #include <qlineedit.h> #include <qpopupmenu.h> #include <qwidgetstack.h> /* hacky but we need to get FileSelector::filter */ #define private public #include <qpe/fileselector.h> #undef private #include <qpe/qpeapplication.h> #include <qpe/mimetype.h> #include <qpe/resource.h> #include <qpe/storage.h> #include "ofileselector_p.h" #include "ofileselector.h" OFileViewInterface::OFileViewInterface( OFileSelector* selector ) : m_selector( selector ) { } OFileViewInterface::~OFileViewInterface() { } QString OFileViewInterface::name()const{ return m_name; } void OFileViewInterface::setName( const QString& name ) { m_name = name; } OFileSelector* OFileViewInterface::selector()const { return m_selector; } DocLnk OFileViewInterface::selectedDocument()const { return DocLnk( selectedName() ); } bool OFileViewInterface::showNew()const { return selector()->showNew(); } bool OFileViewInterface::showClose()const { return selector()->showClose(); } MimeTypes OFileViewInterface::mimeTypes()const { return selector()->mimeTypes(); } QStringList OFileViewInterface::currentMimeType()const { return selector()->currentMimeType(); } void OFileViewInterface::activate( const QString& ) { // not implemented here } void OFileViewInterface::ok() { emit selector()->ok(); } void OFileViewInterface::cancel() { emit selector()->cancel(); } void OFileViewInterface::closeMe() { emit selector()->closeMe(); } void OFileViewInterface::fileSelected( const QString& str) { emit selector()->fileSelected( str); } void OFileViewInterface::fileSelected( const DocLnk& lnk) { emit selector()->fileSelected( lnk ); } void OFileViewInterface::setCurrentFileName( const QString& str ) { selector()->m_lneEdit->setText( str ); } QString OFileViewInterface::currentFileName()const{ return selector()->m_lneEdit->text(); } QString OFileViewInterface::startDirectory()const{ return selector()->m_startDir; } ODocumentFileView::ODocumentFileView( OFileSelector* selector ) : OFileViewInterface( selector ) { m_selector = 0; setName( QObject::tr("Documents") ); } ODocumentFileView::~ODocumentFileView() { } QString ODocumentFileView::selectedName()const { if (!m_selector) return QString::null; return m_selector->selectedDocument().file(); } QString ODocumentFileView::selectedPath()const { return QPEApplication::documentDir(); } QString ODocumentFileView::directory()const { return selectedPath(); } void ODocumentFileView::reread() { if (!m_selector) return; m_selector->setNewVisible( showNew() ); m_selector->setCloseVisible( showClose() ); m_selector->filter = currentMimeType().join(";"); m_selector->reread(); } int ODocumentFileView::fileCount()const { if (!m_selector) return -1; return m_selector->fileCount(); } DocLnk ODocumentFileView::selectedDocument()const { if (!m_selector) return DocLnk(); return m_selector->selectedDocument(); } QWidget* ODocumentFileView::widget( QWidget* parent ) { if (!m_selector ) { m_selector = new FileSelector(currentMimeType().join(";"), parent, "fileselector", showNew(), showClose() ); - QObject::connect(m_selector, SIGNAL(fileSelected( const DocLnk& ) ), + QObject::connect(m_selector, SIGNAL(fileSelected(const DocLnk&) ), selector(), SLOT(slotDocLnkBridge(const DocLnk&) ) ); QObject::connect(m_selector, SIGNAL(closeMe() ), selector(), SIGNAL(closeMe() ) ); - QObject::connect(m_selector, SIGNAL(newSelected(const DocLnk& ) ), - selector(), SIGNAL(newSelected(const DocLnk& ) ) ); + QObject::connect(m_selector, SIGNAL(newSelected(const DocLnk&) ), + selector(), SIGNAL(newSelected(const DocLnk&) ) ); } return m_selector; } /* * This is the file system view used * we use a QListView + QListViewItems for it */ OFileSelectorItem::OFileSelectorItem( QListView* view, const QPixmap& pixmap, const QString& path, const QString& date, const QString& size, const QString& dir, bool isLocked, bool isDir ) : QListViewItem( view ) { setPixmap(0, pixmap ); setText(1, path ); setText(2, size ); setText(3, date ); m_isDir = isDir; m_dir = dir; m_locked = isLocked; } OFileSelectorItem::~OFileSelectorItem() { } bool OFileSelectorItem::isLocked()const { return m_locked; } QString OFileSelectorItem::directory()const { return m_dir; } bool OFileSelectorItem::isDir()const { return m_isDir; } QString OFileSelectorItem::path()const { return text( 1 ); } QString OFileSelectorItem::key( int id, bool )const { QString ke; if( id == 0 || id == 1 ){ // name if( m_isDir ){ ke.append("0" ); ke.append( text(1) ); }else{ ke.append("1" ); ke.append( text(1) ); } return ke; }else return text( id ); } OFileViewFileListView::OFileViewFileListView( QWidget* parent, const QString& startDir, OFileSelector* sel) : QWidget( parent ), m_sel( sel ) { m_all = false; QVBoxLayout* lay = new QVBoxLayout( this ); m_currentDir = startDir; /* * now we add a special bar * One Button For Up * Home * Doc * And a dropdown menu with FileSystems * FUTURE: one to change dir with lineedit * Bookmarks * Create Dir */ QHBox* box = new QHBox(this ); box->setBackgroundMode( PaletteButton ); box->setSpacing( 0 ); QToolButton *btn = new QToolButton( box ); btn->setIconSet( Resource::loadIconSet("up") ); connect(btn, SIGNAL(clicked() ), this, SLOT( cdUP() ) ); btn = new QToolButton( box ); btn->setIconSet( Resource::loadIconSet("home") ); connect(btn, SIGNAL(clicked() ), this, SLOT( cdHome() ) ); btn = new QToolButton( box ); btn->setIconSet( Resource::loadIconSet("DocsIcon") ); connect(btn, SIGNAL(clicked() ), this, SLOT(cdDoc() ) ); m_btnNew = new QToolButton( box ); m_btnNew->setIconSet( Resource::loadIconSet("new") ); connect(m_btnNew, SIGNAL(clicked() ), this, SLOT(slotNew() ) ); m_btnClose = new QToolButton( box ); m_btnClose->setIconSet( Resource::loadIconSet("close") ); connect(m_btnClose, SIGNAL(clicked() ), selector(), SIGNAL(closeMe() ) ); btn = new QToolButton( box ); btn->setIconSet( Resource::loadIconSet("cardmon/pcmcia") ); /* let's fill device parts */ QPopupMenu* pop = new QPopupMenu(this); connect(pop, SIGNAL( activated(int) ), this, SLOT(slotFSActivated(int) ) ); StorageInfo storage; const QList<FileSystem> &fs = storage.fileSystems(); QListIterator<FileSystem> it(fs); for ( ; it.current(); ++it ) { const QString disk = (*it)->name(); const QString path = (*it)->path(); m_dev.insert( disk, path ); pop->insertItem( disk ); } m_fsPop = pop; btn->setPopup( pop ); lay->addWidget( box ); m_view = new QListView( this ); m_view->installEventFilter(this); QPEApplication::setStylusOperation( m_view->viewport(), QPEApplication::RightOnHold); m_view->addColumn(" " ); m_view->addColumn(tr("Name"), 135 ); m_view->addColumn(tr("Size"), -1 ); m_view->addColumn(tr("Date"), 60 ); m_view->addColumn(tr("Mime Type"), -1 ); m_view->setSorting( 1 ); m_view->setAllColumnsShowFocus( TRUE ); lay->addWidget( m_view, 1000 ); connectSlots(); } OFileViewFileListView::~OFileViewFileListView() { } void OFileViewFileListView::slotNew() { DocLnk lnk; emit selector()->newSelected( lnk ); } OFileSelectorItem* OFileViewFileListView::currentItem()const{ QListViewItem* item = m_view->currentItem(); if (!item ) return 0l; return static_cast<OFileSelectorItem*>(item); } void OFileViewFileListView::reread( bool all ) { m_view->clear(); if (selector()->showClose() ) m_btnClose->show(); else m_btnClose->hide(); if (selector()->showNew() ) m_btnNew->show(); else m_btnNew->hide(); m_mimes = selector()->currentMimeType(); m_all = all; QDir dir( m_currentDir ); if (!dir.exists() ) return; dir.setSorting( QDir::Name | QDir::DirsFirst | QDir::Reversed ); int filter; if (m_all ) filter = QDir::Files | QDir::Dirs | QDir::Hidden | QDir::All; else filter = QDir::Files | QDir::Dirs | QDir::All; dir.setFilter( filter ); // now go through all files const QFileInfoList *list = dir.entryInfoList(); if (!list) { cdUP(); return; } QFileInfoListIterator it( *list ); QFileInfo *fi; while( (fi=it.current() ) ){ if( fi->fileName() == QString::fromLatin1("..") || fi->fileName() == QString::fromLatin1(".") ){ ++it; continue; } /* * It is a symlink we try to resolve it now but don't let us attack by DOS * */ if( fi->isSymLink() ){ QString file = fi->dirPath( true ) + "/" + fi->readLink(); for( int i = 0; i<=4; i++) { // 5 tries to prevent dos QFileInfo info( file ); if( !info.exists() ){ addSymlink( fi, TRUE ); break; }else if( info.isDir() ){ addDir( fi, TRUE ); break; }else if( info.isFile() ){ addFile( fi, TRUE ); break; }else if( info.isSymLink() ){ file = info.dirPath(true ) + "/" + info.readLink() ; break; }else if( i == 4){ // couldn't resolve symlink add it as symlink addSymlink( fi ); } } // off for loop for symlink resolving }else if( fi->isDir() ) addDir( fi ); else if( fi->isFile() ) addFile( fi ); ++it; } // of while loop m_view->sort(); } int OFileViewFileListView::fileCount()const{ return m_view->childCount(); } QString OFileViewFileListView::currentDir()const{ return m_currentDir; } OFileSelector* OFileViewFileListView::selector() { return m_sel; } bool OFileViewFileListView::eventFilter (QObject *o, QEvent *e) { if ( e->type() == QEvent::KeyPress ) { QKeyEvent *k = (QKeyEvent *)e; if ( (k->key()==Key_Enter) || (k->key()==Key_Return)) { slotClicked( Qt::LeftButton,m_view->currentItem(),QPoint(0,0),0); return true; } } return false; } void OFileViewFileListView::connectSlots() { connect(m_view, SIGNAL(clicked(QListViewItem*) ), this, SLOT(slotCurrentChanged(QListViewItem*) ) ); - connect(m_view, SIGNAL(mouseButtonClicked(int, QListViewItem*, const QPoint&, int ) ), - this, SLOT(slotClicked(int, QListViewItem*, const QPoint&, int ) ) ); + connect(m_view, SIGNAL(mouseButtonClicked(int,QListViewItem*,const QPoint&,int) ), + this, SLOT(slotClicked(int,QListViewItem*,const QPoint&,int) ) ); } void OFileViewFileListView::slotCurrentChanged( QListViewItem* item) { if (!item) return; #if 0 OFileSelectorItem *sel = static_cast<OFileSelectorItem*>(item); if (!sel->isDir() ) { selector()->m_lneEdit->setText( sel->text(1) ); // if in fileselector mode we will emit selected if ( selector()->mode() == OFileSelector::FileSelector ) { qWarning("slot Current Changed"); QStringList str = QStringList::split("->", sel->text(1) ); QString path = sel->directory() + "/" + str[0].stripWhiteSpace(); emit selector()->fileSelected( path ); DocLnk lnk( path ); emit selector()->fileSelected( lnk ); } } #endif } void OFileViewFileListView::slotClicked(int button , QListViewItem* item, const QPoint&, int ) { if (!item || ( button != Qt::LeftButton) ) return; OFileSelectorItem *sel = static_cast<OFileSelectorItem*>(item); if (!sel->isLocked() ) { QStringList str = QStringList::split("->", sel->text(1) ); if (sel->isDir() ) { m_currentDir = sel->directory() + "/" + str[0].stripWhiteSpace(); emit selector()->dirSelected( m_currentDir ); reread( m_all ); }else { // file qWarning("slot Clicked"); selector()->m_lneEdit->setText( str[0].stripWhiteSpace() ); QString path = sel->directory() + "/" + str[0].stripWhiteSpace(); emit selector()->fileSelected( path ); DocLnk lnk( path ); emit selector()->fileSelected( lnk ); } } // not locked } void OFileViewFileListView::addFile( QFileInfo* info, bool symlink ) { MimeType type( info->absFilePath() ); if (!compliesMime( type.id() ) ) return; QPixmap pix = type.pixmap(); QString dir, name; bool locked; if ( pix.isNull() ) { QWMatrix matrix; QPixmap pixer(Resource::loadPixmap("UnknownDocument") ); matrix.scale( .4, .4 ); pix = pixer.xForm( matrix ); } dir = info->dirPath( true ); locked = false; if ( symlink ) name = info->fileName() + " -> " + info->dirPath() + "/" + info->readLink(); else{ name = info->fileName(); if ( ( (selector()->mode() == OFileSelector::Open)&& !info->isReadable() ) || ( (selector()->mode() == OFileSelector::Save)&& !info->isWritable() ) ) { locked = true; pix = Resource::loadPixmap("locked"); } } (void)new OFileSelectorItem( m_view, pix, name, info->lastModified().toString(), QString::number( info->size() ), dir, locked ); } void OFileViewFileListView::addDir( QFileInfo* info, bool symlink ) { bool locked = false; QString name; QPixmap pix; if ( ( ( selector()->mode() == OFileSelector::Open ) && !info->isReadable() ) || ( ( selector()->mode() == OFileSelector::Save ) && !info->isWritable() ) ) { locked = true; if ( symlink ) pix = Resource::loadPixmap( "opie/symlink" ); else pix = Resource::loadPixmap( "lockedfolder" ); }else pix = symlink ? Resource::loadPixmap( "opie/symlink") : Resource::loadPixmap("folder"); name = symlink ? info->fileName() + " -> " + info->dirPath(true) + "/" + info->readLink() : info->fileName(); (void)new OFileSelectorItem( m_view, pix, name, info->lastModified().toString(), QString::number( info->size() ), info->dirPath( true ), locked, true ); } void OFileViewFileListView::addSymlink( QFileInfo* , bool ) { } void OFileViewFileListView::cdUP() { QDir dir( m_currentDir ); dir.cdUp(); if (!dir.exists() ) m_currentDir = "/"; else m_currentDir = dir.absPath(); emit selector()->dirSelected( m_currentDir ); reread( m_all ); } void OFileViewFileListView::cdHome() { m_currentDir = QDir::homeDirPath(); emit selector()->dirSelected( m_currentDir ); reread( m_all ); } void OFileViewFileListView::cdDoc() { m_currentDir = QPEApplication::documentDir(); emit selector()->dirSelected( m_currentDir ); reread( m_all ); } void OFileViewFileListView::changeDir( const QString& dir ) { m_currentDir = dir; emit selector()->dirSelected( m_currentDir ); reread( m_all ); } void OFileViewFileListView::slotFSActivated( int id ) { changeDir ( m_dev[m_fsPop->text(id)] ); } /* check if the mimetype in mime * complies with the one which is current */ /* * We've the mimetype of the file * We need to get the stringlist of the current mimetype * * mime = image@slashjpeg * QStringList = 'image@slash*' * or QStringList = image/jpeg;image/png;application/x-ogg * or QStringList = application/x-ogg;image@slash*; * with all these mime filters it should get acceptes * to do so we need to look if mime is contained inside * the stringlist * if it's contained return true * if not ( I'm no RegExp expert at all ) we'll look if a '@slash*' * is contained in the mimefilter and then we will * look if both are equal until the '/' */ bool OFileViewFileListView::compliesMime( const QString& str) { if (str.isEmpty() || m_mimes.isEmpty() || str.stripWhiteSpace().isEmpty() ) return true; for (QStringList::Iterator it = m_mimes.begin(); it != m_mimes.end(); ++it ) { QRegExp reg( (*it) ); reg.setWildcard( true ); if ( str.find( reg ) != -1 ) return true; } return false; } /* * The listView giving access to the file system! */ class OFileViewFileSystem : public OFileViewInterface { public: OFileViewFileSystem( OFileSelector* ); ~OFileViewFileSystem(); QString selectedName() const; QString selectedPath() const; QString directory()const; void reread(); int fileCount()const; QWidget* widget( QWidget* parent ); void activate( const QString& ); private: OFileViewFileListView* m_view; bool m_all : 1; }; OFileViewFileSystem::OFileViewFileSystem( OFileSelector* sel) : OFileViewInterface( sel ) { m_view = 0; m_all = false; } OFileViewFileSystem::~OFileViewFileSystem() { } QString OFileViewFileSystem::selectedName()const{ if (!m_view ) return QString::null; @@ -591,339 +591,339 @@ QString OFileViewFileSystem::selectedPath()const{ } QString OFileViewFileSystem::directory()const{ if (!m_view) return QString::null; OFileSelectorItem* item = m_view->currentItem(); if (!item ) return QString::null; return QDir(item->directory() ).absPath(); } void OFileViewFileSystem::reread() { if (!m_view) return; m_view->reread( m_all ); } int OFileViewFileSystem::fileCount()const{ if (!m_view ) return -1; return m_view->fileCount(); } QWidget* OFileViewFileSystem::widget( QWidget* parent ) { if (!m_view ) { m_view = new OFileViewFileListView( parent, startDirectory(), selector() ); } return m_view; } void OFileViewFileSystem::activate( const QString& str) { m_all = (str != QObject::tr("Files") ); } /* Selector */ /** * @short new and complete c'tor * * Create a OFileSelector to let the user select a file. It can * either be used to open a file, select a save name in a dir or * as a dropin for the FileSelector. * * <pre> * QMap<QString, QStringList> mimeTypes; * QStringList types; * types << "text@slash* "; * types << "audio@slash*"; * mimeTypes.insert( tr("Audio and Text"), types ); * mimeTypes.insert( tr("All"), "*@slash*); * * now you could create your fileselector * </pre> * * * @param parent the parent of this widget * @param mode The mode from the enum Mode (Open,Save,FILESELECTOR) * @param sel The selector to be used * @param dirName The name of the dir to start int * @param fileName The fileName placed in the fileselector lineedit * @param mimetypes The MimeType map of used mimetypes * @param showNew Show a New Button. Most likely to be used in the FileSelector view. * @param showClose Show a Close Button. Most likely to be used in FileSelector view. * */ OFileSelector::OFileSelector( QWidget* parent, int mode, int sel, const QString& dirName, const QString& fileName, const MimeTypes& mimetypes, bool showNew, bool showClose) : QWidget( parent, "OFileSelector" ) { m_current = 0; m_shNew = showNew; m_shClose = showClose; m_mimeType = mimetypes; m_startDir = dirName; m_mode = mode; m_selector = sel; initUI(); m_lneEdit->setText( fileName ); initMime(); initViews(); QString str; switch ( m_selector ) { default: case Normal: str = QObject::tr("Documents"); m_cmbView->setCurrentItem( 0 ); break; case Extended: str = QObject::tr("Files"); m_cmbView->setCurrentItem( 1 ); break; case ExtendedAll: str = QObject::tr("All Files"); m_cmbView->setCurrentItem( 2 ); break; } slotViewChange( str ); } /** * This a convience c'tor to just substitute the use of FileSelector */ OFileSelector::OFileSelector( const QString& mimeFilter, QWidget* parent, const char* name, bool showNew, bool showClose ) : QWidget( parent, name ) { m_current = 0; m_shNew = showNew; m_shClose = showClose; m_startDir = QPEApplication::documentDir(); if (!mimeFilter.isEmpty() ) m_mimeType.insert(mimeFilter, QStringList::split(";", mimeFilter ) ); m_mode = OFileSelector::FileSelector; m_selector = OFileSelector::Normal; initUI(); initMime(); initViews(); m_cmbView->setCurrentItem( 0 ); slotViewChange( QObject::tr("Documents") ); } /* * INIT UI will set up the basic GUI * Layout: Simple VBoxLayout * On top a WidgetStack containing the Views... * - List View * - Document View * Below we will have a Label + LineEdit * Below we will have two ComoBoxes one for choosing the view one for * choosing the mimetype */ void OFileSelector::initUI() { QVBoxLayout* lay = new QVBoxLayout( this ); m_stack = new QWidgetStack( this ); lay->addWidget( m_stack, 1000 ); m_nameBox = new QHBox( this ); (void)new QLabel( tr("Name:"), m_nameBox ); m_lneEdit = new QLineEdit( m_nameBox ); m_lneEdit ->installEventFilter(this); lay->addWidget( m_nameBox ); m_cmbBox = new QHBox( this ); m_cmbView = new QComboBox( m_cmbBox ); m_cmbMime = new QComboBox( m_cmbBox ); lay->addWidget( m_cmbBox ); } /* * This will make sure that the return key in the name edit causes dialogs to close */ bool OFileSelector::eventFilter (QObject *o, QEvent *e) { if ( e->type() == QEvent::KeyPress ) { QKeyEvent *k = (QKeyEvent *)e; if ( (k->key()==Key_Enter) || (k->key()==Key_Return)) { emit ok(); return true; } } return false; } /* * This will insert the MimeTypes into the Combo Box * And also connect the changed signal * * AutoMimeTyping is disabled for now. It used to reparse a dir and then set available mimetypes */ void OFileSelector::initMime() { MimeTypes::Iterator it; for ( it = m_mimeType.begin(); it != m_mimeType.end(); ++it ) { m_cmbMime->insertItem( it.key() ); } m_cmbMime->setCurrentItem( 0 ); connect( m_cmbMime, SIGNAL(activated(int) ), this, SLOT(slotMimeTypeChanged() ) ); } void OFileSelector::initViews() { m_cmbView->insertItem( QObject::tr("Documents") ); m_cmbView->insertItem( QObject::tr("Files") ); m_cmbView->insertItem( QObject::tr("All Files") ); - connect(m_cmbView, SIGNAL(activated( const QString& ) ), - this, SLOT(slotViewChange( const QString& ) ) ); + connect(m_cmbView, SIGNAL(activated(const QString&) ), + this, SLOT(slotViewChange(const QString&) ) ); m_views.insert( QObject::tr("Documents"), new ODocumentFileView(this) ); /* see above why add both */ OFileViewInterface* in = new OFileViewFileSystem( this ); m_views.insert( QObject::tr("Files"), in ); m_views.insert( QObject::tr("All Files"), in ); } /** * d'tor */ OFileSelector::~OFileSelector() { } /** * Convience function for the fileselector * make sure to delete the DocLnk * * @see DocLnk * @todo remove in ODP */ const DocLnk* OFileSelector::selected() { DocLnk* lnk = new DocLnk( currentView()->selectedDocument() ); return lnk; } /** * * @return the name of the selected file */ QString OFileSelector::selectedName()const{ return currentView()->selectedName(); } /** * @return the selected path */ QString OFileSelector::selectedPath()const { return currentView()->selectedPath(); } /** * @return the directory name */ QString OFileSelector::directory()const { return currentView()->directory(); } /** * @return a DocLnk for the selected document */ DocLnk OFileSelector::selectedDocument()const { return currentView()->selectedDocument(); } /** * @return the number of items for the current view */ int OFileSelector::fileCount()const { return currentView()->fileCount(); } /** * @return reparse the file content */ void OFileSelector::reread() { return currentView()->reread(); } OFileViewInterface* OFileSelector::currentView()const{ return m_current; } bool OFileSelector::showNew()const { return m_shNew; } bool OFileSelector::showClose()const { return m_shClose; } MimeTypes OFileSelector::mimeTypes()const { return m_mimeType; } /** * @return the Mode of the OFileSelector */ int OFileSelector::mode()const{ return m_mode; } /** * @return the Selector of the OFileSelector */ int OFileSelector::selector()const{ return m_selector; } QStringList OFileSelector::currentMimeType()const { return m_mimeType[m_cmbMime->currentText()]; } void OFileSelector::slotMimeTypeChanged() { reread(); } void OFileSelector::slotDocLnkBridge( const DocLnk& lnk) { m_lneEdit->setText( lnk.name() ); emit fileSelected( lnk ); emit fileSelected( lnk.name() ); } void OFileSelector::slotFileBridge( const QString& str) { DocLnk lnk( str ); emit fileSelected( lnk ); } void OFileSelector::slotViewChange( const QString& view ) { OFileViewInterface* interface = m_views[view]; if (!interface) return; interface->activate( view ); if (m_current) m_stack->removeWidget( m_current->widget( m_stack ) ); static int id = 1; m_stack->addWidget( interface->widget(m_stack), id ); m_stack->raiseWidget( id ); interface->reread(); m_current = interface; id++; } void OFileSelector::setNewVisible( bool b ) { m_shNew = b; currentView()->reread(); } void OFileSelector::setCloseVisible( bool b ) { m_shClose = b; currentView()->reread(); } void OFileSelector::setNameVisible( bool b ) { if ( b ) m_nameBox->show(); else m_nameBox->hide(); } diff --git a/libopie/ofontselector.cpp b/libopie/ofontselector.cpp index 7e07008..87b7869 100644 --- a/libopie/ofontselector.cpp +++ b/libopie/ofontselector.cpp @@ -1,328 +1,328 @@ /* =. This file is part of the OPIE Project .=l. Copyright (c) 2002 Robert Griebl <sandman@handhelds.org> .>+-= _;:, .> :=|. This library is free software; you can .> <`_, > . <= redistribute it and/or modify it under :`=1 )Y*s>-.-- : the terms of the GNU Library General Public .="- .-=="i, .._ License as published by the Free Software - . .-<_> .<> Foundation; either version 2 of the License, ._= =} : or (at your option) any later version. .%`+i> _;_. .i_,=:_. -<s. 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 <qlayout.h> #include <qlistbox.h> #include <qcombobox.h> #include <qlabel.h> #include <qmultilineedit.h> #include <qpe/fontdatabase.h> #include "ofontselector.h" class OFontSelectorPrivate { public: QListBox * m_font_family_list; QComboBox * m_font_style_list; QComboBox * m_font_size_list; QMultiLineEdit *m_preview; bool m_pointbug : 1; FontDatabase m_fdb; }; namespace { class FontListItem : public QListBoxText { public: FontListItem ( const QString &t, const QStringList &styles, const QValueList<int> &sizes ) : QListBoxText ( ) { m_name = t; m_styles = styles; m_sizes = sizes; QString str = t; str [0] = str [0]. upper ( ); setText ( str ); } QString family ( ) const { return m_name; } const QStringList &styles ( ) const { return m_styles; } const QValueList<int> &sizes ( ) const { return m_sizes; } private: QStringList m_styles; QValueList<int> m_sizes; QString m_name; }; static int findItemCB ( QComboBox *box, const QString &str ) { for ( int i = 0; i < box-> count ( ); i++ ) { if ( box-> text ( i ) == str ) return i; } return -1; } } /* static same as anon. namespace */ static int qt_version ( ) { const char *qver = qVersion ( ); return ( qver [0] - '0' ) * 100 + ( qver [2] - '0' ) * 10 + ( qver [4] - '0' ); } /** * Constructs the Selector object * @param withpreview If a font preview should be given * @param parent The parent of the Font Selector * @param name The name of the object * @param fl WidgetFlags */ OFontSelector::OFontSelector ( bool withpreview, QWidget *parent, const char *name, WFlags fl ) : QWidget ( parent, name, fl ) { d = new OFontSelectorPrivate ( ); QGridLayout *gridLayout = new QGridLayout ( this, 0, 0, 4, 4 ); gridLayout->setRowStretch ( 4, 10 ); d-> m_font_family_list = new QListBox( this, "FontListBox" ); gridLayout->addMultiCellWidget( d-> m_font_family_list, 0, 4, 0, 0 ); - connect( d-> m_font_family_list, SIGNAL( highlighted( int ) ), this, SLOT( fontFamilyClicked( int ) ) ); + connect( d-> m_font_family_list, SIGNAL( highlighted(int) ), this, SLOT( fontFamilyClicked(int) ) ); QLabel *label = new QLabel( tr( "Style" ), this ); gridLayout->addWidget( label, 0, 1 ); d-> m_font_style_list = new QComboBox( this, "StyleListBox" ); - connect( d-> m_font_style_list, SIGNAL( activated( int ) ), this, SLOT( fontStyleClicked( int ) ) ); + connect( d-> m_font_style_list, SIGNAL( activated(int) ), this, SLOT( fontStyleClicked(int) ) ); gridLayout->addWidget( d-> m_font_style_list, 1, 1 ); label = new QLabel( tr( "Size" ), this ); gridLayout->addWidget( label, 2, 1 ); d-> m_font_size_list = new QComboBox( this, "SizeListBox" ); - connect( d-> m_font_size_list, SIGNAL( activated( int ) ), - this, SLOT( fontSizeClicked( int ) ) ); + connect( d-> m_font_size_list, SIGNAL( activated(int) ), + this, SLOT( fontSizeClicked(int) ) ); gridLayout->addWidget( d-> m_font_size_list, 3, 1 ); d-> m_pointbug = ( qt_version ( ) <= 233 ); if ( withpreview ) { d-> m_preview = new QMultiLineEdit ( this, "Preview" ); d-> m_preview-> setAlignment ( AlignCenter ); d-> m_preview-> setWordWrap ( QMultiLineEdit::WidgetWidth ); d-> m_preview-> setMargin ( 3 ); d-> m_preview-> setText ( tr( "The Quick Brown Fox Jumps Over The Lazy Dog" )); gridLayout-> addRowSpacing ( 5, 4 ); gridLayout-> addMultiCellWidget ( d-> m_preview, 6, 6, 0, 1 ); gridLayout-> setRowStretch ( 6, 5 ); } else d-> m_preview = 0; loadFonts ( d-> m_font_family_list ); } OFontSelector::~OFontSelector ( ) { delete d; } /** * This methods tries to set the font * @param f The wishes font * @return success or failure */ bool OFontSelector::setSelectedFont ( const QFont &f ) { return setSelectedFont ( f. family ( ), d-> m_fdb. styleString ( f ), f. pointSize ( ), QFont::encodingName ( f. charSet ( ))); } /** * This is an overloaded method @see setSelectedFont * @param familyStr The family of the font * @param styleStr The style of the font * @param sizeVal The size of font * @param charset The charset to be used. Will be deprecated by QT3 */ bool OFontSelector::setSelectedFont ( const QString &familyStr, const QString &styleStr, int sizeVal, const QString & charset ) { QString sizeStr = QString::number ( sizeVal ); QListBoxItem *family = d-> m_font_family_list-> findItem ( familyStr ); if ( !family ) family = d-> m_font_family_list-> findItem ( "Helvetica" ); if ( !family ) family = d-> m_font_family_list-> firstItem ( ); d-> m_font_family_list-> setCurrentItem ( family ); fontFamilyClicked ( d-> m_font_family_list-> index ( family )); int style = findItemCB ( d-> m_font_style_list, styleStr ); if ( style < 0 ) style = findItemCB ( d-> m_font_style_list, "Regular" ); if ( style < 0 && d-> m_font_style_list-> count ( ) > 0 ) style = 0; d-> m_font_style_list-> setCurrentItem ( style ); fontStyleClicked ( style ); int size = findItemCB ( d-> m_font_size_list, sizeStr ); if ( size < 0 ) size = findItemCB ( d-> m_font_size_list, "10" ); if ( size < 0 && d-> m_font_size_list-> count ( ) > 0 ) size = 0; d-> m_font_size_list-> setCurrentItem ( size ); fontSizeClicked ( size ); return (( family ) && ( style >= 0 ) && ( size >= 0 )); } /** * This method returns the name, style and size of the currently selected * font or false if no font is selected * @param family The font family will be written there * @param style The style will be written there * @param size The size will be written there * @return success or failure */ bool OFontSelector::selectedFont ( QString &family, QString &style, int &size ) { QString dummy; return selectedFont ( family, style, size, dummy ); } /** * This method does return the font family or QString::null if there is * no font item selected * @return the font family */ QString OFontSelector::fontFamily ( ) const { FontListItem *fli = (FontListItem *) d-> m_font_family_list-> item ( d-> m_font_family_list-> currentItem ( )); return fli ? fli-> family ( ) : QString::null; } /** * This method will return the style of the font or QString::null * @return the style of the font */ QString OFontSelector::fontStyle ( ) const { FontListItem *fli = (FontListItem *) d-> m_font_family_list-> item ( d-> m_font_family_list-> currentItem ( )); int fst = d-> m_font_style_list-> currentItem ( ); return ( fli && fst >= 0 ) ? fli-> styles ( ) [fst] : QString::null; } /** * This method will return the font size or 10 if no font size is available */ int OFontSelector::fontSize ( ) const { FontListItem *fli = (FontListItem *) d-> m_font_family_list-> item ( d-> m_font_family_list-> currentItem ( )); int fsi = d-> m_font_size_list-> currentItem ( ); return ( fli && fsi >= 0 ) ? fli-> sizes ( ) [fsi] : 10; } /** * returns the charset of the font or QString::null */ QString OFontSelector::fontCharSet ( ) const { FontListItem *fli = (FontListItem *) d-> m_font_family_list-> item ( d-> m_font_family_list-> currentItem ( )); return fli ? d-> m_fdb. charSets ( fli-> family ( )) [0] : QString::null; } /** * Overloaded member function see above * @see selectedFont */ bool OFontSelector::selectedFont ( QString &family, QString &style, int &size, QString &charset ) { int ffa = d-> m_font_family_list-> currentItem ( ); int fst = d-> m_font_style_list-> currentItem ( ); int fsi = d-> m_font_size_list-> currentItem ( ); FontListItem *fli = (FontListItem *) d-> m_font_family_list-> item ( ffa ); if ( fli ) { family = fli-> family ( ); style = fst >= 0 ? fli-> styles ( ) [fst] : QString::null; size = fsi >= 0 ? fli-> sizes ( ) [fsi] : 10; charset = d-> m_fdb. charSets ( fli-> family ( )) [0]; return true; } else return false; } void OFontSelector::loadFonts ( QListBox *list ) { QStringList f = d-> m_fdb. families ( ); for ( QStringList::ConstIterator it = f. begin ( ); it != f. end ( ); ++it ) { QValueList <int> ps = d-> m_fdb. pointSizes ( *it ); if ( d-> m_pointbug ) { for ( QValueList <int>::Iterator it = ps. begin ( ); it != ps. end ( ); it++ ) *it /= 10; } list-> insertItem ( new FontListItem ( *it, d-> m_fdb. styles ( *it ), ps )); } } void OFontSelector::fontFamilyClicked ( int index ) { QString oldstyle = d-> m_font_style_list-> currentText ( ); QString oldsize = d-> m_font_size_list-> currentText ( ); FontListItem *fli = (FontListItem *) d-> m_font_family_list-> item ( index ); d-> m_font_style_list-> clear ( ); d-> m_font_style_list-> insertStringList ( fli-> styles ( )); d-> m_font_style_list-> setEnabled ( !fli-> styles ( ). isEmpty ( )); int i; i = findItemCB ( d-> m_font_style_list, oldstyle ); if ( i < 0 ) diff --git a/libopie/orecurrancewidget.cpp b/libopie/orecurrancewidget.cpp index d81851e..33be269 100644 --- a/libopie/orecurrancewidget.cpp +++ b/libopie/orecurrancewidget.cpp @@ -361,272 +361,272 @@ void ORecurranceWidget::slotWeekLabel() { list.append( dayLabel[i - 1] ); } } } QStringList::Iterator itStr; for ( i = 0, itStr = list.begin(); itStr != list.end(); ++itStr, i++ ) { if ( i == 3 ) bNeedCarriage = TRUE; else bNeedCarriage = FALSE; if ( str.isNull() ) str = *itStr; else if ( i == list.count() - 1 ) { if ( i < 2 ) str += tr(" and ") + *itStr; else { if ( bNeedCarriage ) str += tr( ",\nand " ) + *itStr; else str += tr( ", and " ) + *itStr; } } else { if ( bNeedCarriage ) str += ",\n" + *itStr; else str += ", " + *itStr; } } str = str.prepend( tr("on ") ); lblWeekVar->setText( str ); } void ORecurranceWidget::slotMonthLabel(int type) { QString str; if ( currInterval != Month || type > 1 ) return; if ( type == 1 ) str = strMonthDateTemplate.arg( numberPlacing(start.day()) ); else str = strMonthDayTemplate.arg( numberPlacing(week(start))) .arg( dayLabel[start.dayOfWeek() - 1] ); lblRepeat->setText( str ); } void ORecurranceWidget::slotChangeStartOfWeek( bool onMonday ) { startWeekOnMonday = onMonday; // we need to make this unintrusive as possible... int saveSpin = spinFreq->value(); char days = 0; int day; QListIterator<QToolButton> itExtra( listExtra ); for ( day = 1; *itExtra; ++itExtra, day = day << 1 ) { if ( (*itExtra)->isOn() ) { if ( !startWeekOnMonday ) days |= day; else { if ( day == 1 ) days |= ORecur::SUN; else days |= day >> 1; } } } setupWeekly(); spinFreq->setValue( saveSpin ); int buttons; for ( day = 0x01, buttons = 0; buttons < 7; day = day << 1, buttons++ ) { if ( days & day ) { if ( startWeekOnMonday ) fraExtra->setButton( buttons ); else { if ( buttons == 7 ) fraExtra->setButton( 0 ); else fraExtra->setButton( buttons + 1 ); } } } slotWeekLabel(); } void ORecurranceWidget::setupNone() { lblRepeat->setText( tr("No Repeat") ); lblVar1->hide(); lblVar2->hide(); hideExtras(); cmdEnd->hide(); lblFreq->hide(); lblEvery->hide(); lblFreq->hide(); spinFreq->hide(); lblEnd->hide(); lblWeekVar->hide(); } void ORecurranceWidget::setupDaily() { hideExtras(); lblWeekVar->hide(); spinFreq->setValue( 1 ); lblFreq->setText( tr("day(s)") ); lblVar2->show(); showRepeatStuff(); lblRepeat->setText( strDayTemplate ); setupRepeatLabel( 1 ); } void ORecurranceWidget::setupWeekly() { // reshow the buttons... fraExtra->setTitle( tr("Repeat On") ); fraExtra->setExclusive( FALSE ); fraExtra->show(); if ( startWeekOnMonday ) { cmdExtra1->setText( tr("Mon") ); cmdExtra2->setText( tr("Tue") ); cmdExtra3->setText( tr("Wed") ); cmdExtra4->setText( tr("Thu") ); cmdExtra5->setText( tr("Fri") ); cmdExtra6->setText( tr("Sat") ); cmdExtra7->setText( tr("Sun") ); } else { cmdExtra1->setText( tr("Sun") ); cmdExtra2->setText( tr("Mon") ); cmdExtra3->setText( tr("Tue") ); cmdExtra4->setText( tr("Wed") ); cmdExtra5->setText( tr("Thu") ); cmdExtra6->setText( tr("Fri") ); cmdExtra7->setText( tr("Sat") ); } // I hope clustering these improve performance.... cmdExtra1->setOn( FALSE ); cmdExtra2->setOn( FALSE ); cmdExtra3->setOn( FALSE ); cmdExtra4->setOn( FALSE ); cmdExtra5->setOn( FALSE ); cmdExtra6->setOn( FALSE ); cmdExtra7->setOn( FALSE ); cmdExtra1->show(); cmdExtra2->show(); cmdExtra3->show(); cmdExtra4->show(); cmdExtra5->show(); cmdExtra6->show(); cmdExtra7->show(); lblWeekVar->show(); spinFreq->setValue( 1 ); // might as well set the day too... if ( startWeekOnMonday ) { fraExtra->setButton( start.dayOfWeek() - 1 ); } else { fraExtra->setButton( start.dayOfWeek() % 7 ); } lblFreq->setText( tr("week(s)") ); lblVar2->show(); showRepeatStuff(); setupRepeatLabel( 1 ); } void ORecurranceWidget::setupMonthly() { hideExtras(); lblWeekVar->hide(); fraExtra->setTitle( tr("Repeat By") ); fraExtra->setExclusive( TRUE ); fraExtra->show(); cmdExtra1->setText( tr("Day") ); cmdExtra1->show(); cmdExtra2->setText( tr("Date") ); cmdExtra2->show(); spinFreq->setValue( 1 ); lblFreq->setText( tr("month(s)") ); lblVar2->show(); showRepeatStuff(); setupRepeatLabel( 1 ); } void ORecurranceWidget::setupYearly() { hideExtras(); lblWeekVar->hide(); spinFreq->setValue( 1 ); lblFreq->setText( tr("year(s)") ); lblFreq->show(); lblFreq->show(); showRepeatStuff(); lblVar2->show(); QString strEvery = strYearTemplate.arg( start.monthName(start.month()) ).arg( numberPlacing(start.day()) ); lblRepeat->setText( strEvery ); setupRepeatLabel( 1 ); } void ORecurranceWidget::init() { QPopupMenu *m1 = new QPopupMenu( this ); repeatPicker = new DateBookMonth( m1, 0, TRUE ); m1->insertItem( repeatPicker ); cmdEnd->setPopup( m1 ); cmdEnd->setPopupDelay( 0 ); - QObject::connect( repeatPicker, SIGNAL(dateClicked(int, int, int)), - this, SLOT(endDateChanged(int, int, int)) ); + QObject::connect( repeatPicker, SIGNAL(dateClicked(int,int,int)), + this, SLOT(endDateChanged(int,int,int)) ); QObject::connect( qApp, SIGNAL(weekChanged(bool)), this, SLOT(slotChangeStartOfWeek(bool)) ); listRTypeButtons.setAutoDelete( TRUE ); listRTypeButtons.append( cmdNone ); listRTypeButtons.append( cmdDay ); listRTypeButtons.append( cmdWeek ); listRTypeButtons.append( cmdMonth ); listRTypeButtons.append( cmdYear ); listExtra.setAutoDelete( TRUE ); listExtra.append( cmdExtra1 ); listExtra.append( cmdExtra2 ); listExtra.append( cmdExtra3 ); listExtra.append( cmdExtra4 ); listExtra.append( cmdExtra5 ); listExtra.append( cmdExtra6 ); listExtra.append( cmdExtra7 ); } void ORecurranceWidget::hideExtras() { // hide the extra buttons... fraExtra->hide(); chkNoEnd->hide(); QListIterator<QToolButton> it( listExtra ); for ( ; *it; ++it ) { (*it)->hide(); (*it)->setOn( FALSE ); } } void ORecurranceWidget::showRepeatStuff() { cmdEnd->show(); chkNoEnd->show(); lblFreq->show(); lblEvery->show(); lblFreq->show(); spinFreq->show(); lblEnd->show(); lblRepeat->setText( tr("Every") ); } static int week( const QDate &start ) { // figure out the week... int stop = start.day(), sentinel = start.dayOfWeek(), dayOfWeek = QDate( start.year(), start.month(), 1 ).dayOfWeek(), week = 1, i; for ( i = 1; i < stop; i++ ) { if ( dayOfWeek++ == sentinel ) week++; if ( dayOfWeek > 7 ) dayOfWeek = 0; } return week; } static QString numberPlacing( int x ) { // I hope this works in other languages besides english... QString str = QString::number( x ); switch ( x % 10 ) { case 1: str += QWidget::tr( "st" ); break; case 2: str += QWidget::tr( "nd" ); break; case 3: str += QWidget::tr( "rd" ); break; default: str += QWidget::tr( "th" ); break; } return str; } diff --git a/libopie/otabwidget.cpp b/libopie/otabwidget.cpp index 3a9a5ec..52190b2 100644 --- a/libopie/otabwidget.cpp +++ b/libopie/otabwidget.cpp @@ -1,269 +1,269 @@ /* This file is part of the Opie Project Copyright (c) 2002 Dan Williams <williamsdr@acm.org> =. .=l. .>+-= _;:, .> :=|. This program is free software; you can .> <`_, > . <= redistribute it and/or modify it under :`=1 )Y*s>-.-- : the terms of the GNU Library General Public .="- .-=="i, .._ License as published by the Free Software - . .-<_> .<> Foundation; either version 2 of the License, ._= =} : or (at your option) any later version. .%`+i> _;_. .i_,=:_. -<s. This program 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 "otabwidget.h" #include <qpe/applnk.h> #include <qpe/config.h> #include <qpe/resource.h> #include <opie/otabbar.h> #include <qcombobox.h> #include <qwidgetstack.h> OTabWidget::OTabWidget( QWidget *parent, const char *name, TabStyle s, TabPosition p ) : QWidget( parent, name ) { if ( s == Global ) { Config config( "qpe" ); config.setGroup( "Appearance" ); s = ( TabStyle ) config.readNumEntry( "TabStyle", (int) IconTab ); if ( s <= Global || s > IconList) { s = IconTab; } QString pos = config.readEntry( "TabPosition", "Top"); if ( pos == "Bottom" ) { p = Bottom; } else { p = Top; } } widgetStack = new QWidgetStack( this, "widgetstack" ); widgetStack->setFrameStyle( QFrame::NoFrame ); widgetStack->setLineWidth( style().defaultFrameWidth() ); tabBarStack = new QWidgetStack( this, "tabbarstack" ); tabBar = new OTabBar( tabBarStack, "tabbar" ); tabBarStack->addWidget( tabBar, 0 ); - connect( tabBar, SIGNAL( selected( int ) ), this, SLOT( slotTabBarSelected( int ) ) ); + connect( tabBar, SIGNAL( selected(int) ), this, SLOT( slotTabBarSelected(int) ) ); tabList = new QComboBox( false, tabBarStack, "tablist" ); tabBarStack->addWidget( tabList, 1 ); - connect( tabList, SIGNAL( activated( int ) ), this, SLOT( slotTabListSelected( int ) ) ); + connect( tabList, SIGNAL( activated(int) ), this, SLOT( slotTabListSelected(int) ) ); tabBarPosition = p; setTabStyle( s ); setTabPosition( p ); currTab= 0x0; } OTabWidget::~OTabWidget() { } void OTabWidget::addTab( QWidget *child, const QString &icon, const QString &label ) { QPixmap iconset = loadSmooth( icon ); QTab *tab = new QTab(); if ( tabBarStyle == IconTab ) { tab->label = QString::null; } else { tab->label = label; } if ( tabBarStyle == IconTab || tabBarStyle == IconList ) { tab->iconset = new QIconSet( iconset ); } int tabid = tabBar->addTab( tab ); if ( tabBarStyle == IconTab || tabBarStyle == IconList ) { tabList->insertItem( iconset, label, -1 ); } else { tabList->insertItem( label ); } widgetStack->addWidget( child, tabid ); widgetStack->raiseWidget( child ); widgetStack->setFrameStyle( QFrame::StyledPanel | QFrame::Raised ); OTabInfo *tabinfo = new OTabInfo( tabid, child, icon, label ); tabs.append( tabinfo ); selectTab( tabinfo ); } void OTabWidget::removePage( QWidget *childwidget ) { if ( childwidget ) { OTabInfo *tab = tabs.first(); while ( tab && tab->control() != childwidget ) { tab = tabs.next(); } if ( tab && tab->control() == childwidget ) { tabBar->setTabEnabled( tab->id(), FALSE ); tabBar->removeTab( tabBar->tab( tab->id() ) ); int i = 0; while ( i < tabList->count() && tabList->text( i ) != tab->label() ) { i++; } if ( tabList->text( i ) == tab->label() ) { tabList->removeItem( i ); } widgetStack->removeWidget( childwidget ); tabs.remove( tab ); delete tab; currTab = tabs.current(); if ( !currTab ) { widgetStack->setFrameStyle( QFrame::NoFrame ); } setUpLayout(); } } } void OTabWidget::changeTab( QWidget *widget, const QString &iconset, const QString &label) { OTabInfo *currtab = tabs.first(); while ( currtab && currtab->control() != widget ) { currtab = tabs.next(); } if ( currtab && currtab->control() == widget ) { QTab *tab = tabBar->tab( currtab->id() ); QPixmap icon( loadSmooth( iconset ) ); tab->setText( label ); if ( tabBarStyle == IconTab ) tab->setIconSet( icon ); int i = 0; while ( i < tabList->count() && tabList->text( i ) != currtab->label() ) { i++; } if ( i < tabList->count() && tabList->text( i ) == currtab->label() ) { if ( tabBarStyle == IconTab || tabBarStyle == IconList ) { tabList->changeItem( icon, label, i ); } else { tabList->changeItem( label, i ); } } currtab->setLabel( label ); currtab->setIcon( iconset ); } setUpLayout(); } void OTabWidget::setCurrentTab( QWidget *childwidget ) { OTabInfo *currtab = tabs.first(); while ( currtab && currtab->control() != childwidget ) { currtab = tabs.next(); } if ( currtab && currtab->control() == childwidget ) { selectTab( currtab ); } } void OTabWidget::setCurrentTab( const QString &tabname ) { OTabInfo *newtab = tabs.first(); while ( newtab && newtab->label() != tabname ) { newtab = tabs.next(); } if ( newtab && newtab->label() == tabname ) { selectTab( newtab ); } } void OTabWidget::setCurrentTab(int tabindex) { OTabInfo *newtab = tabs.first(); while ( newtab && newtab->id() != tabindex ) { newtab = tabs.next(); } if ( newtab && newtab->id() == tabindex ) { selectTab( newtab ); } } OTabWidget::TabStyle OTabWidget::tabStyle() const { return tabBarStyle; } void OTabWidget::setTabStyle( TabStyle s ) { tabBarStyle = s; if ( tabBarStyle == TextTab || tabBarStyle == IconTab ) { QTab *currtab; for ( OTabInfo *tabinfo = tabs.first(); tabinfo; tabinfo = tabs.next() ) { currtab = tabBar->tab( tabinfo->id() ); if ( tabBarStyle == IconTab ) { currtab->iconset = new QIconSet( loadSmooth( tabinfo->icon() ) ); if ( tabinfo == currTab ) currtab->setText( tabinfo->label() ); else currtab->setText( QString::null ); } else { currtab->iconset = 0x0; currtab->setText( tabinfo->label() ); } } tabBarStack->raiseWidget( tabBar ); } else if ( tabBarStyle == TextList || tabBarStyle == IconList ) { diff --git a/libopie/otimepicker.cpp b/libopie/otimepicker.cpp index 1eca7c5..11b80ed 100644 --- a/libopie/otimepicker.cpp +++ b/libopie/otimepicker.cpp @@ -1,242 +1,242 @@ #include "otimepicker.h" #include <qlayout.h> #include <stdio.h> #include <qlineedit.h> /** * Constructs the widget * @param parent The parent of the OTimePicker * @param name The name of the object * @param fl Window Flags */ OTimePicker::OTimePicker(QWidget* parent, const char* name, WFlags fl) : QWidget(parent,name,fl) { QVBoxLayout *vbox=new QVBoxLayout(this); OClickableLabel *r; QString s; // Hour Row QWidget *row=new QWidget(this); QHBoxLayout *l=new QHBoxLayout(row); vbox->addWidget(row); for (int i=0; i<24; i++) { r=new OClickableLabel(row); hourLst.append(r); s.sprintf("%.2d",i); r->setText(s); r->setToggleButton(true); r->setAlignment(AlignHCenter | AlignVCenter); l->addWidget(r); connect(r, SIGNAL(toggled(bool)), this, SLOT(slotHour(bool))); if (i==11) { // Second row row=new QWidget(this); l=new QHBoxLayout(row); vbox->addWidget(row); } } // Minute Row row=new QWidget(this); l=new QHBoxLayout(row); vbox->addWidget(row); for (int i=0; i<60; i+=5) { r=new OClickableLabel(row); minuteLst.append(r); s.sprintf("%.2d",i); r->setText(s); r->setToggleButton(true); r->setAlignment(AlignHCenter | AlignVCenter); l->addWidget(r); connect(r, SIGNAL(toggled(bool)), this, SLOT(slotMinute(bool))); } } /** * This method return the current time * @return the time */ QTime OTimePicker::time()const { return tm; } void OTimePicker::slotHour(bool b) { OClickableLabel *r = (OClickableLabel *) sender(); if (b) { QValueListIterator<OClickableLabel *> it; for (it=hourLst.begin(); it!=hourLst.end(); it++) { if (*it != r) (*it)->setOn(false); else tm.setHMS((*it)->text().toInt(), tm.minute(), 0); } emit timeChanged(tm); } else { r->setOn(true); } } void OTimePicker::slotMinute(bool b) { OClickableLabel *r = (OClickableLabel *) sender(); if (b) { QValueListIterator<OClickableLabel *> it; for (it=minuteLst.begin(); it!=minuteLst.end(); it++) { if (*it != r) (*it)->setOn(false); else tm.setHMS(tm.hour(),(*it)->text().toInt(), 0); } emit timeChanged(tm); } else { r->setOn(true); } } /** * Method to set the time. No signal gets emitted during this method call * Minutes must be within 5 minutes step starting at 0 ( 0,5,10,15,20... ) * @param t The time to be set */ void OTimePicker::setTime( const QTime& t) { setTime( t.hour(), t.minute() ); } /** * Method to set the time. No signal gets emitted during this method call * @param h The hour * @param m The minute. Minutes need to set by 5 minute steps */ void OTimePicker::setTime( int h, int m ) { setHour(h); setMinute(m); } /* * FIXME round minutes to the 5 minute arrangement -zecke */ /** * Method to set the minutes * @param m minutes */ void OTimePicker::setMinute(int m) { QString minute; minute.sprintf("%.2d",m); QValueListIterator<OClickableLabel *> it; for (it=minuteLst.begin(); it!=minuteLst.end(); it++) { if ((*it)->text() == minute) (*it)->setOn(true); else (*it)->setOn(false); } tm.setHMS(tm.hour(),m,0); } /** * Method to set the hour */ void OTimePicker::setHour(int h) { QString hour; hour.sprintf("%.2d",h); QValueListIterator<OClickableLabel *> it; for (it=hourLst.begin(); it!=hourLst.end(); it++) { if ((*it)->text() == hour) (*it)->setOn(true); else (*it)->setOn(false); } tm.setHMS(h,tm.minute(),0); } /** * This is a modal Dialog. * * @param parent The parent widget * @param name The name of the object * @param fl Possible window flags */ OTimePickerDialog::OTimePickerDialog ( QWidget* parent, const char* name, WFlags fl ) : OTimePickerDialogBase (parent , name, true , fl) { - connect ( m_timePicker, SIGNAL( timeChanged( const QTime& ) ), - this, SLOT( setTime ( const QTime& ) ) ); - connect ( minuteField, SIGNAL( textChanged ( const QString& ) ), - this, SLOT ( setMinute ( const QString& ) ) ); - connect ( hourField, SIGNAL( textChanged ( const QString& ) ), - this, SLOT ( setHour ( const QString& ) ) ); + connect ( m_timePicker, SIGNAL( timeChanged(const QTime&) ), + this, SLOT( setTime(const QTime&) ) ); + connect ( minuteField, SIGNAL( textChanged(const QString&) ), + this, SLOT ( setMinute(const QString&) ) ); + connect ( hourField, SIGNAL( textChanged(const QString&) ), + this, SLOT ( setHour(const QString&) ) ); } /** * @return the time */ QTime OTimePickerDialog::time()const { return m_time; } /** * Set the time to time * @param time The time to be set */ void OTimePickerDialog::setTime( const QTime& time ) { m_time = time; m_timePicker->setHour ( time.hour() ); m_timePicker->setMinute( time.minute() ); // Set Textfields if ( time.hour() < 10 ) hourField->setText( "0" + QString::number( time.hour() ) ); else hourField->setText( QString::number( time.hour() ) ); if ( time.minute() < 10 ) minuteField->setText( "0" + QString::number( time.minute() ) ); else minuteField->setText( QString::number( time.minute() ) ); } /** * This method takes the current minute and tries to set hour * to hour. This succeeds if the resulting date is valid * @param hour The hour as a string */ void OTimePickerDialog::setHour ( const QString& hour ) { if ( QTime::isValid ( hour.toInt(), m_time.minute() , 00 ) ){ m_time.setHMS ( hour.toInt(), m_time.minute() , 00 ); setTime ( m_time ); } } /** * Method to set a new minute. It tries to convert the string to int and * if the resulting date is valid a new date is set. * @see setHour */ void OTimePickerDialog::setMinute ( const QString& minute ) { if ( QTime::isValid ( m_time.hour(), minute.toInt(), 00 ) ){ m_time.setHMS ( m_time.hour(), minute.toInt(), 00 ); setTime ( m_time ); } } diff --git a/libopie/pim/ocontactaccess.cpp b/libopie/pim/ocontactaccess.cpp index 2e3ec1f..bc359f7 100644 --- a/libopie/pim/ocontactaccess.cpp +++ b/libopie/pim/ocontactaccess.cpp @@ -1,168 +1,173 @@ /* * Class to manage the Contacts. * * Copyright (c) 2002 by Stefan Eilers (Eilers.Stefan@epost.de) * * ===================================================================== * This program 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. * ===================================================================== * Info: This class could just work with a change in the header-file * of the Contact class ! Therefore our libopie only compiles * with our version of libqpe * ===================================================================== * ToDo: XML-Backend: Automatic reload if something was changed... * * * ===================================================================== * Version: $Id$ * ===================================================================== * History: * $Log$ + * Revision 1.9 2004/03/02 12:14:22 alwin + * run the optimize_connect script + * the whole cvs is tagged with "before_optimize_connect" if there are problems you + * can check the diff (but it had compiled and run here) + * * Revision 1.8 2003/05/08 13:55:09 tille * search stuff * and match, toRichText & toShortText in oevent * * Revision 1.7 2002/11/13 14:14:51 eilers * Added sorted for Contacts.. * * Revision 1.6 2002/11/01 15:10:42 eilers * Added regExp-search in database for all fields in a contact. * * Revision 1.5 2002/10/16 10:52:40 eilers * Added some docu to the interface and now using the cache infrastucture by zecke.. :) * * Revision 1.4 2002/10/14 16:21:54 eilers * Some minor interface updates * * Revision 1.3 2002/10/07 17:34:24 eilers * added OBackendFactory for advanced backend access * * Revision 1.2 2002/10/02 16:18:11 eilers * debugged and seems to work almost perfectly .. * * Revision 1.1 2002/09/27 17:11:44 eilers * Added API for accessing the Contact-Database ! It is compiling, but * please do not expect that anything is working ! * I will debug that stuff in the next time .. * Please read README_COMPILE for compiling ! * * */ #include "ocontactaccess.h" #include "obackendfactory.h" #include <qasciidict.h> #include <qdatetime.h> #include <qfile.h> #include <qregexp.h> #include <qlist.h> #include <qcopchannel_qws.h> //#include <qpe/qcopenvelope_qws.h> #include <qpe/global.h> #include <errno.h> #include <fcntl.h> #include <unistd.h> #include <stdlib.h> #include "ocontactaccessbackend_xml.h" OContactAccess::OContactAccess ( const QString appname, const QString , OContactAccessBackend* end, bool autosync ): OPimAccessTemplate<OContact>( end ) { /* take care of the backend. If there is no one defined, we * will use the XML-Backend as default (until we have a cute SQL-Backend..). */ if( end == 0 ) { qWarning ("Using BackendFactory !"); end = OBackendFactory<OContactAccessBackend>::Default( "contact", appname ); } // Set backend locally and in template m_backEnd = end; OPimAccessTemplate<OContact>::setBackEnd (end); /* Connect signal of external db change to function */ QCopChannel *dbchannel = new QCopChannel( "QPE/PIM", this ); - connect( dbchannel, SIGNAL(received(const QCString &, const QByteArray &)), - this, SLOT(copMessage( const QCString &, const QByteArray &)) ); + connect( dbchannel, SIGNAL(received(const QCString&,const QByteArray&)), + this, SLOT(copMessage(const QCString&,const QByteArray&)) ); if ( autosync ){ QCopChannel *syncchannel = new QCopChannel( "QPE/Sync", this ); - connect( syncchannel, SIGNAL(received(const QCString &, const QByteArray &)), - this, SLOT(copMessage( const QCString &, const QByteArray &)) ); + connect( syncchannel, SIGNAL(received(const QCString&,const QByteArray&)), + this, SLOT(copMessage(const QCString&,const QByteArray&)) ); } } OContactAccess::~OContactAccess () { /* The user may forget to save the changed database, therefore try to * do it for him.. */ save(); // delete m_backEnd; is done by template.. } bool OContactAccess::save () { /* If the database was changed externally, we could not save the * Data. This will remove added items which is unacceptable ! * Therefore: Reload database and merge the data... */ if ( OPimAccessTemplate<OContact>::wasChangedExternally() ) reload(); bool status = OPimAccessTemplate<OContact>::save(); if ( !status ) return false; /* Now tell everyone that new data is available. */ QCopEnvelope e( "QPE/PIM", "addressbookUpdated()" ); return true; } const uint OContactAccess::querySettings() { return ( m_backEnd->querySettings() ); } bool OContactAccess::hasQuerySettings ( int querySettings ) const { return ( m_backEnd->hasQuerySettings ( querySettings ) ); } ORecordList<OContact> OContactAccess::sorted( bool ascending, int sortOrder, int sortFilter, int cat ) const { QArray<int> matchingContacts = m_backEnd -> sorted( ascending, sortOrder, sortFilter, cat ); return ( ORecordList<OContact>(matchingContacts, this) ); } bool OContactAccess::wasChangedExternally()const { return ( m_backEnd->wasChangedExternally() ); } void OContactAccess::copMessage( const QCString &msg, const QByteArray & ) { if ( msg == "addressbookUpdated()" ){ qWarning ("OContactAccess: Received addressbokUpdated()"); emit signalChanged ( this ); } else if ( msg == "flush()" ) { qWarning ("OContactAccess: Received flush()"); save (); } else if ( msg == "reload()" ) { qWarning ("OContactAccess: Received reload()"); reload (); emit signalChanged ( this ); } } diff --git a/libopie/pim/opimmainwindow.cpp b/libopie/pim/opimmainwindow.cpp index 2739e26..99a0333 100644 --- a/libopie/pim/opimmainwindow.cpp +++ b/libopie/pim/opimmainwindow.cpp @@ -1,150 +1,150 @@ #include <qapplication.h> #include <qdatetime.h> #include <qcopchannel_qws.h> #include <qpe/sound.h> #include <qpe/qcopenvelope_qws.h> #include <qpe/qpeapplication.h> #include "opimresolver.h" #include "opimmainwindow.h" OPimMainWindow::OPimMainWindow( const QString& service, QWidget* parent, const char* name, WFlags flag ) : QMainWindow( parent, name, flag ), m_rtti(-1), m_service( service ), m_fallBack(0l) { /* * let's generate our QCopChannel */ m_str = QString("QPE/"+m_service).local8Bit(); m_channel= new QCopChannel(m_str, this ); - connect(m_channel, SIGNAL(received(const QCString&, const QByteArray& ) ), - this, SLOT( appMessage( const QCString&, const QByteArray& ) ) ); - connect(qApp, SIGNAL(appMessage(const QCString&, const QByteArray& ) ), - this, SLOT( appMessage( const QCString&, const QByteArray& ) ) ); + connect(m_channel, SIGNAL(received(const QCString&,const QByteArray&) ), + this, SLOT( appMessage(const QCString&,const QByteArray&) ) ); + connect(qApp, SIGNAL(appMessage(const QCString&,const QByteArray&) ), + this, SLOT( appMessage(const QCString&,const QByteArray&) ) ); /* connect flush and reload */ connect(qApp, SIGNAL(flush() ), this, SLOT(flush() ) ); connect(qApp, SIGNAL(reload() ), this, SLOT(reload() ) ); } OPimMainWindow::~OPimMainWindow() { delete m_channel; } QCopChannel* OPimMainWindow::channel() { return m_channel; } void OPimMainWindow::doSetDocument( const QString& ) { } void OPimMainWindow::appMessage( const QCString& cmd, const QByteArray& array ) { bool needShow = false; /* * create demands to create * a new record... */ QDataStream stream(array, IO_ReadOnly); if ( cmd == "create()" ) { raise(); int uid = create(); QCopEnvelope e(m_str, "created(int)" ); e << uid; needShow = true; }else if ( cmd == "remove(int)" ) { int uid; stream >> uid; bool rem = remove( uid ); QCopEnvelope e(m_str, "removed(bool)" ); e << rem; needShow = true; }else if ( cmd == "beam(int)" ) { int uid; stream >> uid; beam( uid); }else if ( cmd == "show(int)" ) { raise(); int uid; stream >> uid; show( uid ); needShow = true; }else if ( cmd == "edit(int)" ) { raise(); int uid; stream >> uid; edit( uid ); }else if ( cmd == "add(int,QByteArray)" ) { int rtti; QByteArray array; stream >> rtti; stream >> array; m_fallBack = record(rtti, array ); if (!m_fallBack) return; add( *m_fallBack ); delete m_fallBack; }else if ( cmd == "alarm(QDateTime,int)" ) { raise(); QDateTime dt; int uid; stream >> dt; stream >> uid; qWarning(" Date: %s Uid: %d", dt.toString().latin1(), uid ); QDateTime current = QDateTime::currentDateTime(); if ( current.time().hour() != dt.time().hour() && current.time().minute() != dt.time().minute() ) return; doAlarm( dt, uid ); needShow = true; } if (needShow ) QPEApplication::setKeepRunning(); } /* implement the url scripting here */ void OPimMainWindow::setDocument( const QString& str) { doSetDocument( str ); } /* * we now try to get the array demarshalled * check if the rtti matches this one */ OPimRecord* OPimMainWindow::record( int rtti, const QByteArray& array ) { if ( service() != rtti ) return 0l; OPimRecord* record = OPimResolver::self()->record( rtti ); QDataStream str(array, IO_ReadOnly ); if ( !record || !record->loadFromStream(str) ) { delete record; record = 0l; } return record; } /* * get the rtti for the service */ int OPimMainWindow::service() { if ( m_rtti == -1 ) m_rtti = OPimResolver::self()->serviceId( m_service ); return m_rtti; } void OPimMainWindow::doAlarm( const QDateTime&, int ) { } void OPimMainWindow::startAlarm(int count ) { m_alarmCount = count; m_playedCount = 0; Sound::soundAlarm(); m_timerId = startTimer( 5000 ); } void OPimMainWindow::killAlarm() { killTimer( m_timerId ); } void OPimMainWindow::timerEvent( QTimerEvent* e) { if ( m_playedCount <m_alarmCount ) { m_playedCount++; Sound::soundAlarm(); }else { killTimer( e->timerId() ); } } diff --git a/libopie2/examples/opieui/osplitter_example/osplitter_mail.cpp b/libopie2/examples/opieui/osplitter_example/osplitter_mail.cpp index a75f9dc..789496c 100644 --- a/libopie2/examples/opieui/osplitter_example/osplitter_mail.cpp +++ b/libopie2/examples/opieui/osplitter_example/osplitter_mail.cpp @@ -1,79 +1,79 @@ #include <qstring.h> #include <qlabel.h> #include <qheader.h> #include <qlayout.h> #include <qpe/qpeapplication.h> #include <opie2/oapplicationfactory.h> #include "osplitter_mail.h" OPIE_EXPORT_APP( OApplicationFactory<ListViews> ) class Folder { int dummy; }; // ----------------------------------------------------------------- ListViews::ListViews( QWidget* p, const char* name, WFlags fl ) : QWidget( p, name, fl ) { qApp->installEventFilter( this ); m_lstFolders.setAutoDelete( true ); QHBoxLayout *lay = new QHBoxLayout(this); m_splitter = new OSplitter( Horizontal, this, "SPlitter 1" ); lay->addWidget( m_splitter ); - connect(m_splitter, SIGNAL(sizeChange(bool, const QSize& ) ), - this, SLOT(slotSizeChange(bool, const QSize& ) ) ); + connect(m_splitter, SIGNAL(sizeChange(bool,const QSize&) ), + this, SLOT(slotSizeChange(bool,const QSize&) ) ); m_overview = new QListView( m_splitter ); m_overview->header()->setClickEnabled( FALSE ); m_overview->addColumn( tr("Folder") ); m_overview->setMaximumWidth( 200 ); m_splitter->addWidget( m_overview, "zoom", tr("Folder Overview") ); m_splitter->setSizeChange( 300 ); /* OSplitter starts with the small mode */ m_messages = 0; m_message = m_attach = 0; splitti = new OSplitter( Vertical, m_splitter, "Splitti2" ); splitti->setSizeChange( 300 ); splitti->setSizePolicy( QSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding ) ); QLabel *lbl = new QLabel(splitti); lbl->setTextFormat ( Qt::RichText ); lbl->setText("<br><br><b>Test Test Test</b><br><br><p>Fooooo hjhh</p>"); m_messages = new QListView( splitti ); m_messages->addColumn(" Messages "); folder1 = new QListView( splitti ); folder1->addColumn( "Messages 2 " ); splitti->addWidget(m_messages, "mail", tr("Mails") ); splitti->addWidget(folder1, "folder", tr("Folder") ); splitti->addWidget( lbl, "logo", tr("Label") ); m_message = lbl; m_splitter->addWidget( splitti ); } ListViews::~ListViews() { } bool ListViews::eventFilter( QObject* obj, QEvent* ev ) { if (!obj->isWidgetType() ) return false; if ( ev->type() == QEvent::MouseButtonRelease ) { qWarning(" name %s, class %s", obj->name(), obj->className() ); } return false; } diff --git a/libopie2/examples/opieui/oversatileviewdemo/opieuidemo.cpp b/libopie2/examples/opieui/oversatileviewdemo/opieuidemo.cpp index f62729c..0d8bc9f 100644 --- a/libopie2/examples/opieui/oversatileviewdemo/opieuidemo.cpp +++ b/libopie2/examples/opieui/oversatileviewdemo/opieuidemo.cpp @@ -1,205 +1,205 @@ /********************************************************************** ** Copyright (C) 2002 Michael 'Mickey' Lauer. All rights reserved. ** ** This file is part of Opie Environment. ** ** This file may be distributed and/or modified under the terms of the ** GNU General Public License version 2 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. ** ** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE ** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. ** ***********************************************************************/ // Qt #include <qcolor.h> #include <qpopupmenu.h> #include <qmenubar.h> #include <qmessagebox.h> #include <qvbox.h> #include <qstring.h> #include <qstringlist.h> // Qtopia #ifdef QWS #include <qpe/qpeapplication.h> #include <qpe/global.h> #endif // Opie #ifdef QWS #include <opie2/odevice.h> using namespace Opie; #endif #include <opie2/ocompletionbox.h> #include <opie2/olineedit.h> #include <opie2/ocombobox.h> #include <opie2/oeditlistbox.h> #include <opie2/oselector.h> #include <opie2/opopupmenu.h> #include <qtabwidget.h> #include "oversatileviewdemo.h" // Local #include "opieuidemo.h" enum Demos { ocompletionbox, olineedit, ocombobox, oeditlistbox, oselector }; OpieUIDemo::OpieUIDemo( QWidget* parent, const char* name, WFlags fl ) : QMainWindow( parent, name, fl ) { QMenuBar* mbar = this->menuBar(); OPopupMenu* demo = new OPopupMenu( this ); demo->setTitle( "Title" ); demo->setItemParameter( demo->insertItem( "OCompletionBox", this, SLOT( demo(int) ) ), ocompletionbox ); demo->setItemParameter( demo->insertItem( "OLineEdit", this, SLOT( demo(int) ) ), olineedit ); demo->setItemParameter( demo->insertItem( "OComboBox", this, SLOT( demo(int) ) ), ocombobox ); demo->setItemParameter( demo->insertItem( "OEditListBox", this, SLOT( demo(int) ) ), oeditlistbox ); demo->setItemParameter( demo->insertItem( "OSelector", this, SLOT( demo(int) ) ), oselector ); mbar->insertItem( "Demonstrate", demo ); build(); } OpieUIDemo::~OpieUIDemo() { } void OpieUIDemo::build() { main = new QTabWidget( this, "tabwidget" ); setCentralWidget( main ); main->show(); main->addTab( new OVersatileViewDemo( main ), "VersatileView" ); } void OpieUIDemo::demo( int d ) { switch (d) { case ocompletionbox: demoOCompletionBox(); break; case olineedit: demoOLineEdit(); break; case ocombobox: demoOComboBox(); break; case oeditlistbox: demoOEditListBox(); break; case oselector: demoOSelector(); break; } } void OpieUIDemo::demoOCompletionBox() { qDebug( "ocompletionbox" ); OCompletionBox* box = new OCompletionBox( 0 ); box->insertItem( "This CompletionBox" ); box->insertItem( "Says 'Hello World'" ); box->insertItem( "Here are some" ); box->insertItem( "Additional Items" ); box->insertItem( "Complete Completion Box" ); - connect( box, SIGNAL( activated( const QString& ) ), this, SLOT( messageBox( const QString& ) ) ); + connect( box, SIGNAL( activated(const QString&) ), this, SLOT( messageBox(const QString&) ) ); box->popup(); } void OpieUIDemo::demoOLineEdit() { qDebug( "olineedit" ); OLineEdit *edit = new OLineEdit( 0, "lineedit" ); edit->setCompletionMode( OGlobalSettings::CompletionPopup ); OCompletion* comp = edit->completionObject(); QStringList list; list << "mickeyl@handhelds.org"; list << "mickey@tm.informatik.uni-frankfurt.de"; list << "mickey@vanille.de"; comp->setItems( list ); edit->show(); } void OpieUIDemo::demoOComboBox() { qDebug( "ocombobox" ); OComboBox *combo = new OComboBox( true, 0, "combobox" ); combo->setCompletionMode( OGlobalSettings::CompletionPopup ); OCompletion* comp = combo->completionObject(); QStringList ilist; ilist << "kergoth@handhelds.org"; ilist << "harlekin@handhelds.org"; ilist << "groucho@handhelds.org"; combo->insertStringList( ilist ); QStringList clist; clist << "mickeyl@handhelds.org"; clist << "mickey@tm.informatik.uni-frankfurt.de"; clist << "mickey@vanille.de"; comp->setItems( clist ); combo->show(); } void OpieUIDemo::demoOEditListBox() { qDebug( "oeditlistbox" ); OEditListBox* edit = new OEditListBox( "OEditListBox", 0, "editlistbox" ); edit->lineEdit()->setCompletionMode( OGlobalSettings::CompletionPopup ); OCompletion* comp = edit->lineEdit()->completionObject(); QStringList clist; clist << "Completion everywhere"; clist << "Cool Completion everywhere"; clist << "History History History"; comp->setItems( clist ); QStringList list; list << "kergoth@handhelds.org"; list << "harlekin@handhelds.org"; list << "groucho@handhelds.org"; list << "mickeyl@handhelds.org"; edit->insertStringList( list ); edit->show(); } void OpieUIDemo::demoOSelector() { qDebug( "oselector" ); OHSSelector* sel = new OHSSelector( 0, "gradientselector" ); //#sel->resize( QSize( 200, 30 ) ); //#sel->setColors( QColor( 90, 190, 60 ), QColor( 200, 55, 255 ) ); //#sel->setText( "Dark", "Light" ); sel->show(); } void OpieUIDemo::messageBox( const QString& text ) { QString info; info = "You have selected '" + text + "'"; QMessageBox::information( this, "OpieUIDemo", info ); } diff --git a/libopie2/examples/opieui/oversatileviewdemo/oversatileviewdemo.cpp b/libopie2/examples/opieui/oversatileviewdemo/oversatileviewdemo.cpp index cf1e443..9db4e62 100644 --- a/libopie2/examples/opieui/oversatileviewdemo/oversatileviewdemo.cpp +++ b/libopie2/examples/opieui/oversatileviewdemo/oversatileviewdemo.cpp @@ -1,158 +1,158 @@ /* This file is part of the Opie Project Copyright (C) 2003 Michael 'Mickey' Lauer <mickey@tm.informatik.uni-frankfurt.de> =. .=l. .>+-= _;:, .> :=|. This program is free software; you can .> <`_, > . <= redistribute it and/or modify it under :`=1 )Y*s>-.-- : the terms of the GNU Library General Public .="- .-=="i, .._ License as published by the Free Software - . .-<_> .<> Foundation; either version 2 of the License, ._= =} : or (at your option) any later version. .%`+i> _;_. .i_,=:_. -<s. This program 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 "oversatileviewdemo.h" #include <opie2/oversatileview.h> #include <opie2/oversatileviewitem.h> #include <qstring.h> #include <qpixmap.h> #include <qlistview.h> OVersatileViewDemo::OVersatileViewDemo( QWidget* parent, const char* name, WFlags f ) :QVBox( parent, name, f ) { vv = new OVersatileView( this ); vv->addColumn( "First" ); vv->addColumn( "2nd" ); vv->addColumn( "IIIrd" ); QString counter; QPixmap leaf( "leaf.png" ); QPixmap opened( "folder_opened.png" ); QPixmap closed( "folder_closed.png" ); QPixmap leaf32( "leaf32.png" ); QPixmap opened32( "folder_opened32.png" ); QPixmap closed32( "folder_closed32.png" ); vv->setDefaultPixmaps( OVersatileView::Tree, leaf, opened, closed ); vv->setDefaultPixmaps( OVersatileView::Icons, leaf32, opened32, closed32 ); OVersatileViewItem* item; OVersatileViewItem* item2; for ( int i = 0; i < 5; ++i ) { counter.sprintf( "%d", i ); item = new OVersatileViewItem( vv, "Item", "Text", "Some more", counter ); item->setRenameEnabled( true ); item2 = new OVersatileViewItem( item, "OSubitem", "123", "...", counter ); item2->setRenameEnabled( true ); } connect( vv, SIGNAL( selectionChanged() ), this, SLOT( selectionChanged() ) ); - connect( vv, SIGNAL( selectionChanged( OVersatileViewItem * ) ), this, SLOT( selectionChanged( OVersatileViewItem * ) ) ); - connect( vv, SIGNAL( currentChanged( OVersatileViewItem * ) ), this, SLOT( currentChanged( OVersatileViewItem * ) ) ); - connect( vv, SIGNAL( clicked( OVersatileViewItem * ) ), this, SLOT( clicked( OVersatileViewItem * ) ) ); - connect( vv, SIGNAL( pressed( OVersatileViewItem * ) ), this, SLOT( pressed( OVersatileViewItem * ) ) ); + connect( vv, SIGNAL( selectionChanged(OVersatileViewItem*) ), this, SLOT( selectionChanged(OVersatileViewItem*) ) ); + connect( vv, SIGNAL( currentChanged(OVersatileViewItem*) ), this, SLOT( currentChanged(OVersatileViewItem*) ) ); + connect( vv, SIGNAL( clicked(OVersatileViewItem*) ), this, SLOT( clicked(OVersatileViewItem*) ) ); + connect( vv, SIGNAL( pressed(OVersatileViewItem*) ), this, SLOT( pressed(OVersatileViewItem*) ) ); - connect( vv, SIGNAL( doubleClicked( OVersatileViewItem * ) ), this, SLOT( doubleClicked( OVersatileViewItem * ) ) ); - connect( vv, SIGNAL( returnPressed( OVersatileViewItem * ) ), this, SLOT( returnPressed( OVersatileViewItem * ) ) ); + connect( vv, SIGNAL( doubleClicked(OVersatileViewItem*) ), this, SLOT( doubleClicked(OVersatileViewItem*) ) ); + connect( vv, SIGNAL( returnPressed(OVersatileViewItem*) ), this, SLOT( returnPressed(OVersatileViewItem*) ) ); - connect( vv, SIGNAL( onItem( OVersatileViewItem * ) ), this, SLOT( onItem( OVersatileViewItem * ) ) ); + connect( vv, SIGNAL( onItem(OVersatileViewItem*) ), this, SLOT( onItem(OVersatileViewItem*) ) ); connect( vv, SIGNAL( onViewport() ), this, SLOT( onViewport() ) ); - connect( vv, SIGNAL( expanded( OVersatileViewItem * ) ), this, SLOT( expanded( OVersatileViewItem * ) ) ); - connect( vv, SIGNAL( collapsed( OVersatileViewItem * ) ), this, SLOT( collapsed( OVersatileViewItem * ) ) ); + connect( vv, SIGNAL( expanded(OVersatileViewItem*) ), this, SLOT( expanded(OVersatileViewItem*) ) ); + connect( vv, SIGNAL( collapsed(OVersatileViewItem*) ), this, SLOT( collapsed(OVersatileViewItem*) ) ); connect( vv, SIGNAL( moved() ), this, SLOT( moved() ) ); - connect( vv, SIGNAL( contextMenuRequested( OVersatileViewItem *, const QPoint&, int ) ), this, SLOT( contextMenuRequested( OVersatileViewItem *, const QPoint&, int ) ) ); + connect( vv, SIGNAL( contextMenuRequested(OVersatileViewItem*,const QPoint&,int) ), this, SLOT( contextMenuRequested(OVersatileViewItem*,const QPoint&,int) ) ); } OVersatileViewDemo::~OVersatileViewDemo() { } void OVersatileViewDemo::selectionChanged() { qDebug( "received signal selectionChanged()" ); } void OVersatileViewDemo::selectionChanged( OVersatileViewItem * item ) { qDebug( "received signal selectionChanged(OVersatileViewItem*)" ); } void OVersatileViewDemo::currentChanged( OVersatileViewItem * item ) { qDebug( "received signal currentChanged( OVersatileViewItem * )" ); } void OVersatileViewDemo::clicked( OVersatileViewItem * item ) { qDebug( "received signal clicked( OVersatileViewItem * )" ); } void OVersatileViewDemo::pressed( OVersatileViewItem * item ) { qDebug( "received signal pressed( OVersatileViewItem * )" ); } void OVersatileViewDemo::doubleClicked( OVersatileViewItem *item ) { qDebug( "received signal doubleClicked( OVersatileViewItem *item )" ); } void OVersatileViewDemo::returnPressed( OVersatileViewItem *item ) { qDebug( "received signal returnPressed( OVersatileViewItem *item )" ); } void OVersatileViewDemo::onItem( OVersatileViewItem *item ) { qDebug( "received signal onItem( OVersatileViewItem *item )" ); } void OVersatileViewDemo::onViewport() { qDebug( "received signal onViewport()" ); } void OVersatileViewDemo::expanded( OVersatileViewItem *item ) { qDebug( "received signal expanded( OVersatileViewItem *item )" ); } void OVersatileViewDemo::collapsed( OVersatileViewItem *item ) { qDebug( "received signal collapsed( OVersatileViewItem *item )" ); } void OVersatileViewDemo::moved() { qDebug( "received signal moved( OVersatileViewItem *item )" ); } void OVersatileViewDemo::contextMenuRequested( OVersatileViewItem *item, const QPoint& pos, int col ) { qDebug( "received signal contextMenuRequested( OVersatileViewItem *item )" ); } diff --git a/libopie2/opiecore/device/odevice.cpp b/libopie2/opiecore/device/odevice.cpp index b8d48fe..27b0e53 100644 --- a/libopie2/opiecore/device/odevice.cpp +++ b/libopie2/opiecore/device/odevice.cpp @@ -1,340 +1,340 @@ /* This file is part of the Opie Project Copyright (C) The Opie Team <opie-devel@handhelds.org> =. .=l. .>+-= _;:, .> :=|. This program is free software; you can .> <`_, > . <= redistribute it and/or modify it under :`=1 )Y*s>-.-- : the terms of the GNU Library General Public .="- .-=="i, .._ License as published by the Free Software - . .-<_> .<> Foundation; either version 2 of the License, ._= =} : or (at your option) any later version. .%`+i> _;_. .i_,=:_. -<s. This program 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 "odevice_ipaq.h" #include "odevice_jornada.h" #include "odevice_ramses.h" #include "odevice_simpad.h" #include "odevice_yopy.h" #include "odevice_zaurus.h" /* QT */ #include <qapplication.h> #include <qfile.h> #include <qtextstream.h> #include <qwindowsystem_qws.h> /* OPIE */ #include <qpe/config.h> #include <qpe/resource.h> #include <qpe/sound.h> #include <qpe/qcopenvelope_qws.h> /* STD */ #include <fcntl.h> #include <math.h> #include <stdlib.h> #include <signal.h> #include <sys/ioctl.h> #include <sys/time.h> #include <unistd.h> #ifndef QT_NO_SOUND #include <linux/soundcard.h> #endif const char* PATH_PROC_CPUINFO = "/proc/cpuinfo"; using namespace Opie; ODevice *ODevice::inst() { static ODevice *dev = 0; // rewrite this to only use /proc/cpuinfo or so if ( !dev ) { QFile f( PATH_PROC_CPUINFO ); if ( f.open( IO_ReadOnly ) ) { QTextStream s( &f ); while ( !s.atEnd() ) { QString line; line = s.readLine(); if ( line.startsWith( "Hardware" ) ) { qDebug( "ODevice() - found '%s'", (const char*) line ); if ( line.contains( "sharp", false ) ) dev = new Zaurus(); else if ( line.contains( "ipaq", false ) ) dev = new iPAQ(); else if ( line.contains( "simpad", false ) ) dev = new SIMpad(); else if ( line.contains( "jornada", false ) ) dev = new Jornada(); else if ( line.contains( "ramses", false ) ) dev = new Ramses(); else qWarning( "ODevice() - unknown hardware - using default." ); break; } } } else { qWarning( "ODevice() - can't open '%s' - unknown hardware - using default." ); } if ( !dev ) dev = new ODevice(); dev->init(); } return dev; } ODevice::ODevice() { d = new ODeviceData; d->m_modelstr = "Unknown"; d->m_model = Model_Unknown; d->m_vendorstr = "Unknown"; d->m_vendor = Vendor_Unknown; d->m_systemstr = "Unknown"; d->m_system = System_Unknown; d->m_sysverstr = "0.0"; d->m_rotation = Rot0; d->m_direction = CW; d->m_holdtime = 1000; // 1000ms d->m_buttons = 0; d->m_cpu_frequencies = new QStrList; } void ODevice::systemMessage ( const QCString &msg, const QByteArray & ) { if ( msg == "deviceButtonMappingChanged()" ) { reloadButtonMapping(); } } void ODevice::init() { } /** * This method initialises the button mapping */ void ODevice::initButtons() { if ( d->m_buttons ) return; qDebug ( "init Buttons" ); d->m_buttons = new QValueList <ODeviceButton>; reloadButtonMapping(); QCopChannel *sysch = new QCopChannel ( "QPE/System", this ); - connect ( sysch, SIGNAL( received( const QCString &, const QByteArray & )), this, SLOT( systemMessage ( const QCString &, const QByteArray & ))); + connect ( sysch, SIGNAL( received(const QCString&,const QByteArray&)), this, SLOT( systemMessage(const QCString&,const QByteArray&))); } ODevice::~ODevice() { // we leak m_devicebuttons and m_cpu_frequency // but it's a singleton and it is not so importantant // -zecke delete d; } bool ODevice::setSoftSuspend ( bool /*soft*/ ) { return false; } //#include <linux/apm_bios.h> #define APM_IOC_SUSPEND OD_IO( 'A', 2 ) /** * This method will try to suspend the device * It only works if the user is the QWS Server and the apm application * is installed. * It tries to suspend and then waits some time cause some distributions * do have asynchronus apm implementations. * This method will either fail and return false or it'll suspend the * device and return once the device got woken up * * @return if the device got suspended */ bool ODevice::suspend() { qDebug("ODevice::suspend"); if ( !isQWS( ) ) // only qwsserver is allowed to suspend return false; if ( d->m_model == Model_Unknown ) // better don't suspend in qvfb / on unkown devices return false; bool res = false; ODevice::sendSuspendmsg(); struct timeval tvs, tvn; ::gettimeofday ( &tvs, 0 ); ::sync(); // flush fs caches res = ( ::system ( "apm --suspend" ) == 0 ); // This is needed because the iPAQ apm implementation is asynchronous and we // can not be sure when exactly the device is really suspended // This can be deleted as soon as a stable familiar with a synchronous apm implementation exists. if ( res ) { do { // wait at most 1.5 sec: either suspend didn't work or the device resumed ::usleep ( 200 * 1000 ); ::gettimeofday ( &tvn, 0 ); } while ((( tvn. tv_sec - tvs. tv_sec ) * 1000 + ( tvn. tv_usec - tvs. tv_usec ) / 1000 ) < 1500 ); } return res; } //#include <linux/fb.h> better not rely on kernel headers in userspace ... #define FBIOBLANK OD_IO( 'F', 0x11 ) // 0x4611 /* VESA Blanking Levels */ #define VESA_NO_BLANKING 0 #define VESA_VSYNC_SUSPEND 1 #define VESA_HSYNC_SUSPEND 2 #define VESA_POWERDOWN 3 /** * This sets the display on or off */ bool ODevice::setDisplayStatus ( bool on ) { qDebug("ODevice::setDisplayStatus(%d)", on); if ( d->m_model == Model_Unknown ) return false; bool res = false; int fd; if (( fd = ::open ( "/dev/fb0", O_RDWR )) >= 0 ) { res = ( ::ioctl ( fd, FBIOBLANK, on ? VESA_NO_BLANKING : VESA_POWERDOWN ) == 0 ); ::close ( fd ); } return res; } /** * This sets the display brightness * * @param p The brightness to be set on a scale from 0 to 255 * @return success or failure */ bool ODevice::setDisplayBrightness ( int p) { Q_UNUSED( p ) return false; } /** * @return returns the number of steppings on the brightness slider * in the Light-'n-Power settings. */ int ODevice::displayBrightnessResolution() const { return 16; } /** * This sets the display contrast * @param p The contrast to be set on a scale from 0 to 255 * @return success or failure */ bool ODevice::setDisplayContrast ( int p) { Q_UNUSED( p ) return false; } /** * @return return the max value for the brightness settings slider * or 0 if the device doesn't support setting of a contrast */ int ODevice::displayContrastResolution() const { return 0; } /** * This returns the vendor as string * @return Vendor as QString */ QString ODevice::vendorString() const { return d->m_vendorstr; } /** * This returns the vendor as one of the values of OVendor * @return OVendor */ OVendor ODevice::vendor() const { return d->m_vendor; } /** * This returns the model as a string * @return A string representing the model */ QString ODevice::modelString() const { return d->m_modelstr; } /** * This does return the OModel used */ OModel ODevice::model() const { return d->m_model; } /** * This does return the systen name */ QString ODevice::systemString() const { return d->m_systemstr; } /** * Return System as OSystem value */ OSystem ODevice::system() const { return d->m_system; } /** * @return the version string of the base system */ QString ODevice::systemVersionString() const { return d->m_sysverstr; } diff --git a/libopie2/opiecore/device/odevice_ipaq.cpp b/libopie2/opiecore/device/odevice_ipaq.cpp index cc4b01a..8ecea1b 100644 --- a/libopie2/opiecore/device/odevice_ipaq.cpp +++ b/libopie2/opiecore/device/odevice_ipaq.cpp @@ -23,385 +23,385 @@ -_. . . )=. = 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 "odevice_ipaq.h" /* QT */ #include <qapplication.h> #include <qfile.h> #include <qtextstream.h> #include <qwindowsystem_qws.h> /* OPIE */ #include <qpe/config.h> #include <qpe/resource.h> #include <qpe/sound.h> #include <qpe/qcopenvelope_qws.h> /* STD */ #include <fcntl.h> #include <math.h> #include <stdlib.h> #include <signal.h> #include <sys/ioctl.h> #include <sys/time.h> #include <unistd.h> #ifndef QT_NO_SOUND #include <linux/soundcard.h> #endif /* KERNEL */ #define OD_IOC(dir,type,number,size) (( dir << 30 ) | ( type << 8 ) | ( number ) | ( size << 16 )) #define OD_IO(type,number) OD_IOC(0,type,number,0) #define OD_IOW(type,number,size) OD_IOC(1,type,number,sizeof(size)) #define OD_IOR(type,number,size) OD_IOC(2,type,number,sizeof(size)) #define OD_IORW(type,number,size) OD_IOC(3,type,number,sizeof(size)) typedef struct { unsigned char OffOnBlink; /* 0=off 1=on 2=Blink */ unsigned char TotalTime; /* Units of 5 seconds */ unsigned char OnTime; /* units of 100m/s */ unsigned char OffTime; /* units of 100m/s */ } LED_IN; typedef struct { unsigned char mode; unsigned char pwr; unsigned char brightness; } FLITE_IN; #define LED_ON OD_IOW( 'f', 5, LED_IN ) #define FLITE_ON OD_IOW( 'f', 7, FLITE_IN ) struct i_button ipaq_buttons [] = { { Model_iPAQ_H31xx | Model_iPAQ_H36xx | Model_iPAQ_H37xx | Model_iPAQ_H38xx | Model_iPAQ_H39xx | Model_iPAQ_H5xxx, Qt::Key_F9, QT_TRANSLATE_NOOP("Button", "Calendar Button"), "devicebuttons/ipaq_calendar", "datebook", "nextView()", "today", "raise()" }, { Model_iPAQ_H31xx | Model_iPAQ_H36xx | Model_iPAQ_H37xx | Model_iPAQ_H38xx | Model_iPAQ_H39xx | Model_iPAQ_H5xxx, Qt::Key_F10, QT_TRANSLATE_NOOP("Button", "Contacts Button"), "devicebuttons/ipaq_contact", "addressbook", "raise()", "addressbook", "beamBusinessCard()" }, { Model_iPAQ_H31xx | Model_iPAQ_H36xx | Model_iPAQ_H37xx, Qt::Key_F11, QT_TRANSLATE_NOOP("Button", "Menu Button"), "devicebuttons/ipaq_menu", "QPE/TaskBar", "toggleMenu()", "QPE/TaskBar", "toggleStartMenu()" }, { Model_iPAQ_H38xx | Model_iPAQ_H39xx | Model_iPAQ_H5xxx, Qt::Key_F13, QT_TRANSLATE_NOOP("Button", "Mail Button"), "devicebuttons/ipaq_mail", "mail", "raise()", "mail", "newMail()" }, { Model_iPAQ_H31xx | Model_iPAQ_H36xx | Model_iPAQ_H37xx | Model_iPAQ_H38xx | Model_iPAQ_H39xx | Model_iPAQ_H5xxx, Qt::Key_F12, QT_TRANSLATE_NOOP("Button", "Home Button"), "devicebuttons/ipaq_home", "QPE/Launcher", "home()", "buttonsettings", "raise()" }, { Model_iPAQ_H31xx | Model_iPAQ_H36xx | Model_iPAQ_H37xx | Model_iPAQ_H38xx | Model_iPAQ_H39xx | Model_iPAQ_H5xxx, Qt::Key_F24, QT_TRANSLATE_NOOP("Button", "Record Button"), "devicebuttons/ipaq_record", "QPE/VMemo", "toggleRecord()", "sound", "raise()" }, }; void iPAQ::init() { d->m_vendorstr = "HP"; d->m_vendor = Vendor_HP; QFile f ( "/proc/hal/model" ); if ( f. open ( IO_ReadOnly )) { QTextStream ts ( &f ); d->m_modelstr = "H" + ts. readLine(); if ( d->m_modelstr == "H3100" ) d->m_model = Model_iPAQ_H31xx; else if ( d->m_modelstr == "H3600" ) d->m_model = Model_iPAQ_H36xx; else if ( d->m_modelstr == "H3700" ) d->m_model = Model_iPAQ_H37xx; else if ( d->m_modelstr == "H3800" ) d->m_model = Model_iPAQ_H38xx; else if ( d->m_modelstr == "H3900" ) d->m_model = Model_iPAQ_H39xx; else if ( d->m_modelstr == "H5400" ) d->m_model = Model_iPAQ_H5xxx; else d->m_model = Model_Unknown; f. close(); } switch ( d->m_model ) { case Model_iPAQ_H31xx: case Model_iPAQ_H38xx: d->m_rotation = Rot90; break; case Model_iPAQ_H36xx: case Model_iPAQ_H37xx: case Model_iPAQ_H39xx: default: d->m_rotation = Rot270; break; case Model_iPAQ_H5xxx: d->m_rotation = Rot0; } f. setName ( "/etc/familiar-version" ); if ( f. open ( IO_ReadOnly )) { d->m_systemstr = "Familiar"; d->m_system = System_Familiar; QTextStream ts ( &f ); d->m_sysverstr = ts. readLine(). mid ( 10 ); f. close(); } else { f. setName ( "/etc/oz_version" ); if ( f. open ( IO_ReadOnly )) { d->m_systemstr = "OpenEmbedded/iPaq"; d->m_system = System_Familiar; QTextStream ts ( &f ); ts.setDevice ( &f ); d->m_sysverstr = ts. readLine(); f. close(); } } m_leds [0] = m_leds [1] = Led_Off; m_power_timer = 0; } void iPAQ::initButtons() { if ( d->m_buttons ) return; if ( isQWS( ) ) QWSServer::setKeyboardFilter ( this ); d->m_buttons = new QValueList <ODeviceButton>; for ( uint i = 0; i < ( sizeof( ipaq_buttons ) / sizeof( i_button )); i++ ) { i_button *ib = ipaq_buttons + i; ODeviceButton b; if (( ib->model & d->m_model ) == d->m_model ) { b. setKeycode ( ib->code ); b. setUserText ( QObject::tr ( "Button", ib->utext )); b. setPixmap ( Resource::loadPixmap ( ib->pix )); b. setFactoryPresetPressedAction ( OQCopMessage ( makeChannel ( ib->fpressedservice ), ib->fpressedaction )); b. setFactoryPresetHeldAction ( OQCopMessage ( makeChannel ( ib->fheldservice ), ib->fheldaction )); d->m_buttons->append ( b ); } } reloadButtonMapping(); QCopChannel *sysch = new QCopChannel ( "QPE/System", this ); - connect ( sysch, SIGNAL( received( const QCString &, const QByteArray & )), this, SLOT( systemMessage ( const QCString &, const QByteArray & ))); + connect ( sysch, SIGNAL( received(const QCString&,const QByteArray&)), this, SLOT( systemMessage(const QCString&,const QByteArray&))); } QValueList <OLed> iPAQ::ledList() const { QValueList <OLed> vl; vl << Led_Power; if ( d->m_model == Model_iPAQ_H38xx ) vl << Led_BlueTooth; return vl; } QValueList <OLedState> iPAQ::ledStateList ( OLed l ) const { QValueList <OLedState> vl; if ( l == Led_Power ) vl << Led_Off << Led_On << Led_BlinkSlow << Led_BlinkFast; else if ( l == Led_BlueTooth && d->m_model == Model_iPAQ_H38xx ) vl << Led_Off; // << Led_On << ??? return vl; } OLedState iPAQ::ledState ( OLed l ) const { switch ( l ) { case Led_Power: return m_leds [0]; case Led_BlueTooth: return m_leds [1]; default: return Led_Off; } } bool iPAQ::setLedState ( OLed l, OLedState st ) { static int fd = ::open ( "/dev/touchscreen/0", O_RDWR | O_NONBLOCK ); if ( l == Led_Power ) { if ( fd >= 0 ) { LED_IN leds; ::memset ( &leds, 0, sizeof( leds )); leds. TotalTime = 0; leds. OnTime = 0; leds. OffTime = 1; leds. OffOnBlink = 2; switch ( st ) { case Led_Off : leds. OffOnBlink = 0; break; case Led_On : leds. OffOnBlink = 1; break; case Led_BlinkSlow: leds. OnTime = 10; leds. OffTime = 10; break; case Led_BlinkFast: leds. OnTime = 5; leds. OffTime = 5; break; } if ( ::ioctl ( fd, LED_ON, &leds ) >= 0 ) { m_leds [0] = st; return true; } } } return false; } bool iPAQ::filter ( int /*unicode*/, int keycode, int modifiers, bool isPress, bool autoRepeat ) { int newkeycode = keycode; switch ( keycode ) { // H38xx/H39xx have no "Q" key anymore - this is now the Mail key case HardKey_Menu: { if (( d->m_model == Model_iPAQ_H38xx ) || ( d->m_model == Model_iPAQ_H39xx ) || ( d->m_model == Model_iPAQ_H5xxx)) { newkeycode = HardKey_Mail; } break; } // Rotate cursor keys 180° or 270° case Key_Left : case Key_Right: case Key_Up : case Key_Down : { if (( d->m_model == Model_iPAQ_H31xx ) || ( d->m_model == Model_iPAQ_H38xx )) { newkeycode = Key_Left + ( keycode - Key_Left + 2 ) % 4; } // Rotate the cursor keys by 270° // keycode - Key_Left = position of the button starting from left clockwise // add the rotation to it and modolo. No we've the original offset // add the offset to the Key_Left key if ( d-> m_model == Model_iPAQ_H5xxx ) newkeycode = Key_Left + ( keycode - Key_Left + 3 ) % 4; break; } // map Power Button short/long press to F34/F35 case Key_SysReq: { if ( isPress ) { if ( m_power_timer ) killTimer ( m_power_timer ); m_power_timer = startTimer ( 500 ); } else if ( m_power_timer ) { killTimer ( m_power_timer ); m_power_timer = 0; QWSServer::sendKeyEvent ( -1, HardKey_Suspend, 0, true, false ); QWSServer::sendKeyEvent ( -1, HardKey_Suspend, 0, false, false ); } newkeycode = Key_unknown; break; } } if ( newkeycode != keycode ) { if ( newkeycode != Key_unknown ) QWSServer::sendKeyEvent ( -1, newkeycode, modifiers, isPress, autoRepeat ); return true; } else return false; } void iPAQ::timerEvent ( QTimerEvent * ) { killTimer ( m_power_timer ); m_power_timer = 0; QWSServer::sendKeyEvent ( -1, HardKey_Backlight, 0, true, false ); QWSServer::sendKeyEvent ( -1, HardKey_Backlight, 0, false, false ); } void iPAQ::playAlarmSound() { #ifndef QT_NO_SOUND static Sound snd ( "alarm" ); int fd; int vol; bool vol_reset = false; if (( fd = ::open ( "/dev/sound/mixer", O_RDWR )) >= 0 ) { if ( ::ioctl ( fd, MIXER_READ( 0 ), &vol ) >= 0 ) { Config cfg ( "qpe" ); cfg. setGroup ( "Volume" ); int volalarm = cfg. readNumEntry ( "AlarmPercent", 50 ); if ( volalarm < 0 ) volalarm = 0; else if ( volalarm > 100 ) volalarm = 100; volalarm |= ( volalarm << 8 ); if ( ::ioctl ( fd, MIXER_WRITE( 0 ), &volalarm ) >= 0 ) vol_reset = true; } } snd. play(); while ( !snd. isFinished()) qApp->processEvents(); if ( fd >= 0 ) { if ( vol_reset ) ::ioctl ( fd, MIXER_WRITE( 0 ), &vol ); ::close ( fd ); } #endif } bool iPAQ::setSoftSuspend ( bool soft ) { bool res = false; int fd; if (( fd = ::open ( "/proc/sys/ts/suspend_button_mode", O_WRONLY )) >= 0 ) { if ( ::write ( fd, soft ? "1" : "0", 1 ) == 1 ) res = true; else ::perror ( "write to /proc/sys/ts/suspend_button_mode" ); ::close ( fd ); } else ::perror ( "/proc/sys/ts/suspend_button_mode" ); return res; } diff --git a/libopie2/opiecore/device/odevice_simpad.cpp b/libopie2/opiecore/device/odevice_simpad.cpp index 31b9297..90aca2f 100644 --- a/libopie2/opiecore/device/odevice_simpad.cpp +++ b/libopie2/opiecore/device/odevice_simpad.cpp @@ -1,384 +1,384 @@ /* This file is part of the Opie Project Copyright (C) The Opie Team <opie-devel@handhelds.org> =. .=l. .>+-= _;:, .> :=|. This program is free software; you can .> <`_, > . <= redistribute it and/or modify it under :`=1 )Y*s>-.-- : the terms of the GNU Library General Public .="- .-=="i, .._ License as published by the Free Software - . .-<_> .<> Foundation; either version 2 of the License, ._= =} : or (at your option) any later version. .%`+i> _;_. .i_,=:_. -<s. This program 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 "odevice_simpad.h" /* QT */ #include <qapplication.h> #include <qfile.h> #include <qtextstream.h> #include <qwindowsystem_qws.h> /* OPIE */ #include <qpe/config.h> #include <qpe/resource.h> #include <qpe/sound.h> #include <qpe/qcopenvelope_qws.h> /* STD */ #include <fcntl.h> #include <math.h> #include <stdlib.h> #include <signal.h> #include <sys/ioctl.h> #include <sys/time.h> #include <unistd.h> #ifndef QT_NO_SOUND #include <linux/soundcard.h> #endif using namespace Opie; struct s_button simpad_buttons [] = { { Model_SIMpad_CL4 | Model_SIMpad_SL4 | Model_SIMpad_SLC | Model_SIMpad_TSinus, Qt::Key_F9, QT_TRANSLATE_NOOP("Button", "Lower+Up"), "devicebuttons/simpad_lower_up", "datebook", "nextView()", "today", "raise()" }, { Model_SIMpad_CL4 | Model_SIMpad_SL4 | Model_SIMpad_SLC | Model_SIMpad_TSinus, Qt::Key_F10, QT_TRANSLATE_NOOP("Button", "Lower+Down"), "devicebuttons/simpad_lower_down", "addressbook", "raise()", "addressbook", "beamBusinessCard()" }, { Model_SIMpad_CL4 | Model_SIMpad_SL4 | Model_SIMpad_SLC | Model_SIMpad_TSinus, Qt::Key_F11, QT_TRANSLATE_NOOP("Button", "Lower+Right"), "devicebuttons/simpad_lower_right", "QPE/TaskBar", "toggleMenu()", "QPE/TaskBar", "toggleStartMenu()" }, { Model_SIMpad_CL4 | Model_SIMpad_SL4 | Model_SIMpad_SLC | Model_SIMpad_TSinus, Qt::Key_F13, QT_TRANSLATE_NOOP("Button", "Lower+Left"), "devicebuttons/simpad_lower_left", "mail", "raise()", "mail", "newMail()" }, { Model_SIMpad_CL4 | Model_SIMpad_SL4 | Model_SIMpad_SLC | Model_SIMpad_TSinus, Qt::Key_F5, QT_TRANSLATE_NOOP("Button", "Upper+Up"), "devicebuttons/simpad_upper_up", "QPE/Launcher", "home()", "buttonsettings", "raise()" }, { Model_SIMpad_CL4 | Model_SIMpad_SL4 | Model_SIMpad_SLC | Model_SIMpad_TSinus, Qt::Key_F6, QT_TRANSLATE_NOOP("Button", "Upper+Down"), "devicebuttons/simpad_upper_down", "addressbook", "raise()", "addressbook", "beamBusinessCard()" }, { Model_SIMpad_CL4 | Model_SIMpad_SL4 | Model_SIMpad_SLC | Model_SIMpad_TSinus, Qt::Key_F7, QT_TRANSLATE_NOOP("Button", "Upper+Right"), "devicebuttons/simpad_upper_right", "QPE/TaskBar", "toggleMenu()", "QPE/TaskBar", "toggleStartMenu()" }, { Model_SIMpad_CL4 | Model_SIMpad_SL4 | Model_SIMpad_SLC | Model_SIMpad_TSinus, Qt::Key_F13, QT_TRANSLATE_NOOP("Button", "Upper+Left"), "devicebuttons/simpad_upper_left", "QPE/Rotation", "flip()", "QPE/Rotation", "flip()" }, /* { Model_SIMpad_CL4 | Model_SIMpad_SL4 | Model_SIMpad_SLC | Model_SIMpad_TSinus, Qt::Key_F12, QT_TRANSLATE_NOOP("Button", "Lower+Upper"), "devicebuttons/simpad_lower_upper", "QPE/Launcher", "home()", "buttonsettings", "raise()" }, { Model_SIMpad_CL4 | Model_SIMpad_SL4 | Model_SIMpad_SLC | Model_SIMpad_TSinus, Qt::Key_F12, QT_TRANSLATE_NOOP("Button", "Lower+Upper"), "devicebuttons/simpad_upper_lower", "QPE/Launcher", "home()", "buttonsettings", "raise()" }, */ }; void SIMpad::init() { d->m_vendorstr = "SIEMENS"; d->m_vendor = Vendor_SIEMENS; QFile f ( "/proc/hal/model" ); //TODO Implement model checking //FIXME For now we assume an SL4 d->m_modelstr = "SL4"; d->m_model = Model_SIMpad_SL4; switch ( d->m_model ) { default: d->m_rotation = Rot0; d->m_direction = CCW; d->m_holdtime = 1000; // 1000ms break; } f. setName ( "/etc/familiar-version" ); if ( f. open ( IO_ReadOnly )) { d->m_systemstr = "Familiar"; d->m_system = System_Familiar; QTextStream ts ( &f ); d->m_sysverstr = ts. readLine(). mid ( 10 ); f. close(); } else { f. setName ( "/etc/oz_version" ); if ( f. open ( IO_ReadOnly )) { d->m_systemstr = "OpenEmbedded/SIMpad"; d->m_system = System_OpenZaurus; QTextStream ts ( &f ); ts.setDevice ( &f ); d->m_sysverstr = ts. readLine(); f. close(); } } m_leds [0] = m_leds [1] = Led_Off; m_power_timer = 0; } void SIMpad::initButtons() { if ( d->m_buttons ) return; if ( isQWS( ) ) QWSServer::setKeyboardFilter ( this ); d->m_buttons = new QValueList <ODeviceButton>; for ( uint i = 0; i < ( sizeof( simpad_buttons ) / sizeof( s_button )); i++ ) { s_button *sb = simpad_buttons + i; ODeviceButton b; if (( sb->model & d->m_model ) == d->m_model ) { b. setKeycode ( sb->code ); b. setUserText ( QObject::tr ( "Button", sb->utext )); b. setPixmap ( Resource::loadPixmap ( sb->pix )); b. setFactoryPresetPressedAction ( OQCopMessage ( makeChannel ( sb->fpressedservice ), sb->fpressedaction )); b. setFactoryPresetHeldAction ( OQCopMessage ( makeChannel ( sb->fheldservice ), sb->fheldaction )); d->m_buttons->append ( b ); } } reloadButtonMapping(); QCopChannel *sysch = new QCopChannel ( "QPE/System", this ); - connect ( sysch, SIGNAL( received( const QCString &, const QByteArray & )), this, SLOT( systemMessage ( const QCString &, const QByteArray & ))); + connect ( sysch, SIGNAL( received(const QCString&,const QByteArray&)), this, SLOT( systemMessage(const QCString&,const QByteArray&))); } // SIMpad boardcontrol register CS3 #define SIMPAD_BOARDCONTROL "/proc/cs3" #define SIMPAD_VCC_5V_EN 0x0001 // For 5V PCMCIA #define SIMPAD_VCC_3V_EN 0x0002 // FOR 3.3V PCMCIA #define SIMPAD_EN1 0x0004 // This is only for EPROM's #define SIMPAD_EN0 0x0008 // Both should be enable for 3.3V or 5V #define SIMPAD_DISPLAY_ON 0x0010 #define SIMPAD_PCMCIA_BUFF_DIS 0x0020 #define SIMPAD_MQ_RESET 0x0040 #define SIMPAD_PCMCIA_RESET 0x0080 #define SIMPAD_DECT_POWER_ON 0x0100 #define SIMPAD_IRDA_SD 0x0200 // Shutdown for powersave #define SIMPAD_RS232_ON 0x0400 #define SIMPAD_SD_MEDIAQ 0x0800 // Shutdown for powersave #define SIMPAD_LED2_ON 0x1000 #define SIMPAD_IRDA_MODE 0x2000 // Fast/Slow IrDA mode #define SIMPAD_ENABLE_5V 0x4000 // Enable 5V circuit #define SIMPAD_RESET_SIMCARD 0x8000 //SIMpad touchscreen backlight strength control #define SIMPAD_BACKLIGHT_CONTROL "/proc/driver/mq200/registers/PWM_CONTROL" #define SIMPAD_BACKLIGHT_MASK 0x00a10044 QValueList <OLed> SIMpad::ledList() const { QValueList <OLed> vl; vl << Led_Power; //FIXME which LED is LED2 ? The green one or the amber one? //vl << Led_Mail; //TODO find out if LED1 is accessible anyway return vl; } QValueList <OLedState> SIMpad::ledStateList ( OLed l ) const { QValueList <OLedState> vl; if ( l == Led_Power ) //FIXME which LED is LED2 ? The green one or the amber one? vl << Led_Off << Led_On; //else if ( l == Led_Mail ) //TODO find out if LED1 is accessible anyway //vl << Led_Off; return vl; } OLedState SIMpad::ledState ( OLed l ) const { switch ( l ) { case Led_Power: return m_leds [0]; //case Led_Mail: // return m_leds [1]; default: return Led_Off; } } bool SIMpad::setLedState ( OLed l, OLedState st ) { #if 0 static int fd = ::open ( SIMPAD_BOARDCONTROL, O_RDWR | O_NONBLOCK ); /*TODO Implement this like that: read from cs3 && with SIMPAD_LED2_ON write to cs3 */ m_leds [0] = st; return true; } } } #endif return false; } bool SIMpad::filter ( int /*unicode*/, int keycode, int modifiers, bool isPress, bool autoRepeat ) { //TODO return false; } void SIMpad::timerEvent ( QTimerEvent * ) { killTimer ( m_power_timer ); m_power_timer = 0; QWSServer::sendKeyEvent ( -1, HardKey_Backlight, 0, true, false ); QWSServer::sendKeyEvent ( -1, HardKey_Backlight, 0, false, false ); } void SIMpad::playAlarmSound() { #ifndef QT_NO_SOUND static Sound snd ( "alarm" ); int fd; int vol; bool vol_reset = false; if (( fd = ::open ( "/dev/sound/mixer", O_RDWR )) >= 0 ) { if ( ::ioctl ( fd, MIXER_READ( 0 ), &vol ) >= 0 ) { Config cfg ( "qpe" ); cfg. setGroup ( "Volume" ); int volalarm = cfg. readNumEntry ( "AlarmPercent", 50 ); if ( volalarm < 0 ) volalarm = 0; else if ( volalarm > 100 ) volalarm = 100; volalarm |= ( volalarm << 8 ); if ( ::ioctl ( fd, MIXER_WRITE( 0 ), &volalarm ) >= 0 ) vol_reset = true; } } snd. play(); while ( !snd. isFinished()) qApp->processEvents(); if ( fd >= 0 ) { if ( vol_reset ) ::ioctl ( fd, MIXER_WRITE( 0 ), &vol ); ::close ( fd ); } #endif } bool SIMpad::suspend() // Must override because SIMpad does NOT have apm { qDebug( "ODevice for SIMpad: suspend()" ); if ( !isQWS( ) ) // only qwsserver is allowed to suspend return false; bool res = false; ODevice::sendSuspendmsg(); struct timeval tvs, tvn; ::gettimeofday ( &tvs, 0 ); ::sync(); // flush fs caches res = ( ::system ( "cat /dev/fb/0 >/tmp/.buffer; echo > /proc/sys/pm/suspend; cat /tmp/.buffer >/dev/fb/0" ) == 0 ); //TODO make better :) return res; } bool SIMpad::setSoftSuspend ( bool soft ) { qDebug( "ODevice for SIMpad: UNHANDLED setSoftSuspend(%s)", soft? "on" : "off" ); return false; } bool SIMpad::setDisplayStatus ( bool on ) { qDebug( "ODevice for SIMpad: setDisplayStatus(%s)", on? "on" : "off" ); bool res = false; int fd; QString cmdline = QString().sprintf( "echo %s > /proc/cs3", on ? "0xd41a" : "0xd40a" ); //TODO make better :) res = ( ::system( (const char*) cmdline ) == 0 ); return res; } bool SIMpad::setDisplayBrightness ( int bright ) { qDebug( "ODevice for SIMpad: setDisplayBrightness( %d )", bright ); bool res = false; int fd; if ( bright > 255 ) bright = 255; if ( bright < 1 ) bright = 0; if (( fd = ::open ( SIMPAD_BACKLIGHT_CONTROL, O_WRONLY )) >= 0 ) { int value = 255 - bright; const int mask = SIMPAD_BACKLIGHT_MASK; value = value << 8; value += mask; char writeCommand[100]; const int count = sprintf( writeCommand, "0x%x\n", value ); res = ( ::write ( fd, writeCommand, count ) != -1 ); ::close ( fd ); } return res; diff --git a/libopie2/opiecore/device/odevice_yopy.cpp b/libopie2/opiecore/device/odevice_yopy.cpp index a76f90b..d241db8 100644 --- a/libopie2/opiecore/device/odevice_yopy.cpp +++ b/libopie2/opiecore/device/odevice_yopy.cpp @@ -1,163 +1,163 @@ /* This file is part of the Opie Project Copyright (C) The Opie Team <opie-devel@handhelds.org> =. .=l. .>+-= _;:, .> :=|. This program is free software; you can .> <`_, > . <= redistribute it and/or modify it under :`=1 )Y*s>-.-- : the terms of the GNU Library General Public .="- .-=="i, .._ License as published by the Free Software - . .-<_> .<> Foundation; either version 2 of the License, ._= =} : or (at your option) any later version. .%`+i> _;_. .i_,=:_. -<s. This program 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 "odevice_yopy.h" /* QT */ #include <qapplication.h> #include <qfile.h> #include <qtextstream.h> #include <qwindowsystem_qws.h> /* OPIE */ #include <qpe/config.h> #include <qpe/resource.h> #include <qpe/sound.h> #include <qpe/qcopenvelope_qws.h> /* STD */ #include <fcntl.h> #include <math.h> #include <stdlib.h> #include <signal.h> #include <sys/ioctl.h> #include <sys/time.h> #include <unistd.h> #ifndef QT_NO_SOUND #include <linux/soundcard.h> #endif using namespace Opie; struct yopy_button yopy_buttons [] = { { Qt::Key_F10, QT_TRANSLATE_NOOP( "Button", "Action Button" ), "devicebuttons/yopy_action", "datebook", "nextView()", "today", "raise()" }, { Qt::Key_F11, QT_TRANSLATE_NOOP( "Button", "OK Button" ), "devicebuttons/yopy_ok", "addressbook", "raise()", "addressbook", "beamBusinessCard()" }, { Qt::Key_F12, QT_TRANSLATE_NOOP( "Button", "End Button" ), "devicebuttons/yopy_end", "QPE/Launcher", "home()", "buttonsettings", "raise()" }, }; void Yopy::init() { d->m_vendorstr = "G.Mate"; d->m_vendor = Vendor_GMate; d->m_modelstr = "Yopy3700"; d->m_model = Model_Yopy_3700; d->m_rotation = Rot0; d->m_systemstr = "Linupy"; d->m_system = System_Linupy; QFile f ( "/etc/issue" ); if ( f. open ( IO_ReadOnly ) ) { QTextStream ts ( &f ); ts.readLine(); d->m_sysverstr = ts. readLine(); f. close(); } } void Yopy::initButtons() { if ( d->m_buttons ) return ; d->m_buttons = new QValueList <ODeviceButton>; for ( uint i = 0; i < ( sizeof( yopy_buttons ) / sizeof( yopy_button ) ); i++ ) { yopy_button *ib = yopy_buttons + i; ODeviceButton b; b. setKeycode ( ib->code ); b. setUserText ( QObject::tr ( "Button", ib->utext ) ); b. setPixmap ( Resource::loadPixmap ( ib->pix ) ); b. setFactoryPresetPressedAction ( OQCopMessage( makeChannel( ib->fpressedservice ), ib->fpressedaction ) ); b. setFactoryPresetHeldAction ( OQCopMessage( makeChannel( ib->fheldservice ), ib->fheldaction ) ); d->m_buttons->append ( b ); } reloadButtonMapping(); QCopChannel *sysch = new QCopChannel( "QPE/System", this ); - connect( sysch, SIGNAL( received( const QCString &, const QByteArray & ) ), - this, SLOT( systemMessage( const QCString &, const QByteArray & ) ) ); + connect( sysch, SIGNAL( received(const QCString&,const QByteArray&) ), + this, SLOT( systemMessage(const QCString&,const QByteArray&) ) ); } bool Yopy::suspend() { /* Opie for Yopy does not implement its own power management at the moment. The public version runs parallel to X, and relies on the existing power management features. */ return false; } bool Yopy::setDisplayBrightness( int bright ) { /* The code here works, but is disabled as the current version runs parallel to X, and relies on the existing backlight demon. */ #if 0 if ( QFile::exists( "/proc/sys/pm/light" ) ) { int fd = ::open( "/proc/sys/pm/light", O_WRONLY ); if ( fd >= 0 ) { if ( bright ) ::write( fd, "1\n", 2 ); else ::write( fd, "0\n", 2 ); ::close( fd ); return true; } } #endif return false; } int Yopy::displayBrightnessResolution() const { return 2; } diff --git a/libopie2/opiecore/device/odevice_zaurus.cpp b/libopie2/opiecore/device/odevice_zaurus.cpp index 9d23a12..8ab3cbe 100644 --- a/libopie2/opiecore/device/odevice_zaurus.cpp +++ b/libopie2/opiecore/device/odevice_zaurus.cpp @@ -63,386 +63,386 @@ struct z_button z_buttons [] = { { Qt::Key_F10, QT_TRANSLATE_NOOP("Button", "Contacts Button"), "devicebuttons/z_contact", "addressbook", "raise()", "addressbook", "beamBusinessCard()" }, { Qt::Key_F12, QT_TRANSLATE_NOOP("Button", "Home Button"), "devicebuttons/z_home", "QPE/Launcher", "home()", "buttonsettings", "raise()" }, { Qt::Key_F11, QT_TRANSLATE_NOOP("Button", "Menu Button"), "devicebuttons/z_menu", "QPE/TaskBar", "toggleMenu()", "QPE/TaskBar", "toggleStartMenu()" }, { Qt::Key_F13, QT_TRANSLATE_NOOP("Button", "Mail Button"), "devicebuttons/z_mail", "mail", "raise()", "mail", "newMail()" }, }; struct z_button z_buttons_c700 [] = { { Qt::Key_F9, QT_TRANSLATE_NOOP("Button", "Calendar Button"), "devicebuttons/z_calendar", "datebook", "nextView()", "today", "raise()" }, { Qt::Key_F10, QT_TRANSLATE_NOOP("Button", "Contacts Button"), "devicebuttons/z_contact", "addressbook", "raise()", "addressbook", "beamBusinessCard()" }, { Qt::Key_F12, QT_TRANSLATE_NOOP("Button", "Home Button"), "devicebuttons/z_home", "QPE/Launcher", "home()", "buttonsettings", "raise()" }, { Qt::Key_F11, QT_TRANSLATE_NOOP("Button", "Menu Button"), "devicebuttons/z_menu", "QPE/TaskBar", "toggleMenu()", "QPE/TaskBar", "toggleStartMenu()" }, { Qt::Key_F14, QT_TRANSLATE_NOOP("Button", "Display Rotate"), "devicebuttons/z_hinge", "QPE/Rotation", "rotateDefault()", "QPE/Dummy", "doNothing()" }, }; // FIXME This gets unnecessary complicated. We should think about splitting the Zaurus // class up into individual classes. We need three classes // // Zaurus-Collie (SA-model w/ 320x240 lcd, for SL5500 and SL5000) // Zaurus-Poodle (PXA-model w/ 320x240 lcd, for SL5600) // Zaurus-Corgi (PXA-model w/ 640x480 lcd, for C700, C750, C760, and C860) // // Only question right now is: Do we really need to do it? Because as soon // as the OpenZaurus kernel is ready, there will be a unified interface for all // Zaurus models (concerning apm, backlight, buttons, etc.) // // Comments? - mickeyl. void Zaurus::init() { d->m_vendorstr = "Sharp"; d->m_vendor = Vendor_Sharp; m_embedix = true; // Not openzaurus means: It has an embedix kernel ! // QFile f ( "/proc/filesystems" ); QString model; // It isn't a good idea to check the system configuration to // detect the distribution ! // Otherwise it may happen that any other distribution is detected as openzaurus, just // because it uses a jffs2 filesystem.. // (eilers) // if ( f. open ( IO_ReadOnly ) && ( QTextStream ( &f ). read(). find ( "\tjffs2\n" ) >= 0 )) { QFile f ("/etc/oz_version"); if ( f.exists() ){ d->m_vendorstr = "OpenZaurus Team"; d->m_systemstr = "OpenZaurus"; d->m_system = System_OpenZaurus; if ( f. open ( IO_ReadOnly )) { QTextStream ts ( &f ); d->m_sysverstr = ts. readLine();//. mid ( 10 ); f. close(); } // Openzaurus sometimes uses the embedix kernel! // => Check whether this is an embedix kernel FILE *uname = popen("uname -r", "r"); QString line; if ( f.open(IO_ReadOnly, uname) ) { QTextStream ts ( &f ); line = ts. readLine(); int loc = line. find ( "embedix" ); if ( loc != -1 ) m_embedix = true; else m_embedix = false; f. close(); } pclose(uname); } else { d->m_systemstr = "Zaurus"; d->m_system = System_Zaurus; } f. setName ( "/proc/cpuinfo" ); if ( f. open ( IO_ReadOnly ) ) { QTextStream ts ( &f ); QString line; while( line = ts. readLine() ) { if ( line. left ( 8 ) == "Hardware" ) break; } int loc = line. find ( ":" ); if ( loc != -1 ) model = line. mid ( loc + 2 ). simplifyWhiteSpace( ); } if ( model == "SHARP Corgi" ) { d->m_model = Model_Zaurus_SLC7x0; d->m_modelstr = "Zaurus SL-C700"; } else if ( model == "SHARP Shepherd" ) { d->m_model = Model_Zaurus_SLC7x0; d->m_modelstr = "Zaurus SL-C750"; } else if ( model == "SHARP Husky" ) { d->m_model = Model_Zaurus_SLC7x0; d->m_modelstr = "Zaurus SL-C760"; } else if ( model == "SHARP Poodle" ) { d->m_model = Model_Zaurus_SLB600; d->m_modelstr = "Zaurus SL-B500 or SL-5600"; } else if ( model == "Sharp-Collie" || model == "Collie" ) { d->m_model = Model_Zaurus_SL5500; d->m_modelstr = "Zaurus SL-5500 or SL-5000d"; } else { d->m_model = Model_Zaurus_SL5500; d->m_modelstr = "Zaurus (Model unknown)"; } bool flipstate = false; switch ( d->m_model ) { case Model_Zaurus_SLA300: d->m_rotation = Rot0; break; case Model_Zaurus_SLC7x0: d->m_rotation = rotation(); d->m_direction = direction(); break; case Model_Zaurus_SLB600: case Model_Zaurus_SL5500: case Model_Zaurus_SL5000: default: d->m_rotation = Rot270; break; } m_leds [0] = Led_Off; } void Zaurus::initButtons() { if ( d->m_buttons ) return; d->m_buttons = new QValueList <ODeviceButton>; struct z_button * pz_buttons; int buttoncount; switch ( d->m_model ) { case Model_Zaurus_SLC7x0: pz_buttons = z_buttons_c700; buttoncount = ARRAY_SIZE(z_buttons_c700); break; default: pz_buttons = z_buttons; buttoncount = ARRAY_SIZE(z_buttons); break; } for ( int i = 0; i < buttoncount; i++ ) { struct z_button *zb = pz_buttons + i; ODeviceButton b; b. setKeycode ( zb->code ); b. setUserText ( QObject::tr ( "Button", zb->utext )); b. setPixmap ( Resource::loadPixmap ( zb->pix )); b. setFactoryPresetPressedAction ( OQCopMessage ( makeChannel ( zb->fpressedservice ), zb->fpressedaction )); b. setFactoryPresetHeldAction ( OQCopMessage ( makeChannel ( zb->fheldservice ), zb->fheldaction )); d->m_buttons->append ( b ); } reloadButtonMapping(); QCopChannel *sysch = new QCopChannel ( "QPE/System", this ); - connect ( sysch, SIGNAL( received( const QCString &, const QByteArray & )), - this, SLOT( systemMessage ( const QCString &, const QByteArray & ))); + connect ( sysch, SIGNAL( received(const QCString&,const QByteArray&)), + this, SLOT( systemMessage(const QCString&,const QByteArray&))); } #include <unistd.h> #include <fcntl.h> #include <sys/ioctl.h> //#include <asm/sharp_char.h> // including kernel headers is evil ... #define SHARP_DEV_IOCTL_COMMAND_START 0x5680 #define SHARP_BUZZER_IOCTL_START (SHARP_DEV_IOCTL_COMMAND_START) #define SHARP_BUZZER_MAKESOUND (SHARP_BUZZER_IOCTL_START) #define SHARP_BUZ_TOUCHSOUND 1 /* touch panel sound */ #define SHARP_BUZ_KEYSOUND 2 /* key sound */ #define SHARP_BUZ_SCHEDULE_ALARM 11 /* schedule alarm */ /* --- for SHARP_BUZZER device --- */ //#define SHARP_BUZZER_IOCTL_START (SHARP_DEV_IOCTL_COMMAND_START) //#define SHARP_BUZZER_MAKESOUND (SHARP_BUZZER_IOCTL_START) #define SHARP_BUZZER_SETVOLUME (SHARP_BUZZER_IOCTL_START+1) #define SHARP_BUZZER_GETVOLUME (SHARP_BUZZER_IOCTL_START+2) #define SHARP_BUZZER_ISSUPPORTED (SHARP_BUZZER_IOCTL_START+3) #define SHARP_BUZZER_SETMUTE (SHARP_BUZZER_IOCTL_START+4) #define SHARP_BUZZER_STOPSOUND (SHARP_BUZZER_IOCTL_START+5) //#define SHARP_BUZ_TOUCHSOUND 1 /* touch panel sound */ //#define SHARP_BUZ_KEYSOUND 2 /* key sound */ //#define SHARP_PDA_ILLCLICKSOUND 3 /* illegal click */ //#define SHARP_PDA_WARNSOUND 4 /* warning occurred */ //#define SHARP_PDA_ERRORSOUND 5 /* error occurred */ //#define SHARP_PDA_CRITICALSOUND 6 /* critical error occurred */ //#define SHARP_PDA_SYSSTARTSOUND 7 /* system start */ //#define SHARP_PDA_SYSTEMENDSOUND 8 /* system shutdown */ //#define SHARP_PDA_APPSTART 9 /* application start */ //#define SHARP_PDA_APPQUIT 10 /* application ends */ //#define SHARP_BUZ_SCHEDULE_ALARM 11 /* schedule alarm */ //#define SHARP_BUZ_DAILY_ALARM 12 /* daily alarm */ //#define SHARP_BUZ_GOT_PHONE_CALL 13 /* phone call sound */ //#define SHARP_BUZ_GOT_MAIL 14 /* mail sound */ // #define SHARP_LED_IOCTL_START (SHARP_DEV_IOCTL_COMMAND_START) #define SHARP_LED_SETSTATUS (SHARP_LED_IOCTL_START+1) #define SHARP_IOCTL_GET_ROTATION 0x413c typedef struct sharp_led_status { int which; /* select which LED status is wanted. */ int status; /* set new led status if you call SHARP_LED_SETSTATUS */ } sharp_led_status; #define SHARP_LED_MAIL_EXISTS 9 /* mail status (exists or not) */ #define LED_MAIL_NO_UNREAD_MAIL 0 /* for SHARP_LED_MAIL_EXISTS */ #define LED_MAIL_NEWMAIL_EXISTS 1 /* for SHARP_LED_MAIL_EXISTS */ #define LED_MAIL_UNREAD_MAIL_EX 2 /* for SHARP_LED_MAIL_EXISTS */ // #include <asm/sharp_apm.h> // including kernel headers is evil ... #define APM_IOCGEVTSRC OD_IOR( 'A', 203, int ) #define APM_IOCSEVTSRC OD_IORW( 'A', 204, int ) #define APM_EVT_POWER_BUTTON (1 << 0) #define FL_IOCTL_STEP_CONTRAST 100 void Zaurus::buzzer ( int sound ) { #ifndef QT_NO_SOUND QString soundname; // Not all devices have real sound if ( d->m_model == Model_Zaurus_SLC7x0 || d->m_model == Model_Zaurus_SLB600 ){ switch ( sound ){ case SHARP_BUZ_SCHEDULE_ALARM: soundname = "alarm"; break; case SHARP_BUZ_TOUCHSOUND: soundname = "touchsound"; break; case SHARP_BUZ_KEYSOUND: soundname = "keysound"; break; default: soundname = "alarm"; } } // If a soundname is defined, we expect that this device has // sound capabilities.. Otherwise we expect to have the buzzer // device.. if ( !soundname.isEmpty() ){ int fd; int vol; bool vol_reset = false; Sound snd ( soundname ); if (( fd = ::open ( "/dev/sound/mixer", O_RDWR )) >= 0 ) { if ( ::ioctl ( fd, MIXER_READ( 0 ), &vol ) >= 0 ) { Config cfg ( "qpe" ); cfg. setGroup ( "Volume" ); int volalarm = cfg. readNumEntry ( "AlarmPercent", 50 ); if ( volalarm < 0 ) volalarm = 0; else if ( volalarm > 100 ) volalarm = 100; volalarm |= ( volalarm << 8 ); if ( ::ioctl ( fd, MIXER_WRITE( 0 ), &volalarm ) >= 0 ) vol_reset = true; } } snd. play(); while ( !snd. isFinished()) qApp->processEvents(); if ( fd >= 0 ) { if ( vol_reset ) ::ioctl ( fd, MIXER_WRITE( 0 ), &vol ); ::close ( fd ); } } else { int fd = ::open ( "/dev/sharp_buz", O_WRONLY|O_NONBLOCK ); if ( fd >= 0 ) { ::ioctl ( fd, SHARP_BUZZER_MAKESOUND, sound ); ::close ( fd ); } } #endif } void Zaurus::playAlarmSound() { buzzer ( SHARP_BUZ_SCHEDULE_ALARM ); } void Zaurus::playTouchSound() { buzzer ( SHARP_BUZ_TOUCHSOUND ); } void Zaurus::playKeySound() { buzzer ( SHARP_BUZ_KEYSOUND ); } QValueList <OLed> Zaurus::ledList() const { QValueList <OLed> vl; vl << Led_Mail; return vl; } QValueList <OLedState> Zaurus::ledStateList ( OLed l ) const { QValueList <OLedState> vl; if ( l == Led_Mail ) vl << Led_Off << Led_On << Led_BlinkSlow; return vl; } OLedState Zaurus::ledState ( OLed which ) const { if ( which == Led_Mail ) return m_leds [0]; else return Led_Off; } bool Zaurus::setLedState ( OLed which, OLedState st ) { if (!m_embedix) // Currently not supported on non_embedix kernels return false; static int fd = ::open ( "/dev/sharp_led", O_RDWR|O_NONBLOCK ); diff --git a/libopie2/opiecore/oprocess.cpp b/libopie2/opiecore/oprocess.cpp index 0a361a1..6349c83 100644 --- a/libopie2/opiecore/oprocess.cpp +++ b/libopie2/opiecore/oprocess.cpp @@ -483,406 +483,406 @@ void OProcess::flushStdin ( ) do { d1 = input_total - input_sent; slotSendData ( 0 ); d2 = input_total - input_sent; } while ( d2 <= d1 ); } void OProcess::suspend() { if ( ( communication & Stdout ) && outnot ) outnot->setEnabled( false ); } void OProcess::resume() { if ( ( communication & Stdout ) && outnot ) outnot->setEnabled( true ); } bool OProcess::closeStdin() { bool rv; if ( communication & Stdin ) { communication = ( Communication ) ( communication & ~Stdin ); delete innot; innot = 0; close( in[ 1 ] ); rv = true; } else rv = false; return rv; } bool OProcess::closeStdout() { bool rv; if ( communication & Stdout ) { communication = ( Communication ) ( communication & ~Stdout ); delete outnot; outnot = 0; close( out[ 0 ] ); rv = true; } else rv = false; return rv; } bool OProcess::closeStderr() { bool rv; if ( communication & Stderr ) { communication = static_cast<Communication>( communication & ~Stderr ); delete errnot; errnot = 0; close( err[ 0 ] ); rv = true; } else rv = false; return rv; } void OProcess::slotChildOutput( int fdno ) { if ( !childOutput( fdno ) ) closeStdout(); } void OProcess::slotChildError( int fdno ) { if ( !childError( fdno ) ) closeStderr(); } void OProcess::slotSendData( int ) { if ( input_sent == input_total ) { innot->setEnabled( false ); input_data = 0; emit wroteStdin( this ); } else input_sent += ::write( in[ 1 ], input_data + input_sent, input_total - input_sent ); } void OProcess::processHasExited( int state ) { if ( runs ) { runs = false; status = state; commClose(); // cleanup communication sockets // also emit a signal if the process was run Blocking if ( DontCare != run_mode ) { emit processExited( this ); } } } int OProcess::childOutput( int fdno ) { if ( communication & NoRead ) { int len = -1; emit receivedStdout( fdno, len ); errno = 0; // Make sure errno doesn't read "EAGAIN" return len; } else { char buffer[ 1024 ]; int len; len = ::read( fdno, buffer, 1024 ); if ( 0 < len ) { emit receivedStdout( this, buffer, len ); } return len; } } int OProcess::childError( int fdno ) { char buffer[ 1024 ]; int len; len = ::read( fdno, buffer, 1024 ); if ( 0 < len ) emit receivedStderr( this, buffer, len ); return len; } int OProcess::setupCommunication( Communication comm ) { int ok; communication = comm; ok = 1; if ( comm & Stdin ) ok &= socketpair( AF_UNIX, SOCK_STREAM, 0, in ) >= 0; if ( comm & Stdout ) ok &= socketpair( AF_UNIX, SOCK_STREAM, 0, out ) >= 0; if ( comm & Stderr ) ok &= socketpair( AF_UNIX, SOCK_STREAM, 0, err ) >= 0; return ok; } int OProcess::commSetupDoneP() { int ok = 1; if ( communication != NoCommunication ) { if ( communication & Stdin ) close( in[ 0 ] ); if ( communication & Stdout ) close( out[ 1 ] ); if ( communication & Stderr ) close( err[ 1 ] ); // Don't create socket notifiers and set the sockets non-blocking if // blocking is requested. if ( run_mode == Block ) return ok; if ( communication & Stdin ) { // ok &= (-1 != fcntl(in[1], F_SETFL, O_NONBLOCK)); innot = new QSocketNotifier( in[ 1 ], QSocketNotifier::Write, this ); CHECK_PTR( innot ); innot->setEnabled( false ); // will be enabled when data has to be sent - QObject::connect( innot, SIGNAL( activated( int ) ), - this, SLOT( slotSendData( int ) ) ); + QObject::connect( innot, SIGNAL( activated(int) ), + this, SLOT( slotSendData(int) ) ); } if ( communication & Stdout ) { // ok &= (-1 != fcntl(out[0], F_SETFL, O_NONBLOCK)); outnot = new QSocketNotifier( out[ 0 ], QSocketNotifier::Read, this ); CHECK_PTR( outnot ); - QObject::connect( outnot, SIGNAL( activated( int ) ), - this, SLOT( slotChildOutput( int ) ) ); + QObject::connect( outnot, SIGNAL( activated(int) ), + this, SLOT( slotChildOutput(int) ) ); if ( communication & NoRead ) suspend(); } if ( communication & Stderr ) { // ok &= (-1 != fcntl(err[0], F_SETFL, O_NONBLOCK)); errnot = new QSocketNotifier( err[ 0 ], QSocketNotifier::Read, this ); CHECK_PTR( errnot ); - QObject::connect( errnot, SIGNAL( activated( int ) ), - this, SLOT( slotChildError( int ) ) ); + QObject::connect( errnot, SIGNAL( activated(int) ), + this, SLOT( slotChildError(int) ) ); } } return ok; } int OProcess::commSetupDoneC() { int ok = 1; struct linger so; memset( &so, 0, sizeof( so ) ); if ( communication & Stdin ) close( in[ 1 ] ); if ( communication & Stdout ) close( out[ 0 ] ); if ( communication & Stderr ) close( err[ 0 ] ); if ( communication & Stdin ) ok &= dup2( in[ 0 ], STDIN_FILENO ) != -1; else { int null_fd = open( "/dev/null", O_RDONLY ); ok &= dup2( null_fd, STDIN_FILENO ) != -1; close( null_fd ); } if ( communication & Stdout ) { ok &= dup2( out[ 1 ], STDOUT_FILENO ) != -1; ok &= !setsockopt( out[ 1 ], SOL_SOCKET, SO_LINGER, ( char* ) & so, sizeof( so ) ); } else { int null_fd = open( "/dev/null", O_WRONLY ); ok &= dup2( null_fd, STDOUT_FILENO ) != -1; close( null_fd ); } if ( communication & Stderr ) { ok &= dup2( err[ 1 ], STDERR_FILENO ) != -1; ok &= !setsockopt( err[ 1 ], SOL_SOCKET, SO_LINGER, reinterpret_cast<char *>( &so ), sizeof( so ) ); } else { int null_fd = open( "/dev/null", O_WRONLY ); ok &= dup2( null_fd, STDERR_FILENO ) != -1; close( null_fd ); } return ok; } void OProcess::commClose() { if ( NoCommunication != communication ) { bool b_in = ( communication & Stdin ); bool b_out = ( communication & Stdout ); bool b_err = ( communication & Stderr ); if ( b_in ) delete innot; if ( b_out || b_err ) { // If both channels are being read we need to make sure that one socket buffer // doesn't fill up whilst we are waiting for data on the other (causing a deadlock). // Hence we need to use select. // Once one or other of the channels has reached EOF (or given an error) go back // to the usual mechanism. int fds_ready = 1; fd_set rfds; int max_fd = 0; if ( b_out ) { fcntl( out[ 0 ], F_SETFL, O_NONBLOCK ); if ( out[ 0 ] > max_fd ) max_fd = out[ 0 ]; delete outnot; outnot = 0; } if ( b_err ) { fcntl( err[ 0 ], F_SETFL, O_NONBLOCK ); if ( err[ 0 ] > max_fd ) max_fd = err[ 0 ]; delete errnot; errnot = 0; } while ( b_out || b_err ) { // * If the process is still running we block until we // receive data. (p_timeout = 0, no timeout) // * If the process has already exited, we only check // the available data, we don't wait for more. // (p_timeout = &timeout, timeout immediately) struct timeval timeout; timeout.tv_sec = 0; timeout.tv_usec = 0; struct timeval *p_timeout = runs ? 0 : &timeout; FD_ZERO( &rfds ); if ( b_out ) FD_SET( out[ 0 ], &rfds ); if ( b_err ) FD_SET( err[ 0 ], &rfds ); fds_ready = select( max_fd + 1, &rfds, 0, 0, p_timeout ); if ( fds_ready <= 0 ) break; if ( b_out && FD_ISSET( out[ 0 ], &rfds ) ) { int ret = 1; while ( ret > 0 ) ret = childOutput( out[ 0 ] ); if ( ( ret == -1 && errno != EAGAIN ) || ret == 0 ) b_out = false; } if ( b_err && FD_ISSET( err[ 0 ], &rfds ) ) { int ret = 1; while ( ret > 0 ) ret = childError( err[ 0 ] ); if ( ( ret == -1 && errno != EAGAIN ) || ret == 0 ) b_err = false; } } } if ( b_in ) { communication = ( Communication ) ( communication & ~Stdin ); close( in[ 1 ] ); } if ( b_out ) { communication = ( Communication ) ( communication & ~Stdout ); close( out[ 0 ] ); } if ( b_err ) { communication = ( Communication ) ( communication & ~Stderr ); close( err[ 0 ] ); } } } void OProcess::setUseShell( bool useShell, const char *shell ) { if ( !d ) d = new OProcessPrivate; d->useShell = useShell; d->shell = shell; if ( d->shell.isEmpty() ) d->shell = searchShell(); } QString OProcess::quote( const QString &arg ) { QString res = arg; res.replace( QRegExp( QString::fromLatin1( "\'" ) ), QString::fromLatin1( "'\"'\"'" ) ); res.prepend( '\'' ); res.append( '\'' ); return res; } QCString OProcess::searchShell() { QCString tmpShell = QCString( getenv( "SHELL" ) ).stripWhiteSpace(); if ( !isExecutable( tmpShell ) ) { tmpShell = "/bin/sh"; } return tmpShell; } bool OProcess::isExecutable( const QCString &filename ) { struct stat fileinfo; if ( filename.isEmpty() ) return false; // CC: we've got a valid filename, now let's see whether we can execute that file diff --git a/libopie2/opiepim/core/ocontactaccess.cpp b/libopie2/opiepim/core/ocontactaccess.cpp index c12e138..4f9b504 100644 --- a/libopie2/opiepim/core/ocontactaccess.cpp +++ b/libopie2/opiepim/core/ocontactaccess.cpp @@ -1,152 +1,152 @@ /* This file is part of the Opie Project Copyright (C) The Main Author <main-author@whereever.org> =. Copyright (C) The Opie Team <opie-devel@handhelds.org> .=l. .>+-= _;:, .> :=|. This program is free software; you can .> <`_, > . <= redistribute it and/or modify it under :`=1 )Y*s>-.-- : the terms of the GNU Library General Public .="- .-=="i, .._ License as published by the Free Software - . .-<_> .<> Foundation; either version 2 of the License, ._= =} : or (at your option) any later version. .%`+i> _;_. .i_,=:_. -<s. This program 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. */ /* * ===================================================================== * ToDo: XML-Backend: Automatic reload if something was changed... * * */ #include "ocontactaccess.h" #include "obackendfactory.h" #include <qasciidict.h> #include <qdatetime.h> #include <qfile.h> #include <qregexp.h> #include <qlist.h> #include <qcopchannel_qws.h> //#include <qpe/qcopenvelope_qws.h> #include <qpe/global.h> #include <errno.h> #include <fcntl.h> #include <unistd.h> #include <stdlib.h> #include <opie2/ocontactaccessbackend_xml.h> namespace Opie { OPimContactAccess::OPimContactAccess ( const QString appname, const QString , OPimContactAccessBackend* end, bool autosync ): OPimAccessTemplate<OPimContact>( end ) { /* take care of the backend. If there is no one defined, we * will use the XML-Backend as default (until we have a cute SQL-Backend..). */ if( end == 0 ) { qWarning ("Using BackendFactory !"); end = OBackendFactory<OPimContactAccessBackend>::Default( "contact", appname ); } // Set backend locally and in template m_backEnd = end; OPimAccessTemplate<OPimContact>::setBackEnd (end); /* Connect signal of external db change to function */ QCopChannel *dbchannel = new QCopChannel( "QPE/PIM", this ); - connect( dbchannel, SIGNAL(received(const QCString &, const QByteArray &)), - this, SLOT(copMessage( const QCString &, const QByteArray &)) ); + connect( dbchannel, SIGNAL(received(const QCString&,const QByteArray&)), + this, SLOT(copMessage(const QCString&,const QByteArray&)) ); if ( autosync ){ QCopChannel *syncchannel = new QCopChannel( "QPE/Sync", this ); - connect( syncchannel, SIGNAL(received(const QCString &, const QByteArray &)), - this, SLOT(copMessage( const QCString &, const QByteArray &)) ); + connect( syncchannel, SIGNAL(received(const QCString&,const QByteArray&)), + this, SLOT(copMessage(const QCString&,const QByteArray&)) ); } } OPimContactAccess::~OPimContactAccess () { /* The user may forget to save the changed database, therefore try to * do it for him.. */ save(); // delete m_backEnd; is done by template.. } bool OPimContactAccess::save () { /* If the database was changed externally, we could not save the * Data. This will remove added items which is unacceptable ! * Therefore: Reload database and merge the data... */ if ( OPimAccessTemplate<OPimContact>::wasChangedExternally() ) reload(); bool status = OPimAccessTemplate<OPimContact>::save(); if ( !status ) return false; /* Now tell everyone that new data is available. */ QCopEnvelope e( "QPE/PIM", "addressbookUpdated()" ); return true; } const uint OPimContactAccess::querySettings() { return ( m_backEnd->querySettings() ); } bool OPimContactAccess::hasQuerySettings ( int querySettings ) const { return ( m_backEnd->hasQuerySettings ( querySettings ) ); } OPimRecordList<OPimContact> OPimContactAccess::sorted( bool ascending, int sortOrder, int sortFilter, int cat ) const { QArray<int> matchingContacts = m_backEnd -> sorted( ascending, sortOrder, sortFilter, cat ); return ( OPimRecordList<OPimContact>(matchingContacts, this) ); } bool OPimContactAccess::wasChangedExternally()const { return ( m_backEnd->wasChangedExternally() ); } void OPimContactAccess::copMessage( const QCString &msg, const QByteArray & ) { if ( msg == "addressbookUpdated()" ){ qWarning ("OPimContactAccess: Received addressbokUpdated()"); emit signalChanged ( this ); } else if ( msg == "flush()" ) { qWarning ("OPimContactAccess: Received flush()"); save (); } else if ( msg == "reload()" ) { qWarning ("OPimContactAccess: Received reload()"); reload (); emit signalChanged ( this ); } } } diff --git a/libopie2/opiepim/ui/opimmainwindow.cpp b/libopie2/opiepim/ui/opimmainwindow.cpp index 10ed743..40dc297 100644 --- a/libopie2/opiepim/ui/opimmainwindow.cpp +++ b/libopie2/opiepim/ui/opimmainwindow.cpp @@ -1,181 +1,181 @@ /* This file is part of the Opie Project Copyright (C) Stefan Eilers (Eilers.Stefan@epost.de) =. Copyright (C) The Opie Team <opie-devel@handhelds.org> .=l. .>+-= _;:, .> :=|. This program is free software; you can .> <`_, > . <= redistribute it and/or modify it under :`=1 )Y*s>-.-- : the terms of the GNU Library General Public .="- .-=="i, .._ License as published by the Free Software - . .-<_> .<> Foundation; either version 2 of the License, ._= =} : or (at your option) any later version. .%`+i> _;_. .i_,=:_. -<s. This program 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 <qapplication.h> #include <qdatetime.h> #include <qcopchannel_qws.h> #include <qpe/sound.h> #include <qpe/qcopenvelope_qws.h> #include <qpe/qpeapplication.h> #include <opie2/opimresolver.h> #include "opimmainwindow.h" namespace Opie { OPimMainWindow::OPimMainWindow( const QString& service, QWidget* parent, const char* name, WFlags flag ) : QMainWindow( parent, name, flag ), m_rtti(-1), m_service( service ), m_fallBack(0l) { /* * let's generate our QCopChannel */ m_str = QString("QPE/"+m_service).local8Bit(); m_channel= new QCopChannel(m_str, this ); - connect(m_channel, SIGNAL(received(const QCString&, const QByteArray& ) ), - this, SLOT( appMessage( const QCString&, const QByteArray& ) ) ); - connect(qApp, SIGNAL(appMessage(const QCString&, const QByteArray& ) ), - this, SLOT( appMessage( const QCString&, const QByteArray& ) ) ); + connect(m_channel, SIGNAL(received(const QCString&,const QByteArray&) ), + this, SLOT( appMessage(const QCString&,const QByteArray&) ) ); + connect(qApp, SIGNAL(appMessage(const QCString&,const QByteArray&) ), + this, SLOT( appMessage(const QCString&,const QByteArray&) ) ); /* connect flush and reload */ connect(qApp, SIGNAL(flush() ), this, SLOT(flush() ) ); connect(qApp, SIGNAL(reload() ), this, SLOT(reload() ) ); } OPimMainWindow::~OPimMainWindow() { delete m_channel; } QCopChannel* OPimMainWindow::channel() { return m_channel; } void OPimMainWindow::doSetDocument( const QString& ) { } void OPimMainWindow::appMessage( const QCString& cmd, const QByteArray& array ) { bool needShow = false; /* * create demands to create * a new record... */ QDataStream stream(array, IO_ReadOnly); if ( cmd == "create()" ) { raise(); int uid = create(); QCopEnvelope e(m_str, "created(int)" ); e << uid; needShow = true; }else if ( cmd == "remove(int)" ) { int uid; stream >> uid; bool rem = remove( uid ); QCopEnvelope e(m_str, "removed(bool)" ); e << rem; needShow = true; }else if ( cmd == "beam(int)" ) { int uid; stream >> uid; beam( uid); }else if ( cmd == "show(int)" ) { raise(); int uid; stream >> uid; show( uid ); needShow = true; }else if ( cmd == "edit(int)" ) { raise(); int uid; stream >> uid; edit( uid ); }else if ( cmd == "add(int,QByteArray)" ) { int rtti; QByteArray array; stream >> rtti; stream >> array; m_fallBack = record(rtti, array ); if (!m_fallBack) return; add( *m_fallBack ); delete m_fallBack; }else if ( cmd == "alarm(QDateTime,int)" ) { raise(); QDateTime dt; int uid; stream >> dt; stream >> uid; qWarning(" Date: %s Uid: %d", dt.toString().latin1(), uid ); QDateTime current = QDateTime::currentDateTime(); if ( current.time().hour() != dt.time().hour() && current.time().minute() != dt.time().minute() ) return; doAlarm( dt, uid ); needShow = true; } if (needShow ) QPEApplication::setKeepRunning(); } /* implement the url scripting here */ void OPimMainWindow::setDocument( const QString& str) { doSetDocument( str ); } /* * we now try to get the array demarshalled * check if the rtti matches this one */ OPimRecord* OPimMainWindow::record( int rtti, const QByteArray& array ) { if ( service() != rtti ) return 0l; OPimRecord* record = OPimResolver::self()->record( rtti ); QDataStream str(array, IO_ReadOnly ); if ( !record || !record->loadFromStream(str) ) { delete record; record = 0l; } return record; } /* * get the rtti for the service */ int OPimMainWindow::service() { if ( m_rtti == -1 ) m_rtti = OPimResolver::self()->serviceId( m_service ); return m_rtti; } void OPimMainWindow::doAlarm( const QDateTime&, int ) { } void OPimMainWindow::startAlarm(int count ) { m_alarmCount = count; m_playedCount = 0; Sound::soundAlarm(); m_timerId = startTimer( 5000 ); } void OPimMainWindow::killAlarm() { killTimer( m_timerId ); } void OPimMainWindow::timerEvent( QTimerEvent* e) { if ( m_playedCount <m_alarmCount ) { m_playedCount++; Sound::soundAlarm(); }else { killTimer( e->timerId() ); } } } diff --git a/libopie2/opiepim/ui/opimrecurrencewidget.cpp b/libopie2/opiepim/ui/opimrecurrencewidget.cpp index 569bdd5..90c1a5f 100644 --- a/libopie2/opiepim/ui/opimrecurrencewidget.cpp +++ b/libopie2/opiepim/ui/opimrecurrencewidget.cpp @@ -363,272 +363,272 @@ void OPimRecurrenceWidget::slotWeekLabel() { list.append( dayLabel[i - 1] ); } } } QStringList::Iterator itStr; for ( i = 0, itStr = list.begin(); itStr != list.end(); ++itStr, i++ ) { if ( i == 3 ) bNeedCarriage = TRUE; else bNeedCarriage = FALSE; if ( str.isNull() ) str = *itStr; else if ( i == list.count() - 1 ) { if ( i < 2 ) str += tr(" and ") + *itStr; else { if ( bNeedCarriage ) str += tr( ",\nand " ) + *itStr; else str += tr( ", and " ) + *itStr; } } else { if ( bNeedCarriage ) str += ",\n" + *itStr; else str += ", " + *itStr; } } str = str.prepend( tr("on ") ); lblWeekVar->setText( str ); } void OPimRecurrenceWidget::slotMonthLabel(int type) { QString str; if ( currInterval != Month || type > 1 ) return; if ( type == 1 ) str = strMonthDateTemplate.arg( numberPlacing(start.day()) ); else str = strMonthDayTemplate.arg( numberPlacing(week(start))) .arg( dayLabel[start.dayOfWeek() - 1] ); lblRepeat->setText( str ); } void OPimRecurrenceWidget::slotChangeStartOfWeek( bool onMonday ) { startWeekOnMonday = onMonday; // we need to make this unintrusive as possible... int saveSpin = spinFreq->value(); char days = 0; int day; QListIterator<QToolButton> itExtra( listExtra ); for ( day = 1; *itExtra; ++itExtra, day = day << 1 ) { if ( (*itExtra)->isOn() ) { if ( !startWeekOnMonday ) days |= day; else { if ( day == 1 ) days |= OPimRecurrence::SUN; else days |= day >> 1; } } } setupWeekly(); spinFreq->setValue( saveSpin ); int buttons; for ( day = 0x01, buttons = 0; buttons < 7; day = day << 1, buttons++ ) { if ( days & day ) { if ( startWeekOnMonday ) fraExtra->setButton( buttons ); else { if ( buttons == 7 ) fraExtra->setButton( 0 ); else fraExtra->setButton( buttons + 1 ); } } } slotWeekLabel(); } void OPimRecurrenceWidget::setupNone() { lblRepeat->setText( tr("No Repeat") ); lblVar1->hide(); lblVar2->hide(); hideExtras(); cmdEnd->hide(); lblFreq->hide(); lblEvery->hide(); lblFreq->hide(); spinFreq->hide(); lblEnd->hide(); lblWeekVar->hide(); } void OPimRecurrenceWidget::setupDaily() { hideExtras(); lblWeekVar->hide(); spinFreq->setValue( 1 ); lblFreq->setText( tr("day(s)") ); lblVar2->show(); showRepeatStuff(); lblRepeat->setText( strDayTemplate ); setupRepeatLabel( 1 ); } void OPimRecurrenceWidget::setupWeekly() { // reshow the buttons... fraExtra->setTitle( tr("Repeat On") ); fraExtra->setExclusive( FALSE ); fraExtra->show(); if ( startWeekOnMonday ) { cmdExtra1->setText( tr("Mon") ); cmdExtra2->setText( tr("Tue") ); cmdExtra3->setText( tr("Wed") ); cmdExtra4->setText( tr("Thu") ); cmdExtra5->setText( tr("Fri") ); cmdExtra6->setText( tr("Sat") ); cmdExtra7->setText( tr("Sun") ); } else { cmdExtra1->setText( tr("Sun") ); cmdExtra2->setText( tr("Mon") ); cmdExtra3->setText( tr("Tue") ); cmdExtra4->setText( tr("Wed") ); cmdExtra5->setText( tr("Thu") ); cmdExtra6->setText( tr("Fri") ); cmdExtra7->setText( tr("Sat") ); } // I hope clustering these improve performance.... cmdExtra1->setOn( FALSE ); cmdExtra2->setOn( FALSE ); cmdExtra3->setOn( FALSE ); cmdExtra4->setOn( FALSE ); cmdExtra5->setOn( FALSE ); cmdExtra6->setOn( FALSE ); cmdExtra7->setOn( FALSE ); cmdExtra1->show(); cmdExtra2->show(); cmdExtra3->show(); cmdExtra4->show(); cmdExtra5->show(); cmdExtra6->show(); cmdExtra7->show(); lblWeekVar->show(); spinFreq->setValue( 1 ); // might as well set the day too... if ( startWeekOnMonday ) { fraExtra->setButton( start.dayOfWeek() - 1 ); } else { fraExtra->setButton( start.dayOfWeek() % 7 ); } lblFreq->setText( tr("week(s)") ); lblVar2->show(); showRepeatStuff(); setupRepeatLabel( 1 ); } void OPimRecurrenceWidget::setupMonthly() { hideExtras(); lblWeekVar->hide(); fraExtra->setTitle( tr("Repeat By") ); fraExtra->setExclusive( TRUE ); fraExtra->show(); cmdExtra1->setText( tr("Day") ); cmdExtra1->show(); cmdExtra2->setText( tr("Date") ); cmdExtra2->show(); spinFreq->setValue( 1 ); lblFreq->setText( tr("month(s)") ); lblVar2->show(); showRepeatStuff(); setupRepeatLabel( 1 ); } void OPimRecurrenceWidget::setupYearly() { hideExtras(); lblWeekVar->hide(); spinFreq->setValue( 1 ); lblFreq->setText( tr("year(s)") ); lblFreq->show(); lblFreq->show(); showRepeatStuff(); lblVar2->show(); QString strEvery = strYearTemplate.arg( start.monthName(start.month()) ).arg( numberPlacing(start.day()) ); lblRepeat->setText( strEvery ); setupRepeatLabel( 1 ); } void OPimRecurrenceWidget::init() { QPopupMenu *m1 = new QPopupMenu( this ); repeatPicker = new DateBookMonth( m1, 0, TRUE ); m1->insertItem( repeatPicker ); cmdEnd->setPopup( m1 ); cmdEnd->setPopupDelay( 0 ); - QObject::connect( repeatPicker, SIGNAL(dateClicked(int, int, int)), - this, SLOT(endDateChanged(int, int, int)) ); + QObject::connect( repeatPicker, SIGNAL(dateClicked(int,int,int)), + this, SLOT(endDateChanged(int,int,int)) ); QObject::connect( qApp, SIGNAL(weekChanged(bool)), this, SLOT(slotChangeStartOfWeek(bool)) ); listRTypeButtons.setAutoDelete( TRUE ); listRTypeButtons.append( cmdNone ); listRTypeButtons.append( cmdDay ); listRTypeButtons.append( cmdWeek ); listRTypeButtons.append( cmdMonth ); listRTypeButtons.append( cmdYear ); listExtra.setAutoDelete( TRUE ); listExtra.append( cmdExtra1 ); listExtra.append( cmdExtra2 ); listExtra.append( cmdExtra3 ); listExtra.append( cmdExtra4 ); listExtra.append( cmdExtra5 ); listExtra.append( cmdExtra6 ); listExtra.append( cmdExtra7 ); } void OPimRecurrenceWidget::hideExtras() { // hide the extra buttons... fraExtra->hide(); chkNoEnd->hide(); QListIterator<QToolButton> it( listExtra ); for ( ; *it; ++it ) { (*it)->hide(); (*it)->setOn( FALSE ); } } void OPimRecurrenceWidget::showRepeatStuff() { cmdEnd->show(); chkNoEnd->show(); lblFreq->show(); lblEvery->show(); lblFreq->show(); spinFreq->show(); lblEnd->show(); lblRepeat->setText( tr("Every") ); } static int week( const QDate &start ) { // figure out the week... int stop = start.day(), sentinel = start.dayOfWeek(), dayOfWeek = QDate( start.year(), start.month(), 1 ).dayOfWeek(), week = 1, i; for ( i = 1; i < stop; i++ ) { if ( dayOfWeek++ == sentinel ) week++; if ( dayOfWeek > 7 ) dayOfWeek = 0; } return week; } static QString numberPlacing( int x ) { // I hope this works in other languages besides english... QString str = QString::number( x ); switch ( x % 10 ) { case 1: str += QWidget::tr( "st" ); break; case 2: str += QWidget::tr( "nd" ); break; case 3: str += QWidget::tr( "rd" ); break; default: str += QWidget::tr( "th" ); break; } return str; } diff --git a/libopie2/opieui/fileselector/ofiledialog.cpp b/libopie2/opieui/fileselector/ofiledialog.cpp index 2a89c5d..e7daead 100644 --- a/libopie2/opieui/fileselector/ofiledialog.cpp +++ b/libopie2/opieui/fileselector/ofiledialog.cpp @@ -1,222 +1,222 @@ /* =. This file is part of the OPIE Project .=l. Copyright (C) Holger Freyther <zecke@handhelds.org> .>+-= _;:, .> :=|. This library is free software; you can .> <`_, > . <= redistribute it and/or modify it under :`=1 )Y*s>-.-- : the terms of the GNU Library General Public .="- .-=="i, .._ License as published by the Free Software - . .-<_> .<> Foundation; either version 2 of the License, ._= =} : or (at your option) any later version. .%`+i> _;_. .i_,=:_. -<s. 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. */ /* OPIE */ #include <opie2/ofiledialog.h> #include <qpe/applnk.h> #include <qpe/config.h> #include <qpe/qpeapplication.h> /* QT */ #include <qfileinfo.h> #include <qstring.h> #include <qapplication.h> #include <qlayout.h> using namespace Opie; namespace { /* * helper functions to load the start dir * and to save it * helper to extract the dir out of a file name */ /** * This method will use Config( argv[0] ); * @param key The group key used */ QString lastUsedDir( const QString& key ) { if ( qApp->argc() < 1 ) return QString::null; Config cfg( QFileInfo(qApp->argv()[0]).fileName() ); // appname cfg.setGroup( key ); return cfg.readEntry("LastDir", QPEApplication::documentDir() ); } void saveLastDir( const QString& key, const QString& file ) { if ( qApp->argc() < 1 ) return; Config cfg( QFileInfo(qApp->argv()[0]).fileName() ); cfg.setGroup( key ); QFileInfo inf( file ); cfg.writeEntry("LastDir", inf.dirPath( true ) ); } }; /** * This constructs a modal dialog * * @param caption The caption of the dialog * @param wid The parent widget * @param mode The mode of the OFileSelector @see OFileSelector * @param selector The selector of the OFileSelector * @param dirName the dir or resource to start from * @param fileName a proposed or existing filename * @param mimetypes The mimeTypes */ OFileDialog::OFileDialog(const QString &caption, QWidget *wid, int mode, int selector, const QString &dirName, const QString &fileName, const QMap<QString,QStringList>& mimetypes ) : QDialog( wid, "OFileDialog", true ) { // QVBoxLayout *lay = new QVBoxLayout(this); //showMaximized(); QVBoxLayout *lay = new QVBoxLayout(this ); file = new OFileSelector(this , mode, selector, dirName, fileName, mimetypes ); lay->addWidget( file ); //lay->addWidget( file ); //showFullScreen(); setCaption( caption.isEmpty() ? tr("FileDialog") : caption ); connect(file, SIGNAL(fileSelected(const QString&) ), this, SLOT(slotFileSelected(const QString&) ) ); connect(file, SIGNAL(ok() ), this, SLOT(slotSelectorOk()) ) ; connect(file, SIGNAL(dirSelected(const QString&) ), this, SLOT(slotDirSelected(const QString&) ) ); #if 0 - connect(file, SIGNAL(dirSelected(const QString &) ), - this, SLOT(slotDirSelected(const QString &) ) ); + connect(file, SIGNAL(dirSelected(const QString&) ), + this, SLOT(slotDirSelected(const QString&) ) ); #endif } /** * @returns the mimetype of the selected * currently it return QString::null */ QString OFileDialog::mimetype()const { return QString::null; } /** * @return the fileName */ QString OFileDialog::fileName()const { return file->selectedName(); } /** * return a DocLnk to the current file */ DocLnk OFileDialog::selectedDocument()const { return file->selectedDocument(); } /** * This opens up a filedialog in Open mode * * @param selector the Selector Mode * @param startDir Where to start from * @param file A proposed filename * @param mimes A list of MimeTypes * @param wid the parent * @param caption of the dialog if QString::null tr("Open") will be used * @return the fileName or QString::null */ QString OFileDialog::getOpenFileName(int selector, const QString &_startDir, const QString &file, const MimeTypes &mimes, QWidget *wid, const QString &caption ) { QString ret; QString startDir = _startDir; if (startDir.isEmpty() ) startDir = lastUsedDir( "FileDialog-OPEN" ); OFileDialog dlg( caption.isEmpty() ? tr("Open") : caption, wid, OFileSelector::Open, selector, startDir, file, mimes); dlg.showMaximized(); if( dlg.exec() ) { ret = dlg.fileName(); saveLastDir( "FileDialog-OPEN", ret ); } return ret; } /** * This opens up a file dialog in save mode * @see getOpenFileName */ QString OFileDialog::getSaveFileName(int selector, const QString &_startDir, const QString &file, const MimeTypes &mimes, QWidget *wid, const QString &caption ) { QString ret; QString startDir = _startDir; if (startDir.isEmpty() ) startDir = lastUsedDir( "FileDialog-SAVE" ); OFileDialog dlg( caption.isEmpty() ? tr("Save") : caption, wid, OFileSelector::Save, selector, startDir, file, mimes); dlg.showMaximized(); if( dlg.exec() ) { ret = dlg.fileName(); saveLastDir( "FileDialog-SAVE", ret ); } return ret; } void OFileDialog::slotFileSelected(const QString & ) { accept(); } void OFileDialog::slotSelectorOk( ) { accept(); } void OFileDialog::slotDirSelected(const QString &dir ) { setCaption( dir ); // if mode //accept(); } diff --git a/libopie2/opieui/fileselector/ofileselector.cpp b/libopie2/opieui/fileselector/ofileselector.cpp index 600daff..15cadd4 100644 --- a/libopie2/opieui/fileselector/ofileselector.cpp +++ b/libopie2/opieui/fileselector/ofileselector.cpp @@ -21,700 +21,700 @@ -_. . . )=. = 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. */ /* hacky but we need to get FileSelector::filter */ #define private public #include <qpe/fileselector.h> #undef private #include "ofileselector_p.h" /* OPIE */ #include <opie2/ofileselector.h> #include <qpe/qpeapplication.h> #include <qpe/mimetype.h> #include <qpe/resource.h> #include <qpe/storage.h> /* QT */ #include <qcombobox.h> #include <qdir.h> #include <qhbox.h> #include <qheader.h> #include <qlabel.h> #include <qlayout.h> #include <qlineedit.h> #include <qlistview.h> #include <qpopupmenu.h> #include <qwidgetstack.h> #include <qregexp.h> #include <qobjectlist.h> using namespace Opie; OFileViewInterface::OFileViewInterface( OFileSelector* selector ) : m_selector( selector ) {} OFileViewInterface::~OFileViewInterface() {} QString OFileViewInterface::name()const { return m_name; } void OFileViewInterface::setName( const QString& name ) { m_name = name; } OFileSelector* OFileViewInterface::selector()const { return m_selector; } DocLnk OFileViewInterface::selectedDocument()const { return DocLnk( selectedName() ); } bool OFileViewInterface::showNew()const { return selector()->showNew(); } bool OFileViewInterface::showClose()const { return selector()->showClose(); } MimeTypes OFileViewInterface::mimeTypes()const { return selector()->mimeTypes(); } QStringList OFileViewInterface::currentMimeType()const { return selector()->currentMimeType(); } void OFileViewInterface::activate( const QString& ) { // not implemented here } void OFileViewInterface::ok() { emit selector()->ok(); } void OFileViewInterface::cancel() { emit selector()->cancel(); } void OFileViewInterface::closeMe() { emit selector()->closeMe(); } void OFileViewInterface::fileSelected( const QString& str) { emit selector()->fileSelected( str); } void OFileViewInterface::fileSelected( const DocLnk& lnk) { emit selector()->fileSelected( lnk ); } void OFileViewInterface::setCurrentFileName( const QString& str ) { selector()->m_lneEdit->setText( str ); } QString OFileViewInterface::currentFileName()const { return selector()->m_lneEdit->text(); } QString OFileViewInterface::startDirectory()const { return selector()->m_startDir; } ODocumentFileView::ODocumentFileView( OFileSelector* selector ) :OFileViewInterface( selector ) { m_selector = 0; setName( QObject::tr("Documents") ); } ODocumentFileView::~ODocumentFileView() { } QString ODocumentFileView::selectedName()const { if (!m_selector) return QString::null; return m_selector->selectedDocument().file(); } QString ODocumentFileView::selectedPath()const { return QPEApplication::documentDir(); } QString ODocumentFileView::directory()const { return selectedPath(); } void ODocumentFileView::reread() { if (!m_selector) return; m_selector->setNewVisible( showNew() ); m_selector->setCloseVisible( showClose() ); m_selector->filter = currentMimeType().join(";"); m_selector->reread(); } int ODocumentFileView::fileCount()const { if (!m_selector) return -1; return m_selector->fileCount(); } DocLnk ODocumentFileView::selectedDocument()const { if (!m_selector) return DocLnk(); return m_selector->selectedDocument(); } QWidget* ODocumentFileView::widget( QWidget* parent ) { if (!m_selector ) { m_selector = new FileSelector(currentMimeType().join(";"), parent, "fileselector", showNew(), showClose() ); - QObject::connect(m_selector, SIGNAL(fileSelected( const DocLnk& ) ), + QObject::connect(m_selector, SIGNAL(fileSelected(const DocLnk&) ), selector(), SLOT(slotDocLnkBridge(const DocLnk&) ) ); QObject::connect(m_selector, SIGNAL(closeMe() ), selector(), SIGNAL(closeMe() ) ); - QObject::connect(m_selector, SIGNAL(newSelected(const DocLnk& ) ), - selector(), SIGNAL(newSelected(const DocLnk& ) ) ); + QObject::connect(m_selector, SIGNAL(newSelected(const DocLnk&) ), + selector(), SIGNAL(newSelected(const DocLnk&) ) ); } return m_selector; } /* * This is the file system view used * we use a QListView + QListViewItems for it */ OFileSelectorItem::OFileSelectorItem( QListView* view, const QPixmap& pixmap, const QString& path, const QString& date, const QString& size, const QString& dir, bool isLocked, bool isDir ) : QListViewItem( view ) { setPixmap(0, pixmap ); setText(1, path ); setText(2, size ); setText(3, date ); m_isDir = isDir; m_dir = dir; m_locked = isLocked; } OFileSelectorItem::~OFileSelectorItem() { } bool OFileSelectorItem::isLocked()const { return m_locked; } QString OFileSelectorItem::directory()const { return m_dir; } bool OFileSelectorItem::isDir()const { return m_isDir; } QString OFileSelectorItem::path()const { return text( 1 ); } QString OFileSelectorItem::key( int id, bool )const { QString ke; if( id == 0 || id == 1 ) { // name if( m_isDir ) { ke.append("0" ); ke.append( text(1) ); } else { ke.append("1" ); ke.append( text(1) ); } return ke; } else return text( id ); } OFileViewFileListView::OFileViewFileListView( QWidget* parent, const QString& startDir, OFileSelector* sel) :QWidget( parent ), m_sel( sel ) { m_all = false; QVBoxLayout* lay = new QVBoxLayout( this ); m_currentDir = startDir; /* * now we add a special bar * One Button For Up * Home * Doc * And a dropdown menu with FileSystems * FUTURE: one to change dir with lineedit * Bookmarks * Create Dir */ QHBox* box = new QHBox(this ); box->setBackgroundMode( PaletteButton ); box->setSpacing( 0 ); QToolButton *btn = new QToolButton( box ); btn->setIconSet( Resource::loadIconSet("up") ); connect(btn, SIGNAL(clicked() ), this, SLOT( cdUP() ) ); btn = new QToolButton( box ); btn->setIconSet( Resource::loadIconSet("home") ); connect(btn, SIGNAL(clicked() ), this, SLOT( cdHome() ) ); btn = new QToolButton( box ); btn->setIconSet( Resource::loadIconSet("DocsIcon") ); connect(btn, SIGNAL(clicked() ), this, SLOT(cdDoc() ) ); m_btnNew = new QToolButton( box ); m_btnNew->setIconSet( Resource::loadIconSet("new") ); connect(m_btnNew, SIGNAL(clicked() ), this, SLOT(slotNew() ) ); m_btnClose = new QToolButton( box ); m_btnClose->setIconSet( Resource::loadIconSet("close") ); connect(m_btnClose, SIGNAL(clicked() ), selector(), SIGNAL(closeMe() ) ); btn = new QToolButton( box ); btn->setIconSet( Resource::loadIconSet("cardmon/pcmcia") ); /* let's fill device parts */ QPopupMenu* pop = new QPopupMenu(this); connect(pop, SIGNAL( activated(int) ), this, SLOT(slotFSActivated(int) ) ); StorageInfo storage; const QList<FileSystem> &fs = storage.fileSystems(); QListIterator<FileSystem> it(fs); for ( ; it.current(); ++it ) { const QString disk = (*it)->name(); const QString path = (*it)->path(); m_dev.insert( disk, path ); pop->insertItem( disk ); } m_fsPop = pop; btn->setPopup( pop ); lay->addWidget( box ); m_view = new QListView( this ); m_view->installEventFilter(this); QPEApplication::setStylusOperation( m_view->viewport(), QPEApplication::RightOnHold); m_view->addColumn(" " ); m_view->addColumn(tr("Name"), 135 ); m_view->addColumn(tr("Size"), -1 ); m_view->addColumn(tr("Date"), 60 ); m_view->addColumn(tr("Mime Type"), -1 ); m_view->setSorting( 1 ); m_view->setAllColumnsShowFocus( TRUE ); lay->addWidget( m_view, 1000 ); connectSlots(); } OFileViewFileListView::~OFileViewFileListView() { } void OFileViewFileListView::slotNew() { DocLnk lnk; emit selector()->newSelected( lnk ); } OFileSelectorItem* OFileViewFileListView::currentItem()const { QListViewItem* item = m_view->currentItem(); if (!item ) return 0l; return static_cast<OFileSelectorItem*>(item); } void OFileViewFileListView::reread( bool all ) { m_view->clear(); if (selector()->showClose() ) m_btnClose->show(); else m_btnClose->hide(); if (selector()->showNew() ) m_btnNew->show(); else m_btnNew->hide(); m_mimes = selector()->currentMimeType(); m_all = all; QDir dir( m_currentDir ); if (!dir.exists() ) return; dir.setSorting( QDir::Name | QDir::DirsFirst | QDir::Reversed ); int filter; if (m_all ) filter = QDir::Files | QDir::Dirs | QDir::Hidden | QDir::All; else filter = QDir::Files | QDir::Dirs | QDir::All; dir.setFilter( filter ); // now go through all files const QFileInfoList *list = dir.entryInfoList(); if (!list) { cdUP(); return; } QFileInfoListIterator it( *list ); QFileInfo *fi; while( (fi=it.current() ) ) { if( fi->fileName() == QString::fromLatin1("..") || fi->fileName() == QString::fromLatin1(".") ) { ++it; continue; } /* * It is a symlink we try to resolve it now but don't let us attack by DOS * */ if( fi->isSymLink() ) { QString file = fi->dirPath( true ) + "/" + fi->readLink(); for( int i = 0; i<=4; i++) { // 5 tries to prevent dos QFileInfo info( file ); if( !info.exists() ) { addSymlink( fi, TRUE ); break; } else if( info.isDir() ) { addDir( fi, TRUE ); break; } else if( info.isFile() ) { addFile( fi, TRUE ); break; } else if( info.isSymLink() ) { file = info.dirPath(true ) + "/" + info.readLink() ; break; } else if( i == 4) { // couldn't resolve symlink add it as symlink addSymlink( fi ); } } // off for loop for symlink resolving } else if( fi->isDir() ) addDir( fi ); else if( fi->isFile() ) addFile( fi ); ++it; } // of while loop m_view->sort(); } int OFileViewFileListView::fileCount()const { return m_view->childCount(); } QString OFileViewFileListView::currentDir()const { return m_currentDir; } OFileSelector* OFileViewFileListView::selector() { return m_sel; } bool OFileViewFileListView::eventFilter (QObject *o, QEvent *e) { if ( e->type() == QEvent::KeyPress ) { QKeyEvent *k = (QKeyEvent *)e; if ( (k->key()==Key_Enter) || (k->key()==Key_Return)) { slotClicked( Qt::LeftButton,m_view->currentItem(),QPoint(0,0),0); return true; } } return false; } void OFileViewFileListView::connectSlots() { connect(m_view, SIGNAL(clicked(QListViewItem*) ), this, SLOT(slotCurrentChanged(QListViewItem*) ) ); - connect(m_view, SIGNAL(mouseButtonClicked(int, QListViewItem*, const QPoint&, int ) ), - this, SLOT(slotClicked(int, QListViewItem*, const QPoint&, int ) ) ); + connect(m_view, SIGNAL(mouseButtonClicked(int,QListViewItem*,const QPoint&,int) ), + this, SLOT(slotClicked(int,QListViewItem*,const QPoint&,int) ) ); } void OFileViewFileListView::slotCurrentChanged( QListViewItem* item) { if (!item) return; #if 0 OFileSelectorItem *sel = static_cast<OFileSelectorItem*>(item); if (!sel->isDir() ) { selector()->m_lneEdit->setText( sel->text(1) ); // if in fileselector mode we will emit selected if ( selector()->mode() == OFileSelector::FileSelector ) { qWarning("slot Current Changed"); QStringList str = QStringList::split("->", sel->text(1) ); QString path = sel->directory() + "/" + str[0].stripWhiteSpace(); emit selector()->fileSelected( path ); DocLnk lnk( path ); emit selector()->fileSelected( lnk ); } } #endif } void OFileViewFileListView::slotClicked(int button , QListViewItem* item, const QPoint&, int ) { if (!item || ( button != Qt::LeftButton) ) return; OFileSelectorItem *sel = static_cast<OFileSelectorItem*>(item); if (!sel->isLocked() ) { QStringList str = QStringList::split("->", sel->text(1) ); if (sel->isDir() ) { m_currentDir = sel->directory() + "/" + str[0].stripWhiteSpace(); emit selector()->dirSelected( m_currentDir ); reread( m_all ); } else { // file qWarning("slot Clicked"); selector()->m_lneEdit->setText( str[0].stripWhiteSpace() ); QString path = sel->directory() + "/" + str[0].stripWhiteSpace(); emit selector()->fileSelected( path ); DocLnk lnk( path ); emit selector()->fileSelected( lnk ); } } // not locked } void OFileViewFileListView::addFile( QFileInfo* info, bool symlink ) { MimeType type( info->absFilePath() ); if (!compliesMime( type.id() ) ) return; QPixmap pix = type.pixmap(); QString dir, name; bool locked; if ( pix.isNull() ) { QWMatrix matrix; QPixmap pixer(Resource::loadPixmap("UnknownDocument") ); matrix.scale( .4, .4 ); pix = pixer.xForm( matrix ); } dir = info->dirPath( true ); locked = false; if ( symlink ) name = info->fileName() + " -> " + info->dirPath() + "/" + info->readLink(); else { name = info->fileName(); if ( ( (selector()->mode() == OFileSelector::Open)&& !info->isReadable() ) || ( (selector()->mode() == OFileSelector::Save)&& !info->isWritable() ) ) { locked = true; pix = Resource::loadPixmap("locked"); } } (void)new OFileSelectorItem( m_view, pix, name, info->lastModified().toString(), QString::number( info->size() ), dir, locked ); } void OFileViewFileListView::addDir( QFileInfo* info, bool symlink ) { bool locked = false; QString name; QPixmap pix; if ( ( ( selector()->mode() == OFileSelector::Open ) && !info->isReadable() ) || ( ( selector()->mode() == OFileSelector::Save ) && !info->isWritable() ) ) { locked = true; if ( symlink ) pix = Resource::loadPixmap( "opie/symlink" ); else pix = Resource::loadPixmap( "lockedfolder" ); } else pix = symlink ? Resource::loadPixmap( "opie/symlink") : Resource::loadPixmap("folder"); name = symlink ? info->fileName() + " -> " + info->dirPath(true) + "/" + info->readLink() : info->fileName(); (void)new OFileSelectorItem( m_view, pix, name, info->lastModified().toString(), QString::number( info->size() ), info->dirPath( true ), locked, true ); } void OFileViewFileListView::addSymlink( QFileInfo* , bool ) { } void OFileViewFileListView::cdUP() { QDir dir( m_currentDir ); dir.cdUp(); if (!dir.exists() ) m_currentDir = "/"; else m_currentDir = dir.absPath(); emit selector()->dirSelected( m_currentDir ); reread( m_all ); } void OFileViewFileListView::cdHome() { m_currentDir = QDir::homeDirPath(); emit selector()->dirSelected( m_currentDir ); reread( m_all ); } void OFileViewFileListView::cdDoc() { m_currentDir = QPEApplication::documentDir(); emit selector()->dirSelected( m_currentDir ); reread( m_all ); } void OFileViewFileListView::changeDir( const QString& dir ) { m_currentDir = dir; emit selector()->dirSelected( m_currentDir ); reread( m_all ); } void OFileViewFileListView::slotFSActivated( int id ) { changeDir ( m_dev[m_fsPop->text(id)] ); } /* check if the mimetype in mime * complies with the one which is current */ /* * We've the mimetype of the file * We need to get the stringlist of the current mimetype * * mime = image@slashjpeg * QStringList = 'image@slash*' * or QStringList = image/jpeg;image/png;application/x-ogg * or QStringList = application/x-ogg;image@slash*; * with all these mime filters it should get acceptes * to do so we need to look if mime is contained inside * the stringlist * if it's contained return true * if not ( I'm no RegExp expert at all ) we'll look if a '@slash*' * is contained in the mimefilter and then we will * look if both are equal until the '/' */ bool OFileViewFileListView::compliesMime( const QString& str) { if (str.isEmpty() || m_mimes.isEmpty() || str.stripWhiteSpace().isEmpty() ) return true; for (QStringList::Iterator it = m_mimes.begin(); it != m_mimes.end(); ++it ) { QRegExp reg( (*it) ); reg.setWildcard( true ); if ( str.find( reg ) != -1 ) return true; } return false; @@ -790,377 +790,377 @@ void OFileViewFileSystem::reread() } int OFileViewFileSystem::fileCount()const { if (!m_view ) return -1; return m_view->fileCount(); } QWidget* OFileViewFileSystem::widget( QWidget* parent ) { if (!m_view ) { m_view = new OFileViewFileListView( parent, startDirectory(), selector() ); } return m_view; } void OFileViewFileSystem::activate( const QString& str) { m_all = (str != QObject::tr("Files") ); } /* Selector */ /** * @short new and complete c'tor * * Create a OFileSelector to let the user select a file. It can * either be used to open a file, select a save name in a dir or * as a dropin for the FileSelector. * * <pre> * QMap<QString, QStringList> mimeTypes; * QStringList types; * types << "text@slash* "; * types << "audio@slash*"; * mimeTypes.insert( tr("Audio and Text"), types ); * mimeTypes.insert( tr("All"), "*@slash*); * * now you could create your fileselector * </pre> * * * @param parent the parent of this widget * @param mode The mode from the enum Mode (Open,Save,FILESELECTOR) * @param sel The selector to be used * @param dirName The name of the dir to start int * @param fileName The fileName placed in the fileselector lineedit * @param mimetypes The MimeType map of used mimetypes * @param showNew Show a New Button. Most likely to be used in the FileSelector view. * @param showClose Show a Close Button. Most likely to be used in FileSelector view. * */ OFileSelector::OFileSelector( QWidget* parent, int mode, int sel, const QString& dirName, const QString& fileName, const MimeTypes& mimetypes, bool showNew, bool showClose) :QWidget( parent, "OFileSelector" ) { m_current = 0; m_shNew = showNew; m_shClose = showClose; m_mimeType = mimetypes; m_startDir = dirName; m_mode = mode; m_selector = sel; initUI(); m_lneEdit->setText( fileName ); initMime(); initViews(); QString str; switch ( m_selector ) { default: case Normal: str = QObject::tr("Documents"); m_cmbView->setCurrentItem( 0 ); break; case Extended: str = QObject::tr("Files"); m_cmbView->setCurrentItem( 1 ); break; case ExtendedAll: str = QObject::tr("All Files"); m_cmbView->setCurrentItem( 2 ); break; } slotViewChange( str ); } /** * This a convience c'tor to just substitute the use of FileSelector */ OFileSelector::OFileSelector( const QString& mimeFilter, QWidget* parent, const char* name, bool showNew, bool showClose ) : QWidget( parent, name ) { m_current = 0; m_shNew = showNew; m_shClose = showClose; m_startDir = QPEApplication::documentDir(); if (!mimeFilter.isEmpty() ) m_mimeType.insert(mimeFilter, QStringList::split(";", mimeFilter ) ); m_mode = OFileSelector::FileSelector; m_selector = OFileSelector::Normal; initUI(); initMime(); initViews(); m_cmbView->setCurrentItem( 0 ); slotViewChange( QObject::tr("Documents") ); } /* * INIT UI will set up the basic GUI * Layout: Simple VBoxLayout * On top a WidgetStack containing the Views... * - List View * - Document View * Below we will have a Label + LineEdit * Below we will have two ComoBoxes one for choosing the view one for * choosing the mimetype */ void OFileSelector::initUI() { QVBoxLayout* lay = new QVBoxLayout( this ); m_stack = new QWidgetStack( this ); lay->addWidget( m_stack, 1000 ); m_nameBox = new QHBox( this ); (void)new QLabel( tr("Name:"), m_nameBox ); m_lneEdit = new QLineEdit( m_nameBox ); m_lneEdit ->installEventFilter(this); lay->addWidget( m_nameBox ); m_cmbBox = new QHBox( this ); m_cmbView = new QComboBox( m_cmbBox ); m_cmbMime = new QComboBox( m_cmbBox ); lay->addWidget( m_cmbBox ); } /* * This will make sure that the return key in the name edit causes dialogs to close */ bool OFileSelector::eventFilter (QObject *o, QEvent *e) { if ( e->type() == QEvent::KeyPress ) { QKeyEvent *k = (QKeyEvent *)e; if ( (k->key()==Key_Enter) || (k->key()==Key_Return)) { emit ok(); return true; } } return false; } /* * This will insert the MimeTypes into the Combo Box * And also connect the changed signal * * AutoMimeTyping is disabled for now. It used to reparse a dir and then set available mimetypes */ void OFileSelector::initMime() { MimeTypes::Iterator it; for ( it = m_mimeType.begin(); it != m_mimeType.end(); ++it ) { m_cmbMime->insertItem( it.key() ); } m_cmbMime->setCurrentItem( 0 ); connect( m_cmbMime, SIGNAL(activated(int) ), this, SLOT(slotMimeTypeChanged() ) ); } void OFileSelector::initViews() { m_cmbView->insertItem( QObject::tr("Documents") ); m_cmbView->insertItem( QObject::tr("Files") ); m_cmbView->insertItem( QObject::tr("All Files") ); - connect(m_cmbView, SIGNAL(activated( const QString& ) ), - this, SLOT(slotViewChange( const QString& ) ) ); + connect(m_cmbView, SIGNAL(activated(const QString&) ), + this, SLOT(slotViewChange(const QString&) ) ); m_views.insert( QObject::tr("Documents"), new ODocumentFileView(this) ); /* see above why add both */ OFileViewInterface* in = new OFileViewFileSystem( this ); m_views.insert( QObject::tr("Files"), in ); m_views.insert( QObject::tr("All Files"), in ); } /** * d'tor */ OFileSelector::~OFileSelector() { } /** * Convience function for the fileselector * make sure to delete the DocLnk * * @see DocLnk * @todo remove in ODP */ const DocLnk* OFileSelector::selected() { DocLnk* lnk = new DocLnk( currentView()->selectedDocument() ); return lnk; } /** * * @return the name of the selected file */ QString OFileSelector::selectedName()const { return currentView()->selectedName(); } /** * @return the selected path */ QString OFileSelector::selectedPath()const { return currentView()->selectedPath(); } /** * @return the directory name */ QString OFileSelector::directory()const { return currentView()->directory(); } /** * @return a DocLnk for the selected document */ DocLnk OFileSelector::selectedDocument()const { return currentView()->selectedDocument(); } /** * @return the number of items for the current view */ int OFileSelector::fileCount()const { return currentView()->fileCount(); } /** * @return reparse the file content */ void OFileSelector::reread() { return currentView()->reread(); } OFileViewInterface* OFileSelector::currentView()const { return m_current; } bool OFileSelector::showNew()const { return m_shNew; } bool OFileSelector::showClose()const { return m_shClose; } MimeTypes OFileSelector::mimeTypes()const { return m_mimeType; } /** * @return the Mode of the OFileSelector */ int OFileSelector::mode()const { return m_mode; } /** * @return the Selector of the OFileSelector */ int OFileSelector::selector()const { return m_selector; } QStringList OFileSelector::currentMimeType()const { return m_mimeType[m_cmbMime->currentText()]; } void OFileSelector::slotMimeTypeChanged() { reread(); } void OFileSelector::slotDocLnkBridge( const DocLnk& lnk) { m_lneEdit->setText( lnk.name() ); emit fileSelected( lnk ); emit fileSelected( lnk.name() ); } void OFileSelector::slotFileBridge( const QString& str) { DocLnk lnk( str ); emit fileSelected( lnk ); } void OFileSelector::slotViewChange( const QString& view ) { OFileViewInterface* interface = m_views[view]; if (!interface) return; interface->activate( view ); if (m_current) m_stack->removeWidget( m_current->widget( m_stack ) ); static int id = 1; m_stack->addWidget( interface->widget(m_stack), id ); m_stack->raiseWidget( id ); interface->reread(); m_current = interface; id++; } void OFileSelector::setNewVisible( bool b ) { m_shNew = b; currentView()->reread(); } void OFileSelector::setCloseVisible( bool b ) { m_shClose = b; currentView()->reread(); } void OFileSelector::setNameVisible( bool b ) { if ( b ) m_nameBox->show(); else m_nameBox->hide(); } diff --git a/libopie2/opieui/ofontselector.cpp b/libopie2/opieui/ofontselector.cpp index 49ddeb6..f93781f 100644 --- a/libopie2/opieui/ofontselector.cpp +++ b/libopie2/opieui/ofontselector.cpp @@ -1,341 +1,341 @@ /* This file is part of the Opie Project Copyright (C) Robert Griebl <sandman@handhelds.org> =. Copyright (C) The Opie Team <opie-devel@handhelds.org> .=l. .>+-= _;:, .> :=|. This program is free software; you can .> <`_, > . <= redistribute it and/or modify it under :`=1 )Y*s>-.-- : the terms of the GNU Library General Public .="- .-=="i, .._ License as published by the Free Software - . .-<_> .<> Foundation; either version 2 of the License, ._= =} : or (at your option) any later version. .%`+i> _;_. .i_,=:_. -<s. This program 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. */ /* OPIE */ #include <opie2/ofontselector.h> #include <qpe/fontdatabase.h> /* QT */ #include <qlayout.h> #include <qlistbox.h> #include <qcombobox.h> #include <qlabel.h> #include <qmultilineedit.h> using namespace Opie; namespace Opie { class OFontSelectorPrivate { public: QListBox * m_font_family_list; QComboBox * m_font_style_list; QComboBox * m_font_size_list; QMultiLineEdit *m_preview; bool m_pointbug : 1; FontDatabase m_fdb; }; }; namespace { class FontListItem : public QListBoxText { public: FontListItem ( const QString &t, const QStringList &styles, const QValueList<int> &sizes ) : QListBoxText() { m_name = t; m_styles = styles; m_sizes = sizes; QString str = t; str [0] = str [0]. upper(); setText ( str ); } QString family() const { return m_name; } const QStringList &styles() const { return m_styles; } const QValueList<int> &sizes() const { return m_sizes; } private: QStringList m_styles; QValueList<int> m_sizes; QString m_name; }; static int findItemCB( QComboBox *box, const QString &str ) { for ( int i = 0; i < box->count(); i++ ) { if ( box->text ( i ) == str ) return i; } return -1; } } /* static same as anon. namespace */ static int qt_version() { const char *qver = qVersion(); return ( qver [0] - '0' ) * 100 + ( qver [2] - '0' ) * 10 + ( qver [4] - '0' ); } /** * Constructs the Selector object * @param withpreview If a font preview should be given * @param parent The parent of the Font Selector * @param name The name of the object * @param fl WidgetFlags */ OFontSelector::OFontSelector( bool withpreview, QWidget *parent, const char *name, WFlags fl ) : QWidget ( parent, name, fl ) { d = new OFontSelectorPrivate(); QGridLayout *gridLayout = new QGridLayout( this, 0, 0, 4, 4 ); gridLayout->setRowStretch( 4, 10 ); d->m_font_family_list = new QListBox( this, "FontListBox" ); gridLayout->addMultiCellWidget( d->m_font_family_list, 0, 4, 0, 0 ); - connect( d->m_font_family_list, SIGNAL( highlighted( int ) ), this, SLOT( fontFamilyClicked( int ) ) ); + connect( d->m_font_family_list, SIGNAL( highlighted(int) ), this, SLOT( fontFamilyClicked(int) ) ); QLabel *label = new QLabel( tr( "Style" ), this ); gridLayout->addWidget( label, 0, 1 ); d->m_font_style_list = new QComboBox( this, "StyleListBox" ); - connect( d->m_font_style_list, SIGNAL( activated( int ) ), this, SLOT( fontStyleClicked( int ) ) ); + connect( d->m_font_style_list, SIGNAL( activated(int) ), this, SLOT( fontStyleClicked(int) ) ); gridLayout->addWidget( d->m_font_style_list, 1, 1 ); label = new QLabel( tr( "Size" ), this ); gridLayout->addWidget( label, 2, 1 ); d->m_font_size_list = new QComboBox( this, "SizeListBox" ); - connect( d->m_font_size_list, SIGNAL( activated( int ) ), - this, SLOT( fontSizeClicked( int ) ) ); + connect( d->m_font_size_list, SIGNAL( activated(int) ), + this, SLOT( fontSizeClicked(int) ) ); gridLayout->addWidget( d->m_font_size_list, 3, 1 ); d->m_pointbug = ( qt_version() <= 233 ); if ( withpreview ) { d->m_preview = new QMultiLineEdit ( this, "Preview" ); d->m_preview->setAlignment ( AlignCenter ); d->m_preview->setWordWrap ( QMultiLineEdit::WidgetWidth ); d->m_preview->setMargin ( 3 ); d->m_preview->setText ( tr( "The Quick Brown Fox Jumps Over The Lazy Dog" )); gridLayout->addRowSpacing ( 5, 4 ); gridLayout->addMultiCellWidget ( d->m_preview, 6, 6, 0, 1 ); gridLayout->setRowStretch ( 6, 5 ); } else d->m_preview = 0; loadFonts ( d->m_font_family_list ); } OFontSelector::~OFontSelector() { delete d; } /** * This methods tries to set the font * @param f The wishes font * @return success or failure */ bool OFontSelector::setSelectedFont ( const QFont &f ) { return setSelectedFont ( f. family(), d->m_fdb. styleString ( f ), f. pointSize(), QFont::encodingName ( f. charSet())); } /** * This is an overloaded method @see setSelectedFont * @param familyStr The family of the font * @param styleStr The style of the font * @param sizeVal The size of font * @param charset The charset to be used. Will be deprecated by QT3 */ bool OFontSelector::setSelectedFont( const QString &familyStr, const QString &styleStr, int sizeVal, const QString & charset ) { QString sizeStr = QString::number ( sizeVal ); QListBoxItem *family = d->m_font_family_list->findItem ( familyStr ); if ( !family ) family = d->m_font_family_list->findItem ( "Helvetica" ); if ( !family ) family = d->m_font_family_list->firstItem(); d->m_font_family_list->setCurrentItem ( family ); fontFamilyClicked ( d->m_font_family_list->index ( family )); int style = findItemCB ( d->m_font_style_list, styleStr ); if ( style < 0 ) style = findItemCB ( d->m_font_style_list, "Regular" ); if ( style < 0 && d->m_font_style_list->count() > 0 ) style = 0; d->m_font_style_list->setCurrentItem ( style ); fontStyleClicked ( style ); int size = findItemCB ( d->m_font_size_list, sizeStr ); if ( size < 0 ) size = findItemCB ( d->m_font_size_list, "10" ); if ( size < 0 && d->m_font_size_list->count() > 0 ) size = 0; d->m_font_size_list->setCurrentItem ( size ); fontSizeClicked ( size ); return (( family ) && ( style >= 0 ) && ( size >= 0 )); } /** * This method returns the name, style and size of the currently selected * font or false if no font is selected * @param family The font family will be written there * @param style The style will be written there * @param size The size will be written there * @return success or failure */ bool OFontSelector::selectedFont ( QString &family, QString &style, int &size ) { QString dummy; return selectedFont ( family, style, size, dummy ); } /** * This method does return the font family or QString::null if there is * no font item selected * @return the font family */ QString OFontSelector::fontFamily() const { FontListItem *fli = (FontListItem *) d->m_font_family_list->item ( d->m_font_family_list->currentItem()); return fli ? fli->family() : QString::null; } /** * This method will return the style of the font or QString::null * @return the style of the font */ QString OFontSelector::fontStyle() const { FontListItem *fli = (FontListItem *) d->m_font_family_list->item ( d->m_font_family_list->currentItem()); int fst = d->m_font_style_list->currentItem(); return ( fli && fst >= 0 ) ? fli->styles() [fst] : QString::null; } /** * This method will return the font size or 10 if no font size is available */ int OFontSelector::fontSize() const { FontListItem *fli = (FontListItem *) d->m_font_family_list->item ( d->m_font_family_list->currentItem()); int fsi = d->m_font_size_list->currentItem(); return ( fli && fsi >= 0 ) ? fli->sizes() [fsi] : 10; } /** * returns the charset of the font or QString::null */ QString OFontSelector::fontCharSet() const { FontListItem *fli = (FontListItem *) d->m_font_family_list->item ( d->m_font_family_list->currentItem()); return fli ? d->m_fdb. charSets ( fli->family()) [0] : QString::null; } /** * Overloaded member function see above * @see selectedFont */ bool OFontSelector::selectedFont ( QString &family, QString &style, int &size, QString &charset ) { int ffa = d->m_font_family_list->currentItem(); int fst = d->m_font_style_list->currentItem(); int fsi = d->m_font_size_list->currentItem(); FontListItem *fli = (FontListItem *) d->m_font_family_list->item ( ffa ); if ( fli ) { family = fli->family(); style = fst >= 0 ? fli->styles() [fst] : QString::null; size = fsi >= 0 ? fli->sizes() [fsi] : 10; charset = d->m_fdb. charSets ( fli->family()) [0]; return true; } else return false; } void OFontSelector::loadFonts ( QListBox *list ) { QStringList f = d->m_fdb. families(); for ( QStringList::ConstIterator it = f. begin(); it != f. end(); ++it ) { QValueList <int> ps = d->m_fdb. pointSizes ( *it ); if ( d->m_pointbug ) { for ( QValueList <int>::Iterator it = ps. begin(); it != ps. end(); it++ ) *it /= 10; } list->insertItem ( new FontListItem ( *it, d->m_fdb. styles ( *it ), ps )); } } void OFontSelector::fontFamilyClicked ( int index ) { QString oldstyle = d->m_font_style_list->currentText(); QString oldsize = d->m_font_size_list->currentText(); FontListItem *fli = (FontListItem *) d->m_font_family_list->item ( index ); d->m_font_style_list->clear(); d->m_font_style_list->insertStringList ( fli->styles()); d->m_font_style_list->setEnabled ( !fli->styles(). isEmpty()); int i; i = findItemCB ( d->m_font_style_list, oldstyle ); diff --git a/libopie2/opieui/otabwidget.cpp b/libopie2/opieui/otabwidget.cpp index ec6af9d..f47c90b 100644 --- a/libopie2/opieui/otabwidget.cpp +++ b/libopie2/opieui/otabwidget.cpp @@ -1,273 +1,273 @@ /* This file is part of the Opie Project Copyright (c) 2002 Dan Williams <williamsdr@acm.org> =. .=l. .>+-= _;:, .> :=|. This program is free software; you can .> <`_, > . <= redistribute it and/or modify it under :`=1 )Y*s>-.-- : the terms of the GNU Library General Public .="- .-=="i, .._ License as published by the Free Software - . .-<_> .<> Foundation; either version 2 of the License, ._= =} : or (at your option) any later version. .%`+i> _;_. .i_,=:_. -<s. This program 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 <opie2/otabwidget.h> /* OPIE */ #include <qpe/applnk.h> #include <qpe/config.h> #include <qpe/resource.h> #include <opie2/otabbar.h> /* QT */ #include <qcombobox.h> #include <qwidgetstack.h> using namespace Opie; OTabWidget::OTabWidget( QWidget *parent, const char *name, TabStyle s, TabPosition p ) : QWidget( parent, name ) { if ( s == Global ) { Config config( "qpe" ); config.setGroup( "Appearance" ); s = ( TabStyle ) config.readNumEntry( "TabStyle", (int) IconTab ); if ( s <= Global || s > IconList) { s = IconTab; } QString pos = config.readEntry( "TabPosition", "Top"); if ( pos == "Bottom" ) { p = Bottom; } else { p = Top; } } widgetStack = new QWidgetStack( this, "widgetstack" ); widgetStack->setFrameStyle( QFrame::NoFrame ); widgetStack->setLineWidth( style().defaultFrameWidth() ); tabBarStack = new QWidgetStack( this, "tabbarstack" ); tabBar = new OTabBar( tabBarStack, "tabbar" ); tabBarStack->addWidget( tabBar, 0 ); - connect( tabBar, SIGNAL( selected( int ) ), this, SLOT( slotTabBarSelected( int ) ) ); + connect( tabBar, SIGNAL( selected(int) ), this, SLOT( slotTabBarSelected(int) ) ); tabList = new QComboBox( false, tabBarStack, "tablist" ); tabBarStack->addWidget( tabList, 1 ); - connect( tabList, SIGNAL( activated( int ) ), this, SLOT( slotTabListSelected( int ) ) ); + connect( tabList, SIGNAL( activated(int) ), this, SLOT( slotTabListSelected(int) ) ); tabBarPosition = p; setTabStyle( s ); setTabPosition( p ); currTab= 0x0; } OTabWidget::~OTabWidget() {} void OTabWidget::addTab( QWidget *child, const QString &icon, const QString &label ) { QPixmap iconset = loadSmooth( icon ); QTab *tab = new QTab(); if ( tabBarStyle == IconTab ) { tab->label = QString::null; } else { tab->label = label; } if ( tabBarStyle == IconTab || tabBarStyle == IconList ) { tab->iconset = new QIconSet( iconset ); } int tabid = tabBar->addTab( tab ); if ( tabBarStyle == IconTab || tabBarStyle == IconList ) { tabList->insertItem( iconset, label, -1 ); } else { tabList->insertItem( label ); } widgetStack->addWidget( child, tabid ); widgetStack->raiseWidget( child ); widgetStack->setFrameStyle( QFrame::StyledPanel | QFrame::Raised ); OTabInfo *tabinfo = new OTabInfo( tabid, child, icon, label ); tabs.append( tabinfo ); selectTab( tabinfo ); } void OTabWidget::removePage( QWidget *childwidget ) { if ( childwidget ) { OTabInfo *tab = tabs.first(); while ( tab && tab->control() != childwidget ) { tab = tabs.next(); } if ( tab && tab->control() == childwidget ) { tabBar->setTabEnabled( tab->id(), FALSE ); tabBar->removeTab( tabBar->tab( tab->id() ) ); int i = 0; while ( i < tabList->count() && tabList->text( i ) != tab->label() ) { i++; } if ( tabList->text( i ) == tab->label() ) { tabList->removeItem( i ); } widgetStack->removeWidget( childwidget ); tabs.remove( tab ); delete tab; currTab = tabs.current(); if ( !currTab ) { widgetStack->setFrameStyle( QFrame::NoFrame ); } setUpLayout(); } } } void OTabWidget::changeTab( QWidget *widget, const QString &iconset, const QString &label) { OTabInfo *currtab = tabs.first(); while ( currtab && currtab->control() != widget ) { currtab = tabs.next(); } if ( currtab && currtab->control() == widget ) { QTab *tab = tabBar->tab( currtab->id() ); QPixmap icon( loadSmooth( iconset ) ); tab->setText( label ); if ( tabBarStyle == IconTab ) tab->setIconSet( icon ); int i = 0; while ( i < tabList->count() && tabList->text( i ) != currtab->label() ) { i++; } if ( i < tabList->count() && tabList->text( i ) == currtab->label() ) { if ( tabBarStyle == IconTab || tabBarStyle == IconList ) { tabList->changeItem( icon, label, i ); } else { tabList->changeItem( label, i ); } } currtab->setLabel( label ); currtab->setIcon( iconset ); } setUpLayout(); } void OTabWidget::setCurrentTab( QWidget *childwidget ) { OTabInfo *currtab = tabs.first(); while ( currtab && currtab->control() != childwidget ) { currtab = tabs.next(); } if ( currtab && currtab->control() == childwidget ) { selectTab( currtab ); } } void OTabWidget::setCurrentTab( const QString &tabname ) { OTabInfo *newtab = tabs.first(); while ( newtab && newtab->label() != tabname ) { newtab = tabs.next(); } if ( newtab && newtab->label() == tabname ) { selectTab( newtab ); } } void OTabWidget::setCurrentTab(int tabindex) { OTabInfo *newtab = tabs.first(); while ( newtab && newtab->id() != tabindex ) { newtab = tabs.next(); } if ( newtab && newtab->id() == tabindex ) { selectTab( newtab ); } } OTabWidget::TabStyle OTabWidget::tabStyle() const { return tabBarStyle; } void OTabWidget::setTabStyle( TabStyle s ) { tabBarStyle = s; if ( tabBarStyle == TextTab || tabBarStyle == IconTab ) { QTab *currtab; for ( OTabInfo *tabinfo = tabs.first(); tabinfo; tabinfo = tabs.next() ) { currtab = tabBar->tab( tabinfo->id() ); if ( tabBarStyle == IconTab ) { currtab->iconset = new QIconSet( loadSmooth( tabinfo->icon() ) ); if ( tabinfo == currTab ) currtab->setText( tabinfo->label() ); else currtab->setText( QString::null ); } else { currtab->iconset = 0x0; currtab->setText( tabinfo->label() ); } } tabBarStack->raiseWidget( tabBar ); } else if ( tabBarStyle == TextList || tabBarStyle == IconList ) { diff --git a/libopie2/opieui/otimepicker.cpp b/libopie2/opieui/otimepicker.cpp index d4712a4..66f9ce0 100644 --- a/libopie2/opieui/otimepicker.cpp +++ b/libopie2/opieui/otimepicker.cpp @@ -32,261 +32,261 @@ #include <qlineedit.h> /* OPIE */ #include <opie2/otimepicker.h> using namespace Opie; /** * Constructs the widget * @param parent The parent of the OTimePicker * @param name The name of the object * @param fl Window Flags */ OTimePicker::OTimePicker(QWidget* parent, const char* name, Qt::WFlags fl) :QWidget(parent,name,fl) { QVBoxLayout *vbox=new QVBoxLayout(this); OClickableLabel *r; QString s; // Hour Row QWidget *row=new QWidget(this); QHBoxLayout *l=new QHBoxLayout(row); vbox->addWidget(row); for (int i=0; i<24; i++) { r=new OClickableLabel(row); hourLst.append(r); s.sprintf("%.2d",i); r->setText(s); r->setToggleButton(true); r->setAlignment(AlignHCenter | AlignVCenter); l->addWidget(r); connect(r, SIGNAL(toggled(bool)), this, SLOT(slotHour(bool))); if (i==11) { // Second row row=new QWidget(this); l=new QHBoxLayout(row); vbox->addWidget(row); } } // Minute Row row=new QWidget(this); l=new QHBoxLayout(row); vbox->addWidget(row); for (int i=0; i<60; i+=5) { r=new OClickableLabel(row); minuteLst.append(r); s.sprintf("%.2d",i); r->setText(s); r->setToggleButton(true); r->setAlignment(AlignHCenter | AlignVCenter); l->addWidget(r); connect(r, SIGNAL(toggled(bool)), this, SLOT(slotMinute(bool))); } } /** * This method return the current time * @return the time */ QTime OTimePicker::time()const { return tm; } void OTimePicker::slotHour(bool b) { OClickableLabel *r = (OClickableLabel *) sender(); if (b) { QValueListIterator<OClickableLabel *> it; for (it=hourLst.begin(); it!=hourLst.end(); it++) { if (*it != r) (*it)->setOn(false); else tm.setHMS((*it)->text().toInt(), tm.minute(), 0); } emit timeChanged(tm); } else { r->setOn(true); } } void OTimePicker::slotMinute(bool b) { OClickableLabel *r = (OClickableLabel *) sender(); if (b) { QValueListIterator<OClickableLabel *> it; for (it=minuteLst.begin(); it!=minuteLst.end(); it++) { if (*it != r) (*it)->setOn(false); else tm.setHMS(tm.hour(),(*it)->text().toInt(), 0); } emit timeChanged(tm); } else { r->setOn(true); } } /** * Method to set the time. No signal gets emitted during this method call * Minutes must be within 5 minutes step starting at 0 ( 0,5,10,15,20... ) * @param t The time to be set */ void OTimePicker::setTime( const QTime& t) { setTime( t.hour(), t.minute() ); } /** * Method to set the time. No signal gets emitted during this method call * @param h The hour * @param m The minute. Minutes need to set by 5 minute steps */ void OTimePicker::setTime( int h, int m ) { setHour(h); setMinute(m); } /* * FIXME round minutes to the 5 minute arrangement -zecke */ /** * Method to set the minutes * @param m minutes */ void OTimePicker::setMinute(int m) { QString minute; minute.sprintf("%.2d",m); QValueListIterator<OClickableLabel *> it; for (it=minuteLst.begin(); it!=minuteLst.end(); it++) { if ((*it)->text() == minute) (*it)->setOn(true); else (*it)->setOn(false); } tm.setHMS(tm.hour(),m,0); } /** * Method to set the hour */ void OTimePicker::setHour(int h) { QString hour; hour.sprintf("%.2d",h); QValueListIterator<OClickableLabel *> it; for (it=hourLst.begin(); it!=hourLst.end(); it++) { if ((*it)->text() == hour) (*it)->setOn(true); else (*it)->setOn(false); } tm.setHMS(h,tm.minute(),0); } /** * This is a modal Dialog. * * @param parent The parent widget * @param name The name of the object * @param fl Possible window flags */ OTimePickerDialog::OTimePickerDialog ( QWidget* parent, const char* name, WFlags fl ) : OTimePickerDialogBase (parent , name, true , fl) { - connect ( m_timePicker, SIGNAL( timeChanged( const QTime& ) ), - this, SLOT( setTime ( const QTime& ) ) ); - connect ( minuteField, SIGNAL( textChanged ( const QString& ) ), - this, SLOT ( setMinute ( const QString& ) ) ); - connect ( hourField, SIGNAL( textChanged ( const QString& ) ), - this, SLOT ( setHour ( const QString& ) ) ); + connect ( m_timePicker, SIGNAL( timeChanged(const QTime&) ), + this, SLOT( setTime(const QTime&) ) ); + connect ( minuteField, SIGNAL( textChanged(const QString&) ), + this, SLOT ( setMinute(const QString&) ) ); + connect ( hourField, SIGNAL( textChanged(const QString&) ), + this, SLOT ( setHour(const QString&) ) ); } /** * @return the time */ QTime OTimePickerDialog::time()const { return m_time; } /** * Set the time to time * @param time The time to be set */ void OTimePickerDialog::setTime( const QTime& time ) { m_time = time; m_timePicker->setHour ( time.hour() ); m_timePicker->setMinute( time.minute() ); // Set Textfields if ( time.hour() < 10 ) hourField->setText( "0" + QString::number( time.hour() ) ); else hourField->setText( QString::number( time.hour() ) ); if ( time.minute() < 10 ) minuteField->setText( "0" + QString::number( time.minute() ) ); else minuteField->setText( QString::number( time.minute() ) ); } /** * This method takes the current minute and tries to set hour * to hour. This succeeds if the resulting date is valid * @param hour The hour as a string */ void OTimePickerDialog::setHour ( const QString& hour ) { if ( QTime::isValid ( hour.toInt(), m_time.minute() , 00 ) ) { m_time.setHMS ( hour.toInt(), m_time.minute() , 00 ); setTime ( m_time ); } } /** * Method to set a new minute. It tries to convert the string to int and * if the resulting date is valid a new date is set. * @see setHour */ void OTimePickerDialog::setMinute ( const QString& minute ) { if ( QTime::isValid ( m_time.hour(), minute.toInt(), 00 ) ) { m_time.setHMS ( m_time.hour(), minute.toInt(), 00 ); setTime ( m_time ); } } diff --git a/libopie2/opieui/oversatileview.cpp b/libopie2/opieui/oversatileview.cpp index 8839456..78154b7 100644 --- a/libopie2/opieui/oversatileview.cpp +++ b/libopie2/opieui/oversatileview.cpp @@ -1,410 +1,410 @@ /* This file is part of the Opie Project =. (C) 2003 Michael 'Mickey' Lauer <mickey@tm.informatik.uni-frankfurt.de> .=l. .>+-= _;:, .> :=|. This program is free software; you can .> <`_, > . <= redistribute it and/or modify it under :`=1 )Y*s>-.-- : the terms of the GNU Library General Public .="- .-=="i, .._ License as published by the Free Software - . .-<_> .<> Foundation; either version 2 of the License, ._= =} : or (at your option) any later version. .%`+i> _;_. .i_,=:_. -<s. This program 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. */ /* OPIE */ #include <opie2/odebug.h> #include <opie2/oversatileview.h> #include <opie2/oversatileviewitem.h> #include <opie2/olistview.h> /* QT */ #include <qaction.h> #include <qpopupmenu.h> /* XPM */ static const char * view_icon_xpm[] = { "16 16 16 1", " c None", ". c #87BD88", "+ c #8BBE8B", "@ c #81BA81", "# c #6DAF6D", "$ c #87BD87", "% c #FCFDFC", "& c #AED0AE", "* c #4E9C4C", "= c #91BD91", "- c #72B172", "; c #448643", "> c #519F50", ", c #499247", "' c #356A35", ") c #686868", " ", " .+@# .+@# ", " $%&* $%&* ", " @=-; @=-; ", " #>,' #>,' ", " ", " )))))) )))))) ", " ", " ", " .+@# .+@# ", " $%&* $%&* ", " @=-; @=-; ", " #>,' #>,' ", " ", " )))))) )))))) ", " "}; /* XPM */ static const char * view_tree_xpm[] = { "16 16 17 1", " c None", ". c #3A3A3A", "+ c #87BD88", "@ c #8BBE8B", "# c #81BA81", "$ c #6DAF6D", "% c #87BD87", "& c #FCFDFC", "* c #AED0AE", "= c #4E9C4C", "- c #91BD91", "; c #72B172", "> c #448643", ", c #686868", "' c #519F50", ") c #499247", "! c #356A35", " . ", " . ", " . +@#$ ", " . %&*= ", " .. #-;> ,, ,,,", " . $')! ", " . ", " . ", " . ", " . +@#$ ", " . %&*= ", " .. #-;> ,, ,,,", " $')! ", " ", " ", " "}; OVersatileView::OVersatileView( QWidget* parent, const char* name, int mode ) :QWidgetStack( parent, name ), _viewmode( mode ), _warningpolicy( None ), _treeleaf(), _treeopened(), _treeclosed(), _iconleaf(), _iconopened(), _iconclosed() { // // Create child widgets and set some reasonable default styles // _listview = new OListView( this, "oversatileview embedded listview" ); _iconview = new QIconView( this, "oversatileview embedded iconview" ); _listview->setAllColumnsShowFocus( true ); _listview->setRootIsDecorated( true ); _listview->setShowSortIndicator( true ); _iconview->setGridX( 90 ); _iconview->setGridY( 42 ); _iconview->setAutoArrange( true ); #ifdef QWS // TODO: Let this depend on current geometry (rotation) _iconview->setArrangement( QIconView::TopToBottom ); #else _iconview->setArrangement( QIconView::LeftToRight ); #endif _iconview->setResizeMode( QIconView::Adjust ); // qt-embedded: map stylus right on hold to right button press #ifdef QWS ( (QPEApplication*) qApp)->setStylusOperation( _iconview->viewport(), QPEApplication::RightOnHold ); ( (QPEApplication*) qApp)->setStylusOperation( _listview->viewport(), QPEApplication::RightOnHold ); #endif setViewMode( mode ); // TODO: Read last style from config // setSynchronization( true ); // TODO: Implement this // create context menu allowing to switch between the views _contextmenu = new QPopupMenu( 0, "oversatileview contextmenu" ); _contextmenu->setCaption( "Style" ); _contextmenu->setCheckable( true ); QActionGroup* ag = new QActionGroup( _contextmenu, "style option group" ); QAction* a1 = new QAction( "View Items in Icon Style", QIconSet( QPixmap( view_icon_xpm ) ), "View Icons", 0, ag, "viewicon action", true ); QAction* a2 = new QAction( "View Items in Tree Style", QIconSet( QPixmap( view_tree_xpm ) ), "View Tree", 0, ag, "viewtree action", true ); ag->addTo( _contextmenu ); if ( mode == Icons ) a1->setOn( true ); else if ( mode == Tree ) a2->setOn( true ); connect( a1, SIGNAL( activated() ), this, SLOT( setIconViewMode() ) ); connect( a2, SIGNAL( activated() ), this, SLOT( setTreeViewMode() ) ); #if (QT_VERSION >= 0x030000) - connect( _listview, SIGNAL( contextMenuRequested( QListViewItem*, const QPoint&, int ) ), this, SLOT( contextMenuRequested( QListViewItem*, const QPoint&, int ) ) ); - connect( _iconview, SIGNAL( contextMenuRequested( QIconViewItem*, const QPoint& ) ), this, SLOT( contextMenuRequested( QIconViewItem*, const QPoint& ) ) ); + connect( _listview, SIGNAL( contextMenuRequested(QListViewItem*,const QPoint&,int) ), this, SLOT( contextMenuRequested(QListViewItem*,const QPoint&,int) ) ); + connect( _iconview, SIGNAL( contextMenuRequested(QIconViewItem*,const QPoint&) ), this, SLOT( contextMenuRequested(QIconViewItem*,const QPoint&) ) ); #else - connect( _listview, SIGNAL( rightButtonPressed( QListViewItem*, const QPoint&, int ) ), this, SLOT( contextMenuRequested( QListViewItem*, const QPoint&, int ) ) ); - connect( _iconview, SIGNAL( rightButtonPressed( QIconViewItem*, const QPoint& ) ), this, SLOT( contextMenuRequested( QIconViewItem*, const QPoint& ) ) ); + connect( _listview, SIGNAL( rightButtonPressed(QListViewItem*,const QPoint&,int) ), this, SLOT( contextMenuRequested(QListViewItem*,const QPoint&,int) ) ); + connect( _iconview, SIGNAL( rightButtonPressed(QIconViewItem*,const QPoint&) ), this, SLOT( contextMenuRequested(QIconViewItem*,const QPoint&) ) ); #endif // // signal forwarders // // unfortunately we can't short-circuit all the QListView and QIconView signals // to OVersatileView signals, because the signal/slot mechanism doesn't allow // type-conversion :-( // common signals for listview connect( _listview, SIGNAL( selectionChanged() ), this, SIGNAL( selectionChanged() ) ); - connect( _listview, SIGNAL( selectionChanged( QListViewItem * ) ), this, SLOT( selectionChanged( QListViewItem * ) ) ); - connect( _listview, SIGNAL( currentChanged( QListViewItem * ) ), this, SLOT( currentChanged( QListViewItem * ) ) ); - connect( _listview, SIGNAL( clicked( QListViewItem * ) ), this, SLOT( clicked( QListViewItem * ) ) ); - connect( _listview, SIGNAL( pressed( QListViewItem * ) ), this, SLOT( pressed( QListViewItem * ) ) ); + connect( _listview, SIGNAL( selectionChanged(QListViewItem*) ), this, SLOT( selectionChanged(QListViewItem*) ) ); + connect( _listview, SIGNAL( currentChanged(QListViewItem*) ), this, SLOT( currentChanged(QListViewItem*) ) ); + connect( _listview, SIGNAL( clicked(QListViewItem*) ), this, SLOT( clicked(QListViewItem*) ) ); + connect( _listview, SIGNAL( pressed(QListViewItem*) ), this, SLOT( pressed(QListViewItem*) ) ); - connect( _listview, SIGNAL( doubleClicked( QListViewItem * ) ), this, SLOT( doubleClicked( QListViewItem * ) ) ); - connect( _listview, SIGNAL( returnPressed( QListViewItem * ) ), this, SLOT( returnPressed( QListViewItem * ) ) ); + connect( _listview, SIGNAL( doubleClicked(QListViewItem*) ), this, SLOT( doubleClicked(QListViewItem*) ) ); + connect( _listview, SIGNAL( returnPressed(QListViewItem*) ), this, SLOT( returnPressed(QListViewItem*) ) ); - connect( _listview, SIGNAL( onItem( QListViewItem * ) ), this, SLOT( onItem( QListViewItem * ) ) ); + connect( _listview, SIGNAL( onItem(QListViewItem*) ), this, SLOT( onItem(QListViewItem*) ) ); connect( _listview, SIGNAL( onViewport() ), this, SIGNAL( onViewport() ) ); // common signals for iconview connect( _iconview, SIGNAL( selectionChanged() ), this, SIGNAL( selectionChanged() ) ); - connect( _iconview, SIGNAL( selectionChanged( QIconViewItem * ) ), this, SLOT( selectionChanged( QIconViewItem * ) ) ); - connect( _iconview, SIGNAL( currentChanged( QIconViewItem * ) ), this, SLOT( currentChanged( QIconViewItem * ) ) ); - connect( _iconview, SIGNAL( clicked( QIconViewItem * ) ), this, SLOT( clicked( QIconViewItem * ) ) ); - connect( _iconview, SIGNAL( pressed( QIconViewItem * ) ), this, SLOT( pressed( QIconViewItem * ) ) ); + connect( _iconview, SIGNAL( selectionChanged(QIconViewItem*) ), this, SLOT( selectionChanged(QIconViewItem*) ) ); + connect( _iconview, SIGNAL( currentChanged(QIconViewItem*) ), this, SLOT( currentChanged(QIconViewItem*) ) ); + connect( _iconview, SIGNAL( clicked(QIconViewItem*) ), this, SLOT( clicked(QIconViewItem*) ) ); + connect( _iconview, SIGNAL( pressed(QIconViewItem*) ), this, SLOT( pressed(QIconViewItem*) ) ); - connect( _iconview, SIGNAL( doubleClicked( QIconViewItem * ) ), this, SLOT( doubleClicked( QIconViewItem * ) ) ); - connect( _iconview, SIGNAL( returnPressed( QIconViewItem * ) ), this, SLOT( returnPressed( QIconViewItem * ) ) ); + connect( _iconview, SIGNAL( doubleClicked(QIconViewItem*) ), this, SLOT( doubleClicked(QIconViewItem*) ) ); + connect( _iconview, SIGNAL( returnPressed(QIconViewItem*) ), this, SLOT( returnPressed(QIconViewItem*) ) ); - connect( _iconview, SIGNAL( onItem( QIconViewItem * ) ), this, SLOT( onItem( QIconViewItem * ) ) ); + connect( _iconview, SIGNAL( onItem(QIconViewItem*) ), this, SLOT( onItem(QIconViewItem*) ) ); connect( _iconview, SIGNAL( onViewport() ), this, SIGNAL( onViewport() ) ); // listview only signals - connect( _listview, SIGNAL( expanded( QListViewItem * ) ), this, SLOT( expanded( QListViewItem * ) ) ); - connect( _listview, SIGNAL( collapsed( QListViewItem * ) ), this, SLOT( collapsed( QListViewItem * ) ) ); + connect( _listview, SIGNAL( expanded(QListViewItem*) ), this, SLOT( expanded(QListViewItem*) ) ); + connect( _listview, SIGNAL( collapsed(QListViewItem*) ), this, SLOT( collapsed(QListViewItem*) ) ); // iconview only signals connect( _iconview, SIGNAL( moved() ), this, SIGNAL( moved() ) ); } OVersatileView::~OVersatileView() { } QPopupMenu* OVersatileView::contextMenu() const { return _contextmenu; } void OVersatileView::contextMenuRequested( QListViewItem* item, const QPoint& pos, int col ) { // can't use QObject::inherits here, because ListViewItems, beit Q, O or K, // do not inherit from QObject - assuming here the programmer is // disciplined enough to only add OVersatileViewItems to an OVersatileView popupContextMenu( static_cast<OVersatileViewItem*>( item ), pos, col ); } void OVersatileView::contextMenuRequested( QIconViewItem* item, const QPoint& pos ) { // see above popupContextMenu( static_cast<OVersatileViewItem*>( item ), pos, -1 ); } void OVersatileView::popupContextMenu( OVersatileViewItem* item, const QPoint& pos, int col ) { if ( !item ) _contextmenu->exec( pos ); else emit( contextMenuRequested( item, pos, col ) ); } void OVersatileView::setSynchronization( bool sync ) { _synchronization = sync; } bool OVersatileView::synchronization() { return _synchronization; } void OVersatileView::setDefaultPixmaps( int mode, QPixmap& leaf, QPixmap& opened, QPixmap& closed ) { if ( mode == Tree ) { _treeleaf = leaf; _treeopened = opened; _treeclosed = closed; } else if ( mode == Icons ) { _iconleaf = leaf; _iconopened = opened; _iconclosed = closed; } else { odebug << "OVersatileView::setDefaultPixmaps(): invalid mode" << oendl; } } QIconView* OVersatileView::iconView() const { return _iconview; } OListView* OVersatileView::listView() const { return _listview; } void OVersatileView::setViewMode( int mode ) { if ( mode == Tree ) { _viewmode = mode; raiseWidget( _listview ); } else if ( mode == Icons ) { _viewmode = mode; raiseWidget( _iconview ); } else { odebug << "OVersatileView::setViewMode(): invalid mode" << oendl; } } void OVersatileView::setIconViewMode() { setViewMode( Icons ); } void OVersatileView::setTreeViewMode() { setViewMode( Tree ); } bool OVersatileView::isValidViewMode( int mode ) const { switch ( _warningpolicy ) { case OVersatileView::None: { return true; } case OVersatileView::Warn: { if ( _viewmode != mode ) { odebug << "OVersatileView::isValidViewMode(): Requested operation not valid in current mode." << oendl; return true; } } case OVersatileView::WarnReturn: { if ( _viewmode != mode ) { odebug << "OVersatileView::isValidViewMode(): Requested operation not valid in current mode." << oendl; return false; } } default: { owarn << "OVersatileView::isValidViewMode(): Inconsistent object state!" << oendl; return true; } } } void OVersatileView::setWarningPolicy( int policy ) const { _warningpolicy = policy; } bool OVersatileView::warningPolicy() const { return _warningpolicy; } //==============================================================================================// // Stupid Signal forwarders... // Folks, this is why I like python with its dynamic typing: // I can code the following dozens of lines C++ in four Python lines... //==============================================================================================// void OVersatileView::selectionChanged( QListViewItem * item ) { emit( selectionChanged( static_cast<OVersatileViewItem*>( item ) ) ); } void OVersatileView::selectionChanged( QIconViewItem * item ) { emit( selectionChanged( static_cast<OVersatileViewItem*>( item ) ) ); } void OVersatileView::currentChanged( QListViewItem * item ) { emit( currentChanged( static_cast<OVersatileViewItem*>( item ) ) ); } void OVersatileView::currentChanged( QIconViewItem * item ) { emit( currentChanged( static_cast<OVersatileViewItem*>( item ) ) ); } void OVersatileView::clicked( QListViewItem * item ) { emit( clicked( static_cast<OVersatileViewItem*>( item ) ) ); } void OVersatileView::clicked( QIconViewItem * item ) { emit( clicked( static_cast<OVersatileViewItem*>( item ) ) ); } void OVersatileView::pressed( QListViewItem * item ) { emit( pressed( static_cast<OVersatileViewItem*>( item ) ) ); } void OVersatileView::pressed( QIconViewItem * item ) { emit( pressed( static_cast<OVersatileViewItem*>( item ) ) ); } void OVersatileView::doubleClicked( QListViewItem * item ) { |