-rw-r--r-- | libopie/colordialog.cpp | 2 | ||||
-rw-r--r-- | libopie/colorpopupmenu.cpp | 1 | ||||
-rw-r--r-- | libopie/ocheckitem.cpp | 1 | ||||
-rw-r--r-- | libopie/ocolorbutton.cpp | 3 | ||||
-rw-r--r-- | libopie/odevice.cpp | 1 | ||||
-rw-r--r-- | libopie/odevicebutton.cpp | 2 | ||||
-rw-r--r-- | libopie/ofiledialog.cc | 3 | ||||
-rw-r--r-- | libopie/ofileselector.cpp | 5 | ||||
-rw-r--r-- | libopie/ofontselector.cpp | 1 | ||||
-rw-r--r-- | libopie/oprocctrl.cpp | 1 | ||||
-rw-r--r-- | libopie/oprocess.cpp | 1 | ||||
-rw-r--r-- | libopie/orecurrancewidget.cpp | 2 | ||||
-rw-r--r-- | libopie/oticker.cpp | 9 | ||||
-rw-r--r-- | libopie/otimepicker.cpp | 3 | ||||
-rw-r--r-- | libopie/owait.cpp | 2 | ||||
-rw-r--r-- | libopie/pim/ocontactaccessbackend_xml.cpp | 5 | ||||
-rw-r--r-- | libopie/pim/otodo.cpp | 3 |
17 files changed, 4 insertions, 41 deletions
diff --git a/libopie/colordialog.cpp b/libopie/colordialog.cpp index c7421ec..d46da41 100644 --- a/libopie/colordialog.cpp +++ b/libopie/colordialog.cpp @@ -1,435 +1,433 @@ /**************************************************************************** ** $Id$ ** ** Implementation of OColorDialog class ** ** Created : 990222 ** ** Copyright (C) 1999-2000 Trolltech AS. All rights reserved. ** ** This file is part of the dialogs module of the Qt GUI Toolkit. ** ** This file may be distributed under the terms of the Q Public License ** as defined by Trolltech AS of Norway and appearing in the file ** LICENSE.QPL included in the packaging of this file. ** ** 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. ** ** Licensees holding valid Qt Enterprise Edition or Qt Professional Edition ** licenses may use this file in accordance with the Qt Commercial License ** Agreement provided with the Software. ** ** 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/pricing.html or email sales@trolltech.com for ** information about Qt Commercial License Agreements. ** See http://www.trolltech.com/qpl/ for QPL licensing information. ** 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 "colordialog.h" #include "qpainter.h" #include "qlayout.h" #include "qlabel.h" #include "qpushbutton.h" #include "qlineedit.h" #include "qimage.h" #include "qpixmap.h" #include "qdrawutil.h" #include "qvalidator.h" -#include "qdragobject.h" #include "qapplication.h" -#include "qdragobject.h" static inline void rgb2hsv( QRgb rgb, int&h, int&s, int&v ) { QColor c; c.setRgb( rgb ); c.getHsv(h,s,v); } /* * avoid clashes with the original Qt */ namespace { class QColorPicker : public QFrame { Q_OBJECT public: QColorPicker(QWidget* parent=0, const char* name=0); ~QColorPicker(); public slots: void setCol( int h, int s ); signals: void newCol( int h, int s ); protected: QSize sizeHint() const; QSizePolicy sizePolicy() const; void drawContents(QPainter* p); void mouseMoveEvent( QMouseEvent * ); void mousePressEvent( QMouseEvent * ); private: int hue; int sat; QPoint colPt(); int huePt( const QPoint &pt ); int satPt( const QPoint &pt ); void setCol( const QPoint &pt ); QPixmap *pix; }; static int pWidth = 200; static int pHeight = 200; class QColorLuminancePicker : public QWidget { Q_OBJECT public: QColorLuminancePicker(QWidget* parent=0, const char* name=0); ~QColorLuminancePicker(); public slots: void setCol( int h, int s, int v ); void setCol( int h, int s ); signals: void newHsv( int h, int s, int v ); protected: // QSize sizeHint() const; // QSizePolicy sizePolicy() const; void paintEvent( QPaintEvent*); void mouseMoveEvent( QMouseEvent * ); void mousePressEvent( QMouseEvent * ); private: enum { foff = 3, coff = 4 }; //frame and contents offset int val; int hue; int sat; int y2val( int y ); int val2y( int val ); void setVal( int v ); QPixmap *pix; }; int QColorLuminancePicker::y2val( int y ) { int d = height() - 2*coff - 1; return 255 - (y - coff)*255/d; } int QColorLuminancePicker::val2y( int v ) { int d = height() - 2*coff - 1; return coff + (255-v)*d/255; } QColorLuminancePicker::QColorLuminancePicker(QWidget* parent, const char* name) :QWidget( parent, name ) { hue = 100; val = 100; sat = 100; pix = 0; // setBackgroundMode( NoBackground ); } QColorLuminancePicker::~QColorLuminancePicker() { delete pix; } void QColorLuminancePicker::mouseMoveEvent( QMouseEvent *m ) { setVal( y2val(m->y()) ); } void QColorLuminancePicker::mousePressEvent( QMouseEvent *m ) { setVal( y2val(m->y()) ); } void QColorLuminancePicker::setVal( int v ) { if ( val == v ) return; val = QMAX( 0, QMIN(v,255)); delete pix; pix=0; repaint( FALSE ); //### emit newHsv( hue, sat, val ); } //receives from a hue,sat chooser and relays. void QColorLuminancePicker::setCol( int h, int s ) { setCol( h, s, val ); emit newHsv( h, s, val ); } void QColorLuminancePicker::paintEvent( QPaintEvent * ) { int w = width() - 5; QRect r( 0, foff, w, height() - 2*foff ); int wi = r.width() - 2; int hi = r.height() - 2; if ( !pix || pix->height() != hi || pix->width() != wi ) { delete pix; QImage img( wi, hi, 32 ); int y; for ( y = 0; y < hi; y++ ) { QColor c( hue, sat, y2val(y+coff), QColor::Hsv ); QRgb r = c.rgb(); int x; for ( x = 0; x < wi; x++ ) img.setPixel( x, y, r ); } pix = new QPixmap; pix->convertFromImage(img); } QPainter p(this); p.drawPixmap( 1, coff, *pix ); QColorGroup g = colorGroup(); qDrawShadePanel( &p, r, g, TRUE ); p.setPen( g.foreground() ); p.setBrush( g.foreground() ); QPointArray a; int y = val2y(val); a.setPoints( 3, w, y, w+5, y+5, w+5, y-5 ); erase( w, 0, 5, height() ); p.drawPolygon( a ); } void QColorLuminancePicker::setCol( int h, int s , int v ) { val = v; hue = h; sat = s; delete pix; pix=0; repaint( FALSE );//#### } QPoint QColorPicker::colPt() { return QPoint( (360-hue)*(pWidth-1)/360, (255-sat)*(pHeight-1)/255 ); } int QColorPicker::huePt( const QPoint &pt ) { return 360 - pt.x()*360/(pWidth-1); } int QColorPicker::satPt( const QPoint &pt ) { return 255 - pt.y()*255/(pHeight-1) ; } void QColorPicker::setCol( const QPoint &pt ) { setCol( huePt(pt), satPt(pt) ); } QColorPicker::QColorPicker(QWidget* parent, const char* name ) : QFrame( parent, name ) { hue = 0; sat = 0; setCol( 150, 255 ); QImage img( pWidth, pHeight, 32 ); int x,y; for ( y = 0; y < pHeight; y++ ) for ( x = 0; x < pWidth; x++ ) { QPoint p( x, y ); img.setPixel( x, y, QColor(huePt(p), satPt(p), 200, QColor::Hsv).rgb() ); } pix = new QPixmap; pix->convertFromImage(img); setBackgroundMode( NoBackground ); } QColorPicker::~QColorPicker() { delete pix; } QSize QColorPicker::sizeHint() const { return QSize( pWidth + 2*frameWidth(), pHeight + 2*frameWidth() ); } QSizePolicy QColorPicker::sizePolicy() const { return QSizePolicy( QSizePolicy::Fixed, QSizePolicy::Fixed ); } void QColorPicker::setCol( int h, int s ) { int nhue = QMIN( QMAX(0,h), 360 ); int nsat = QMIN( QMAX(0,s), 255); if ( nhue == hue && nsat == sat ) return; QRect r( colPt(), QSize(20,20) ); hue = nhue; sat = nsat; r = r.unite( QRect( colPt(), QSize(20,20) ) ); r.moveBy( contentsRect().x()-9, contentsRect().y()-9 ); // update( r ); repaint( r, FALSE ); } 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; }; diff --git a/libopie/colorpopupmenu.cpp b/libopie/colorpopupmenu.cpp index 5a8d77e..0d66fba 100644 --- a/libopie/colorpopupmenu.cpp +++ b/libopie/colorpopupmenu.cpp @@ -1,173 +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 <qaction.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& ) ) ); 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/ocheckitem.cpp b/libopie/ocheckitem.cpp index 082d7a2..cd763c1 100644 --- a/libopie/ocheckitem.cpp +++ b/libopie/ocheckitem.cpp @@ -1,106 +1,105 @@ /********************************************************************** ** Copyright (C) 2002 Stefan Eilers (se, eilers.stefan@epost.de ** ** This file may be distributed and/or modified under the terms of the ** GNU Library 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 <qpainter.h> #include "ocheckitem.h" /** * Constructs an CheckItem with a QTable as parent * and a sort key for. * The sort key will be used by QTable to sort the table later * @param t The parent QTable where the check item belongs * @param key A sort key */ OCheckItem::OCheckItem( QTable *t, const QString &key ) : QTableItem( t, Never, "" ), m_checked( FALSE ), m_sortKey( key ) { } /** * reimplemted for internal reasons * @return Returns the sort key of the Item * @see QTableItem */ QString OCheckItem::key() const { return m_sortKey; } /** * This method can check or uncheck the item. It will * call QTable to update the cell. * * @param b Whether to check or uncheck the item */ void OCheckItem::setChecked( bool b ) { m_checked = b; table()->updateCell( row(), col() ); } /** * This will toggle the item. If it is checked it'll get * unchecked by this method or vice versa. */ void OCheckItem::toggle() { m_checked = !m_checked; } /** * This will return the state of the item. * * @return Returns true if the item is checked */ bool OCheckItem::isChecked() const { return m_checked; } /** * @internal * This paints the item */ void OCheckItem::paint( QPainter *p, const QColorGroup &cg, const QRect &cr, bool ) { p->fillRect( 0, 0, cr.width(), cr.height(), cg.brush( QColorGroup::Base ) ); int marg = ( cr.width() - BoxSize ) / 2; int x = 0; int y = ( cr.height() - BoxSize ) / 2; p->setPen( QPen( cg.text() ) ); p->drawRect( x + marg, y, BoxSize, BoxSize ); p->drawRect( x + marg+1, y+1, BoxSize-2, BoxSize-2 ); p->setPen( darkGreen ); x += 1; y += 1; if ( m_checked ) { QPointArray a( 7*2 ); int i, xx, yy; xx = x+1+marg; yy = y+2; for ( i=0; i<3; i++ ) { a.setPoint( 2*i, xx, yy ); a.setPoint( 2*i+1, xx, yy+2 ); xx++; yy++; } yy -= 2; for ( i=3; i<7; i++ ) { a.setPoint( 2*i, xx, yy ); a.setPoint( 2*i+1, xx, yy+2 ); xx++; yy--; } p->drawLineSegments( a ); } } diff --git a/libopie/ocolorbutton.cpp b/libopie/ocolorbutton.cpp index 113a77a..93fe5d0 100644 --- a/libopie/ocolorbutton.cpp +++ b/libopie/ocolorbutton.cpp @@ -1,142 +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 <qcolor.h> -#include <qpixmap.h> -#include <qimage.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 & ))); 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 c5342e1..c0b6efa 100644 --- a/libopie/odevice.cpp +++ b/libopie/odevice.cpp @@ -1,415 +1,414 @@ /* This file is part of the OPIE libraries Copyright (C) 2002 Robert Griebl (sandman@handhelds.org) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include <stdlib.h> #include <unistd.h> #include <fcntl.h> #include <sys/ioctl.h> #include <signal.h> #include <sys/time.h> #ifndef QT_NO_SOUND #include <linux/soundcard.h> #endif #include <math.h> -#include <qapplication.h> #include <qfile.h> #include <qtextstream.h> #include <qpe/sound.h> #include <qpe/resource.h> #include <qpe/config.h> #include <qpe/qcopenvelope_qws.h> #include "odevice.h" #include <qwindowsystem_qws.h> #ifndef ARRAY_SIZE #define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0])) #endif // _IO and friends are only defined in kernel headers ... #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)) using namespace Opie; class ODeviceData { public: QString m_vendorstr; OVendor m_vendor; QString m_modelstr; OModel m_model; QString m_systemstr; OSystem m_system; QString m_sysverstr; Transformation m_rotation; ODirection m_direction; QValueList <ODeviceButton> *m_buttons; uint m_holdtime; QStrList *m_cpu_frequencies; }; class iPAQ : public ODevice, public QWSServer::KeyboardFilter { protected: virtual void init ( ); virtual void initButtons ( ); public: virtual bool setSoftSuspend ( bool soft ); virtual bool setDisplayBrightness ( int b ); virtual int displayBrightnessResolution ( ) const; virtual void alarmSound ( ); virtual QValueList <OLed> ledList ( ) const; virtual QValueList <OLedState> ledStateList ( OLed led ) const; virtual OLedState ledState ( OLed led ) const; virtual bool setLedState ( OLed led, OLedState st ); virtual bool hasLightSensor ( ) const; virtual int readLightSensor ( ); virtual int lightSensorResolution ( ) const; protected: virtual bool filter ( int unicode, int keycode, int modifiers, bool isPress, bool autoRepeat ); virtual void timerEvent ( QTimerEvent *te ); int m_power_timer; OLedState m_leds [2]; }; class Jornada : public ODevice { protected: virtual void init ( ); //virtual void initButtons ( ); public: virtual bool setSoftSuspend ( bool soft ); virtual bool setDisplayBrightness ( int b ); virtual int displayBrightnessResolution ( ) const; static bool isJornada(); }; class Zaurus : public ODevice { protected: virtual void init ( ); virtual void initButtons ( ); public: virtual bool setSoftSuspend ( bool soft ); virtual bool setDisplayBrightness ( int b ); virtual int displayBrightnessResolution ( ) const; virtual void alarmSound ( ); virtual void keySound ( ); virtual void touchSound ( ); virtual QValueList <OLed> ledList ( ) const; virtual QValueList <OLedState> ledStateList ( OLed led ) const; virtual OLedState ledState ( OLed led ) const; virtual bool setLedState ( OLed led, OLedState st ); bool hasHingeSensor() const; OHingeStatus readHingeSensor(); static bool isZaurus(); // Does this break BC? virtual bool suspend ( ); Transformation rotation ( ) const; ODirection direction ( ) const; protected: virtual void buzzer ( int snd ); OLedState m_leds [1]; bool m_embedix; void virtual_hook( int id, void *data ); }; class SIMpad : public ODevice, public QWSServer::KeyboardFilter { protected: virtual void init ( ); virtual void initButtons ( ); public: virtual bool setSoftSuspend ( bool soft ); virtual bool suspend(); virtual bool setDisplayStatus( bool on ); virtual bool setDisplayBrightness ( int b ); virtual int displayBrightnessResolution ( ) const; virtual void alarmSound ( ); virtual QValueList <OLed> ledList ( ) const; virtual QValueList <OLedState> ledStateList ( OLed led ) const; virtual OLedState ledState ( OLed led ) const; virtual bool setLedState ( OLed led, OLedState st ); protected: virtual bool filter ( int unicode, int keycode, int modifiers, bool isPress, bool autoRepeat ); virtual void timerEvent ( QTimerEvent *te ); int m_power_timer; OLedState m_leds [1]; //FIXME check if really only one }; class Ramses : public ODevice, public QWSServer::KeyboardFilter { protected: virtual void init ( ); public: virtual bool setSoftSuspend ( bool soft ); virtual bool suspend ( ); virtual bool setDisplayStatus( bool on ); virtual bool setDisplayBrightness ( int b ); virtual int displayBrightnessResolution ( ) const; virtual bool setDisplayContrast ( int b ); virtual int displayContrastResolution ( ) const; protected: virtual bool filter ( int unicode, int keycode, int modifiers, bool isPress, bool autoRepeat ); virtual void timerEvent ( QTimerEvent *te ); int m_power_timer; }; struct i_button { uint model; Qt::Key code; char *utext; char *pix; char *fpressedservice; char *fpressedaction; char *fheldservice; char *fheldaction; } 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()" }, }; struct z_button { Qt::Key code; char *utext; char *pix; char *fpressedservice; char *fpressedaction; char *fheldservice; char *fheldaction; } z_buttons [] = { { 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_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()" }, }; struct s_button { uint model; Qt::Key code; char *utext; char *pix; char *fpressedservice; char *fpressedaction; char *fheldservice; char *fheldaction; } 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()" }, */ }; 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; diff --git a/libopie/odevicebutton.cpp b/libopie/odevicebutton.cpp index 314eb51..647ac4b 100644 --- a/libopie/odevicebutton.cpp +++ b/libopie/odevicebutton.cpp @@ -1,239 +1,237 @@ /********************************************************************** ** 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 <qpixmap.h> -#include <qstring.h> #include <qpe/qcopenvelope_qws.h> #include <opie/odevicebutton.h> using namespace Opie; class OQCopMessageData { public: QCString m_channel; QCString m_message; QByteArray m_data; }; OQCopMessage::OQCopMessage ( ) : d ( 0 ) { init ( QCString ( ), QCString ( ), QByteArray ( )); } OQCopMessage::OQCopMessage ( const OQCopMessage © ) : d ( 0 ) { init ( copy. channel ( ), copy. message ( ), copy. data ( )); } OQCopMessage &OQCopMessage::operator = ( const OQCopMessage &assign ) { init ( assign. channel ( ), assign. message ( ), assign. data ( )); return *this; } OQCopMessage::OQCopMessage ( const QCString &ch, const QCString &m, const QByteArray &arg ) : d ( 0 ) { init ( ch, m, arg ); } void OQCopMessage::init ( const QCString &ch, const QCString &m, const QByteArray &arg ) { if ( !d ) d = new OQCopMessageData ( ); d-> m_channel = ch; d-> m_message = m; d-> m_data = arg; } bool OQCopMessage::send ( ) { if ( d-> m_channel. isEmpty ( ) || d-> m_message. isEmpty ( ) ) return false; QCopEnvelope e ( d-> m_channel, d-> m_message ); if ( d-> m_data. size ( )) e. writeRawBytes ( d-> m_data. data ( ), d-> m_data. size ( )); return true; } QCString OQCopMessage::channel ( ) const { return d-> m_channel; } QCString OQCopMessage::message ( ) const { return d-> m_message; } QByteArray OQCopMessage::data ( ) const { return d-> m_data; } bool OQCopMessage::isNull() const { return d-> m_message.isNull() || d-> m_channel.isNull(); } void OQCopMessage::setChannel ( const QCString &ch ) { d-> m_channel = ch; } void OQCopMessage::setMessage ( const QCString &m ) { d-> m_message = m; } void OQCopMessage::setData ( const QByteArray &data ) { d-> m_data = data; } /*! \class Opie::ODeviceButton \brief The Opie::ODeviceButton class represents a physical user mappable button on a Qtopia device. This class represents a physical button on a Qtopia device. A device may have "user programmable" buttons. The location and number of buttons will vary from device to device. userText() and pixmap() may be used to describe this button to the user in help documentation. \ingroup qtopiaemb \internal */ ODeviceButton::ODeviceButton() { } ODeviceButton::~ODeviceButton() { } /*! Returns the button's keycode. */ ushort ODeviceButton::keycode() const { return m_Keycode; } /*! This function returns a human readable, translated description of the button. */ QString ODeviceButton::userText() const { return m_UserText; } /*! This function returns the pixmap for this button. If there isn't one it will return an empty (null) pixmap. */ QPixmap ODeviceButton::pixmap() const { return m_Pixmap; } /*! This function returns the factory preset (default) action for when this button is pressed. The return value is a legal QCop message. */ OQCopMessage ODeviceButton::factoryPresetPressedAction() const { return m_FactoryPresetPressedAction; } /*! This function returns the user assigned action for when this button is pressed. If no action is assigned, factoryPresetAction() is returned. */ OQCopMessage ODeviceButton::pressedAction() const { if (m_PressedAction.channel().isEmpty()) return factoryPresetPressedAction(); return m_PressedAction; } /*! This function returns the factory preset (default) action for when this button is pressed and held. The return value is a legal QCop message. */ OQCopMessage ODeviceButton::factoryPresetHeldAction() const { return m_FactoryPresetHeldAction; } /*! This function returns the user assigned action for when this button is pressed and held. If no action is assigned, factoryPresetAction() is returned. */ OQCopMessage ODeviceButton::heldAction() const { if (m_HeldAction.channel().isEmpty()) return factoryPresetHeldAction(); return m_HeldAction; } void ODeviceButton::setKeycode(ushort keycode) { m_Keycode = keycode; } void ODeviceButton::setUserText(const QString& text) { m_UserText = text; } void ODeviceButton::setPixmap(const QPixmap& picture) { m_Pixmap = picture; } void ODeviceButton::setFactoryPresetPressedAction(const OQCopMessage& action) { m_FactoryPresetPressedAction = action; } void ODeviceButton::setPressedAction(const OQCopMessage& action) { m_PressedAction = action; } void ODeviceButton::setFactoryPresetHeldAction(const OQCopMessage& action) { m_FactoryPresetHeldAction = action; } void ODeviceButton::setHeldAction(const OQCopMessage& action) { m_HeldAction = action; } diff --git a/libopie/ofiledialog.cc b/libopie/ofiledialog.cc index 5511b24..47306b6 100644 --- a/libopie/ofiledialog.cc +++ b/libopie/ofiledialog.cc @@ -1,215 +1,212 @@ /* =. This file is part of the OPIE Project .=l. Copyright (c) 2002,2003 <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. */ -#include <qpe/applnk.h> #include <qpe/config.h> #include <qpe/qpeapplication.h> #include <qfileinfo.h> -#include <qstring.h> -#include <qapplication.h> #include <qlayout.h> #include "ofiledialog.h" 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 &) ) ); #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/libopie/ofileselector.cpp b/libopie/ofileselector.cpp index 9ac2981..1ba94ae 100644 --- a/libopie/ofileselector.cpp +++ b/libopie/ofileselector.cpp @@ -1,396 +1,391 @@ #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> /* 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& ) ), 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& ) ) ); } 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 ) ), diff --git a/libopie/ofontselector.cpp b/libopie/ofontselector.cpp index c8471cc..7e07008 100644 --- a/libopie/ofontselector.cpp +++ b/libopie/ofontselector.cpp @@ -1,412 +1,411 @@ /* =. 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 <qfont.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 ) ) ); 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 ) ) ); 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 ) ) ); 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 ) i = findItemCB ( d-> m_font_style_list, "Regular" ); if (( i < 0 ) && ( d-> m_font_style_list-> count ( ) > 0 )) i = 0; if ( i >= 0 ) { d-> m_font_style_list-> setCurrentItem ( i ); fontStyleClicked ( i ); } d-> m_font_size_list-> clear ( ); QValueList<int> sl = fli-> sizes ( ); for ( QValueList<int>::Iterator it = sl. begin ( ); it != sl. end ( ); ++it ) d-> m_font_size_list-> insertItem ( QString::number ( *it )); i = findItemCB ( d-> m_font_size_list, oldsize ); if ( i < 0 ) i = findItemCB ( d-> m_font_size_list, "10" ); if (( i < 0 ) && ( d-> m_font_size_list-> count ( ) > 0 )) i = 0; if ( i >= 0 ) { d-> m_font_size_list-> setCurrentItem ( i ); fontSizeClicked ( i ); } changeFont ( ); } void OFontSelector::fontStyleClicked ( int /*index*/ ) { changeFont ( ); } void OFontSelector::fontSizeClicked ( int /*index*/ ) { changeFont ( ); } void OFontSelector::changeFont ( ) { QFont f = selectedFont ( ); if ( d-> m_preview ) d-> m_preview-> setFont ( f ); emit fontSelected ( f ); } /** * Return the selected font */ QFont OFontSelector::selectedFont ( ) { 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 ) { return d-> m_fdb. font ( fli-> family ( ), \ fst >= 0 ? fli-> styles ( ) [fst] : QString::null, \ fsi >= 0 ? fli-> sizes ( ) [fsi] : 10, \ d-> m_fdb. charSets ( fli-> family ( )) [0] ); } else return QFont ( ); } void OFontSelector::resizeEvent ( QResizeEvent *re ) { if ( d-> m_preview ) { d-> m_preview-> setMinimumHeight ( 1 ); d-> m_preview-> setMaximumHeight ( 32767 ); } QWidget::resizeEvent ( re ); if ( d-> m_preview ) d-> m_preview-> setFixedHeight ( d-> m_preview-> height ( )); } diff --git a/libopie/oprocctrl.cpp b/libopie/oprocctrl.cpp index e7db622..df8da1e 100644 --- a/libopie/oprocctrl.cpp +++ b/libopie/oprocctrl.cpp @@ -1,268 +1,267 @@ /* This file is part of the KDE libraries Copyright (C) 1997 Christian Czezakte (e9025461@student.tuwien.ac.at) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ // // KPROCESSCONTROLLER -- A helper class for KProcess // // version 0.3.1, Jan, 8th 1997 // // (C) Christian Czezatke // e9025461@student.tuwien.ac.at // Ported by Holger Freyther // //#include <config.h> #include <sys/types.h> #include <sys/socket.h> #include <errno.h> #include <fcntl.h> #include <stdio.h> #include <string.h> #include <unistd.h> #include <assert.h> #include <qsocketnotifier.h> -#include "oprocess.h" #include "oprocctrl.h" OProcessController *OProcessController::theOProcessController = 0; struct sigaction OProcessController::oldChildHandlerData; bool OProcessController::handlerSet = false; OProcessController::OProcessController() { assert( theOProcessController == 0 ); if (0 > pipe(fd)) printf(strerror(errno)); notifier = new QSocketNotifier(fd[0], QSocketNotifier::Read); notifier->setEnabled(true); QObject::connect(notifier, SIGNAL(activated(int)), this, SLOT(slotDoHousekeeping(int))); connect( &delayedChildrenCleanupTimer, SIGNAL( timeout()), SLOT( delayedChildrenCleanup())); theOProcessController = this; setupHandlers(); } void OProcessController::setupHandlers() { if( handlerSet ) return; struct sigaction act; act.sa_handler=theSigCHLDHandler; sigemptyset(&(act.sa_mask)); sigaddset(&(act.sa_mask), SIGCHLD); // Make sure we don't block this signal. gdb tends to do that :-( sigprocmask(SIG_UNBLOCK, &(act.sa_mask), 0); act.sa_flags = SA_NOCLDSTOP; // CC: take care of SunOS which automatically restarts interrupted system // calls (and thus does not have SA_RESTART) #ifdef SA_RESTART act.sa_flags |= SA_RESTART; #endif sigaction( SIGCHLD, &act, &oldChildHandlerData ); act.sa_handler=SIG_IGN; sigemptyset(&(act.sa_mask)); sigaddset(&(act.sa_mask), SIGPIPE); act.sa_flags = 0; sigaction( SIGPIPE, &act, 0L); handlerSet = true; } void OProcessController::resetHandlers() { if( !handlerSet ) return; sigaction( SIGCHLD, &oldChildHandlerData, 0 ); // there should be no problem with SIGPIPE staying SIG_IGN handlerSet = false; } // block SIGCHLD handler, because it accesses processList void OProcessController::addOProcess( OProcess* p ) { sigset_t newset, oldset; sigemptyset( &newset ); sigaddset( &newset, SIGCHLD ); sigprocmask( SIG_BLOCK, &newset, &oldset ); processList.append( p ); sigprocmask( SIG_SETMASK, &oldset, 0 ); } void OProcessController::removeOProcess( OProcess* p ) { sigset_t newset, oldset; sigemptyset( &newset ); sigaddset( &newset, SIGCHLD ); sigprocmask( SIG_BLOCK, &newset, &oldset ); processList.remove( p ); sigprocmask( SIG_SETMASK, &oldset, 0 ); } //using a struct which contains both the pid and the status makes it easier to write //and read the data into the pipe //especially this solves a problem which appeared on my box where slotDoHouseKeeping() received //only 4 bytes (with some debug output around the write()'s it received all 8 bytes) //don't know why this happened, but when writing all 8 bytes at once it works here, aleXXX struct waitdata { pid_t pid; int status; }; void OProcessController::theSigCHLDHandler(int arg) { struct waitdata wd; // int status; // pid_t this_pid; int saved_errno; saved_errno = errno; // since waitpid and write change errno, we have to save it and restore it // (Richard Stevens, Advanced programming in the Unix Environment) bool found = false; if( theOProcessController != 0 ) { // iterating the list doesn't perform any system call for( QValueList<OProcess*>::ConstIterator it = theOProcessController->processList.begin(); it != theOProcessController->processList.end(); ++it ) { if( !(*it)->isRunning()) continue; wd.pid = waitpid( (*it)->pid(), &wd.status, WNOHANG ); if ( wd.pid > 0 ) { ::write(theOProcessController->fd[1], &wd, sizeof(wd)); found = true; } } } if( !found && oldChildHandlerData.sa_handler != SIG_IGN && oldChildHandlerData.sa_handler != SIG_DFL ) oldChildHandlerData.sa_handler( arg ); // call the old handler // handle the rest if( theOProcessController != 0 ) { static const struct waitdata dwd = { 0, 0 }; // delayed waitpid() ::write(theOProcessController->fd[1], &dwd, sizeof(dwd)); } else { int dummy; while( waitpid( -1, &dummy, WNOHANG ) > 0 ) ; } errno = saved_errno; } void OProcessController::slotDoHousekeeping(int ) { unsigned int bytes_read = 0; unsigned int errcnt=0; // read pid and status from the pipe. struct waitdata wd; while ((bytes_read < sizeof(wd)) && (errcnt < 50)) { int r = ::read(fd[0], ((char *)&wd) + bytes_read, sizeof(wd) - bytes_read); if (r > 0) bytes_read += r; else if (r < 0) errcnt++; } if (errcnt >= 50) { fprintf(stderr, "Error: Max. error count for pipe read " "exceeded in OProcessController::slotDoHousekeeping\n"); return; // it makes no sense to continue here! } if (bytes_read != sizeof(wd)) { fprintf(stderr, "Error: Could not read info from signal handler %d <> %d!\n", bytes_read, sizeof(wd)); return; // it makes no sense to continue here! } if (wd.pid==0) { // special case, see delayedChildrenCleanup() delayedChildrenCleanupTimer.start( 1000, true ); return; } for( QValueList<OProcess*>::ConstIterator it = processList.begin(); it != processList.end(); ++it ) { OProcess* proc = *it; if (proc->pid() == wd.pid) { // process has exited, so do emit the respective events if (proc->run_mode == OProcess::Block) { // If the reads are done blocking then set the status in proc // but do nothing else because OProcess will perform the other // actions of processHasExited. proc->status = wd.status; proc->runs = false; } else { proc->processHasExited(wd.status); } return; } } } // this is needed e.g. for popen(), which calls waitpid() checking // for its forked child, if we did waitpid() directly in the SIGCHLD // handler, popen()'s waitpid() call would fail void OProcessController::delayedChildrenCleanup() { struct waitdata wd; while(( wd.pid = waitpid( -1, &wd.status, WNOHANG ) ) > 0 ) { for( QValueList<OProcess*>::ConstIterator it = processList.begin(); it != processList.end(); ++it ) { if( !(*it)->isRunning() || (*it)->pid() != wd.pid ) continue; // it's OProcess, handle it ::write(fd[1], &wd, sizeof(wd)); break; } } } OProcessController::~OProcessController() { assert( theOProcessController == this ); resetHandlers(); notifier->setEnabled(false); close(fd[0]); close(fd[1]); delete notifier; theOProcessController = 0; } //#include "kprocctrl.moc" diff --git a/libopie/oprocess.cpp b/libopie/oprocess.cpp index 5db2b6c..c19881a 100644 --- a/libopie/oprocess.cpp +++ b/libopie/oprocess.cpp @@ -1,440 +1,439 @@ /* $Id$ This file is part of the KDE libraries Copyright (C) 1997 Christian Czezatke (e9025461@student.tuwien.ac.at) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ // // KPROCESS -- A class for handling child processes in KDE without // having to take care of Un*x specific implementation details // // version 0.3.1, Jan 8th 1998 // // (C) Christian Czezatke // e9025461@student.tuwien.ac.at // // Changes: // // March 2nd, 1998: Changed parameter list for KShellProcess: // Arguments are now placed in a single string so that // <shell> -c <commandstring> is passed to the shell // to make the use of "operator<<" consistent with KProcess // // // Ported by Holger Freyther // <zekce> Harlekin: oprocess and say it was ported to Qt by the Opie developers an Qt 2 #include "oprocess.h" #define _MAY_INCLUDE_KPROCESSCONTROLLER_ #include "oprocctrl.h" //#include <config.h> #include <qfile.h> #include <qsocketnotifier.h> -#include <qregexp.h> #include <sys/time.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/socket.h> #include <errno.h> #include <fcntl.h> #include <stdlib.h> #include <signal.h> #include <stdio.h> #include <string.h> #include <unistd.h> #ifdef HAVE_SYS_SELECT_H #include <sys/select.h> #endif #ifdef HAVE_INITGROUPS #include <grp.h> #endif #include <pwd.h> #include <qapplication.h> #include <qmap.h> //#include <kdebug.h> ///////////////////////////// // public member functions // ///////////////////////////// class OProcessPrivate { public: OProcessPrivate() : useShell(false) { } bool useShell; QMap<QString,QString> env; QString wd; QCString shell; }; OProcess::OProcess(QObject *parent, const char *name) : QObject(parent, name) { init ( ); } OProcess::OProcess(const QString &arg0, QObject *parent, const char *name) : QObject(parent, name) { init ( ); *this << arg0; } OProcess::OProcess(const QStringList &args, QObject *parent, const char *name) : QObject(parent, name) { init ( ); *this << args; } void OProcess::init ( ) { run_mode = NotifyOnExit; runs = false; pid_ = 0; status = 0; keepPrivs = false; innot = 0; outnot = 0; errnot = 0; communication = NoCommunication; input_data = 0; input_sent = 0; input_total = 0; d = 0; if (0 == OProcessController::theOProcessController) { (void) new OProcessController(); CHECK_PTR(OProcessController::theOProcessController); } OProcessController::theOProcessController->addOProcess(this); out[0] = out[1] = -1; in[0] = in[1] = -1; err[0] = err[1] = -1; } void OProcess::setEnvironment(const QString &name, const QString &value) { if (!d) d = new OProcessPrivate; d->env.insert(name, value); } void OProcess::setWorkingDirectory(const QString &dir) { if (!d) d = new OProcessPrivate; d->wd = dir; } void OProcess::setupEnvironment() { if (d) { QMap<QString,QString>::Iterator it; for(it = d->env.begin(); it != d->env.end(); ++it) setenv(QFile::encodeName(it.key()).data(), QFile::encodeName(it.data()).data(), 1); if (!d->wd.isEmpty()) chdir(QFile::encodeName(d->wd).data()); } } void OProcess::setRunPrivileged(bool keepPrivileges) { keepPrivs = keepPrivileges; } bool OProcess::runPrivileged() const { return keepPrivs; } OProcess::~OProcess() { // destroying the OProcess instance sends a SIGKILL to the // child process (if it is running) after removing it from the // list of valid processes (if the process is not started as // "DontCare") OProcessController::theOProcessController->removeOProcess(this); // this must happen before we kill the child // TODO: block the signal while removing the current process from the process list if (runs && (run_mode != DontCare)) kill(SIGKILL); // Clean up open fd's and socket notifiers. closeStdin(); closeStdout(); closeStderr(); // TODO: restore SIGCHLD and SIGPIPE handler if this is the last OProcess delete d; } void OProcess::detach() { OProcessController::theOProcessController->removeOProcess(this); runs = false; pid_ = 0; // Clean up open fd's and socket notifiers. closeStdin(); closeStdout(); closeStderr(); } bool OProcess::setExecutable(const QString& proc) { if (runs) return false; if (proc.isEmpty()) return false; if (!arguments.isEmpty()) arguments.remove(arguments.begin()); arguments.prepend(QFile::encodeName(proc)); return true; } OProcess &OProcess::operator<<(const QStringList& args) { QStringList::ConstIterator it = args.begin(); for ( ; it != args.end() ; ++it ) arguments.append(QFile::encodeName(*it)); return *this; } OProcess &OProcess::operator<<(const QCString& arg) { return operator<< (arg.data()); } OProcess &OProcess::operator<<(const char* arg) { arguments.append(arg); return *this; } OProcess &OProcess::operator<<(const QString& arg) { arguments.append(QFile::encodeName(arg)); return *this; } void OProcess::clearArguments() { arguments.clear(); } bool OProcess::start(RunMode runmode, Communication comm) { uint i; uint n = arguments.count(); char **arglist; if (runs || (0 == n)) { return false; // cannot start a process that is already running // or if no executable has been assigned } run_mode = runmode; status = 0; QCString shellCmd; if (d && d->useShell) { if (d->shell.isEmpty()) { qWarning( "Could not find a valid shell" ); return false; } arglist = static_cast<char **>(malloc( (4)*sizeof(char *))); for (i=0; i < n; i++) { shellCmd += arguments[i]; shellCmd += " "; // CC: to separate the arguments } arglist[0] = d->shell.data(); arglist[1] = (char *) "-c"; arglist[2] = shellCmd.data(); arglist[3] = 0; } else { arglist = static_cast<char **>(malloc( (n+1)*sizeof(char *))); for (i=0; i < n; i++) arglist[i] = arguments[i].data(); arglist[n]= 0; } if (!setupCommunication(comm)) qWarning( "Could not setup Communication!"); // We do this in the parent because if we do it in the child process // gdb gets confused when the application runs from gdb. uid_t uid = getuid(); gid_t gid = getgid(); #ifdef HAVE_INITGROUPS struct passwd *pw = getpwuid(uid); #endif int fd[2]; if (0 > pipe(fd)) { fd[0] = fd[1] = 0; // Pipe failed.. continue } runs = true; QApplication::flushX(); // WABA: Note that we use fork() and not vfork() because // vfork() has unclear semantics and is not standardized. pid_ = fork(); if (0 == pid_) { if (fd[0]) close(fd[0]); if (!runPrivileged()) { setgid(gid); #if defined( HAVE_INITGROUPS) if(pw) initgroups(pw->pw_name, pw->pw_gid); #endif setuid(uid); } // The child process if(!commSetupDoneC()) qWarning( "Could not finish comm setup in child!" ); setupEnvironment(); // Matthias if (run_mode == DontCare) setpgid(0,0); // restore default SIGPIPE handler (Harri) struct sigaction act; sigemptyset(&(act.sa_mask)); sigaddset(&(act.sa_mask), SIGPIPE); act.sa_handler = SIG_DFL; act.sa_flags = 0; sigaction(SIGPIPE, &act, 0L); // We set the close on exec flag. // Closing of fd[1] indicates that the execvp succeeded! if (fd[1]) fcntl(fd[1], F_SETFD, FD_CLOEXEC); execvp(arglist[0], arglist); char resultByte = 1; if (fd[1]) write(fd[1], &resultByte, 1); _exit(-1); } else if (-1 == pid_) { // forking failed runs = false; free(arglist); return false; } else { if (fd[1]) close(fd[1]); // the parent continues here // Discard any data for stdin that might still be there input_data = 0; // Check whether client could be started. if (fd[0]) for(;;) { char resultByte; int n = ::read(fd[0], &resultByte, 1); if (n == 1) { // Error runs = false; close(fd[0]); free(arglist); pid_ = 0; return false; } if (n == -1) { if ((errno == ECHILD) || (errno == EINTR)) continue; // Ignore } break; // success } if (fd[0]) close(fd[0]); if (!commSetupDoneP()) // finish communication socket setup for the parent qWarning( "Could not finish comm setup in parent!" ); if (run_mode == Block) { commClose(); // The SIGCHLD handler of the process controller will catch // the exit and set the status while(runs) { OProcessController::theOProcessController-> slotDoHousekeeping(0); } runs = FALSE; emit processExited(this); } } free(arglist); return true; } bool OProcess::kill(int signo) { bool rv=false; if (0 != pid_) rv= (-1 != ::kill(pid_, signo)); // probably store errno somewhere... return rv; } diff --git a/libopie/orecurrancewidget.cpp b/libopie/orecurrancewidget.cpp index be8ec30..d81851e 100644 --- a/libopie/orecurrancewidget.cpp +++ b/libopie/orecurrancewidget.cpp @@ -1,390 +1,388 @@ #include <qapplication.h> #include <qlabel.h> -#include <qpopupmenu.h> #include <qspinbox.h> -#include <qpe/timestring.h> #include "orecurrancewidget.h" // Global Templates for use in setting up the repeat label... // the problem is these strings get initialized before QPEApplication can install the translator -zecke namespace { QString strDayTemplate; QString strYearTemplate; QString strMonthDateTemplate; QString strMonthDayTemplate; QString strWeekTemplate; QString dayLabel[7]; } /* * static linkage to not polute the symbol table... * The problem is that const and static linkage are resolved prior to installing a translator * leading to that the above strings are translted but to the original we delay the init of these strings... * -zecke */ static void fillStrings() { strDayTemplate = QObject::tr("Every"); strYearTemplate = QObject::tr("%1 %2 every "); strMonthDateTemplate = QObject::tr("The %1 every "); strMonthDayTemplate = QObject::tr("The %1 %2 of every"); strWeekTemplate = QObject::tr("Every "); dayLabel[0] = QObject::tr("Monday"); dayLabel[1] = QObject::tr("Tuesday"); dayLabel[2] = QObject::tr("Wednesday"); dayLabel[3] = QObject::tr("Thursday"); dayLabel[4] = QObject::tr("Friday"); dayLabel[5] = QObject::tr("Saturday"); dayLabel[6] = QObject::tr("Sunday"); } static QString numberPlacing( int x ); // return the proper word format for // x (1st, 2nd, etc) static int week( const QDate &dt ); // what week in the month is dt? /** * Constructs the Widget * @param startOnMonday Does the week start on monday * @param newStart The start date of the recurrence * @param parent The parent widget * @param name the name of object * @param modal if the dialog should be modal * @param fl Additional window flags */ ORecurranceWidget::ORecurranceWidget( bool startOnMonday, const QDate& newStart, QWidget* parent, const char* name, bool modal, WFlags fl ) : ORecurranceBase( parent, name, modal, fl ), start( newStart ), currInterval( None ), startWeekOnMonday( startOnMonday ) { if (strDayTemplate.isEmpty() ) fillStrings(); init(); fraType->setButton( currInterval ); chkNoEnd->setChecked( TRUE ); setupNone(); } /** * Different constructor * @param startOnMonday Does the week start on monday? * @param rp Already set ORecur object * @param startDate The start date * @param parent The parent widget * @param name The name of the object * @param modal * @param fl The flags for window */ ORecurranceWidget::ORecurranceWidget( bool startOnMonday, const ORecur& rp, const QDate& startDate, QWidget* parent, const char* name, bool modal, WFlags fl) : ORecurranceBase( parent, name, modal, fl ), start( startDate ), end( rp.endDate() ), startWeekOnMonday( startOnMonday ) { if (strDayTemplate.isEmpty() ) fillStrings(); // do some stuff with the repeat pattern init(); setRecurrence( rp ); } ORecurranceWidget::~ORecurranceWidget() { } /** * set the start date * @param date the new start date */ void ORecurranceWidget::setStartDate( const QDate& date ) { setRecurrence( recurrence(), date ); } /** * set the recurrence * @param rp The ORecur object with the new recurrence rules */ void ORecurranceWidget::setRecurrence( const ORecur& rp ) { setRecurrence( rp, start ); } /** * overloaded method taking ORecur and a new start date * @param rp Recurrence rule * @param date The new start date */ void ORecurranceWidget::setRecurrence( const ORecur& rp, const QDate& date ) { start = date; end = rp.endDate(); switch ( rp.type() ) { default: case ORecur::NoRepeat: currInterval = None; setupNone(); break; case ORecur::Daily: currInterval = Day; setupDaily(); break; case ORecur::Weekly: currInterval = Week; setupWeekly(); int day, buttons; for ( day = 0x01, buttons = 0; buttons < 7; day = day << 1, buttons++ ) { if ( rp.days() & day ) { if ( startWeekOnMonday ) fraExtra->setButton( buttons ); else { if ( buttons == 7 ) fraExtra->setButton( 0 ); else fraExtra->setButton( buttons + 1 ); } } } slotWeekLabel(); break; case ORecur::MonthlyDay: currInterval = Month; setupMonthly(); fraExtra->setButton( 0 ); slotMonthLabel( 0 ); break; case ORecur::MonthlyDate: currInterval = Month; setupMonthly(); fraExtra->setButton( 1 ); slotMonthLabel( 1 ); break; case ORecur::Yearly: currInterval = Year; setupYearly(); break; } fraType->setButton( currInterval ); spinFreq->setValue( rp.frequency() ); if ( !rp.hasEndDate() ) { cmdEnd->setText( tr("No End Date") ); chkNoEnd->setChecked( TRUE ); } else cmdEnd->setText( TimeString::shortDate( end ) ); } /** * the user selected recurrence rule. * @return The recurrence rule. */ ORecur ORecurranceWidget::recurrence()const { QListIterator<QToolButton> it( listRTypeButtons ); QListIterator<QToolButton> itExtra( listExtra ); ORecur rpTmp; int i; for ( i = 0; *it; ++it, i++ ) { if ( (*it)->isOn() ) { switch ( i ) { case None: rpTmp.setType( ORecur::NoRepeat ); break; case Day: rpTmp.setType( ORecur::Daily ); break; case Week:{ rpTmp.setType( ORecur::Weekly ); int day; int day2 = 0; for ( day = 1; *itExtra; ++itExtra, day = day << 1 ) { if ( (*itExtra)->isOn() ) { if ( startWeekOnMonday ) day2 |= day; else { if ( day == 1 ) day2 |= Event::SUN; else day2 |= day >> 1; } } } rpTmp.setDays( day2 ); } break; case Month: if ( cmdExtra1->isOn() ) rpTmp.setType( ORecur::MonthlyDay ); else if ( cmdExtra2->isOn() ) rpTmp.setType( ORecur::MonthlyDate ); // figure out the montly day... rpTmp.setPosition( week( start ) ); break; case Year: rpTmp.setType( ORecur::Yearly ); break; } break; // no need to keep looking! } } rpTmp.setFrequency(spinFreq->value() ); rpTmp.setHasEndDate( !chkNoEnd->isChecked() ); if ( rpTmp.hasEndDate() ) { rpTmp.setEndDate( end ); } // timestamp it... // rpTmp.setCreateTime( ); current DateTime is already set -zecke return rpTmp; } /** * Return the end date of the recurrence. This is only * valid if the recurrence rule does contain an enddate */ QDate ORecurranceWidget::endDate()const { return end; } void ORecurranceWidget::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 ORecurranceWidget::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 ORecurranceWidget::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( tr("No End Date") ); } else { end = start; cmdEnd->setText( TimeString::shortDate(end) ); } } void ORecurranceWidget::setupRepeatLabel( const QString& s) { lblVar1->setText( s ); } void ORecurranceWidget::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 = tr( "months" ); else strVar2 = tr( "month" ); break; case Year: if ( x > 1 ) strVar2 = tr( "years" ); else strVar2 = tr( "year" ); break; } if ( !strVar2.isNull() ) lblVar2->setText( strVar2 ); } void ORecurranceWidget::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; } } diff --git a/libopie/oticker.cpp b/libopie/oticker.cpp index 4fb5945..c05c2a8 100644 --- a/libopie/oticker.cpp +++ b/libopie/oticker.cpp @@ -1,139 +1,130 @@ /* This file is part of the Opie Project Copyright (c) 2002 L. Potter <ljp@llornkcor.com> =. .=l. .>+-= _;:, .> :=|. 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 <qpe/qpeapplication.h> -#include <qpe/resource.h> #include <qpe/config.h> -#include <qwidget.h> -#include <qpixmap.h> -#include <qbutton.h> -#include <qpainter.h> -#include <qframe.h> -#include <qlayout.h> -#include <qdir.h> #include <stdlib.h> #include <stdio.h> #include "oticker.h" OTicker::OTicker( QWidget* parent ) : QLabel( parent ) { // : QFrame( parent ) { setTextFormat(Qt::RichText); Config cfg("qpe"); cfg.setGroup("Appearance"); backgroundcolor = QColor( cfg.readEntry( "Background", "#E5E1D5" ) ); foregroundcolor= Qt::black; updateTimerTime = 50; scrollLength = 1; } OTicker::~OTicker() { } void OTicker::setBackgroundColor(const QColor& backcolor) { backgroundcolor = backcolor; update(); } void OTicker::setForegroundColor(const QColor& backcolor) { foregroundcolor = backcolor; update(); } void OTicker::setFrame(int frameStyle) { setFrameStyle( frameStyle/*WinPanel | Sunken */); update(); } void OTicker::setText( const QString& text ) { pos = 0; // reset it everytime the text is changed scrollText = text; qDebug(scrollText); int pixelLen = 0; bool bigger = false; int contWidth = contentsRect().width(); int contHeight = contentsRect().height(); int pixelTextLen = fontMetrics().width( text ); printf("<<<<<<<height %d, width %d, text width %d %d\n", contHeight, contWidth, pixelTextLen, scrollText.length()); if( pixelTextLen < contWidth) { pixelLen = contWidth; } else { bigger = true; pixelLen = pixelTextLen; } QPixmap pm( pixelLen, contHeight); // pm.fill( QColor( 167, 212, 167 )); pm.fill(backgroundcolor); QPainter pmp( &pm ); pmp.setPen(foregroundcolor ); pmp.drawText( 0, 0, pixelTextLen, contHeight, AlignVCenter, scrollText ); pmp.end(); scrollTextPixmap = pm; killTimers(); // qDebug("Scrollupdate %d", updateTimerTime); if ( bigger /*pixelTextLen > contWidth*/ ) startTimer( updateTimerTime); update(); } void OTicker::timerEvent( QTimerEvent * ) { pos = ( pos <= 0 ) ? scrollTextPixmap.width() : pos - scrollLength;//1; repaint( FALSE ); } void OTicker::drawContents( QPainter *p ) { int pixelLen = scrollTextPixmap.width(); p->drawPixmap( pos, contentsRect().y(), scrollTextPixmap ); if ( pixelLen > contentsRect().width() ) // Scrolling p->drawPixmap( pos - pixelLen, contentsRect().y(), scrollTextPixmap ); } void OTicker::mouseReleaseEvent( QMouseEvent * ) { // qDebug("<<<<<<<>>>>>>>>>"); emit mousePressed(); } void OTicker::setUpdateTime(int time) { updateTimerTime=time; } void OTicker::setScrollLength(int len) { scrollLength=len; } diff --git a/libopie/otimepicker.cpp b/libopie/otimepicker.cpp index 115d39b..1eca7c5 100644 --- a/libopie/otimepicker.cpp +++ b/libopie/otimepicker.cpp @@ -1,245 +1,242 @@ #include "otimepicker.h" -#include <qbuttongroup.h> -#include <qtoolbutton.h> #include <qlayout.h> -#include <qstring.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& ) ) ); } /** * @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/owait.cpp b/libopie/owait.cpp index 0fdf08d..a0f3834 100644 --- a/libopie/owait.cpp +++ b/libopie/owait.cpp @@ -1,93 +1,91 @@ /* This file is part of the OPIE libraries Copyright (C) 2003 Maximilian Reiss (harlekin@handhelds.org) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ -#include <qlabel.h> #include <qlayout.h> -#include <qtimer.h> #include <qpe/qpeapplication.h> #include <qpainter.h> #include "owait.h" #include <qpe/resource.h> static int frame = 0; /** * This will construct a modal dialog. * * The default timer length is 10. * * @param parent The parent of the widget * @param msg The name of the object * @param dispIcon Display Icon? */ OWait::OWait(QWidget *parent, const char* msg, bool dispIcon ) :QDialog(parent, msg, TRUE,WStyle_Customize) { QHBoxLayout *hbox = new QHBoxLayout( this ); m_lb = new QLabel( this ); m_lb->setBackgroundMode ( NoBackground ); hbox->addWidget( m_lb ); hbox->activate(); m_pix = Resource::loadPixmap( "BigBusy" ); m_aniSize = m_pix.height(); resize( m_aniSize, m_aniSize ); m_timerLength = 10; m_waitTimer = new QTimer( this ); connect( m_waitTimer, SIGNAL( timeout() ), this, SLOT( hide() ) ); } void OWait::timerEvent( QTimerEvent * ) { frame = (++frame) % 4; repaint(); } void OWait::paintEvent( QPaintEvent * ) { QPainter p( m_lb ); p.drawPixmap( 0, 0, m_pix, m_aniSize * frame, 0, m_aniSize, m_aniSize ); } void OWait::show() { move( ( ( qApp->desktop()->width() ) / 2 ) - ( m_aniSize / 2 ), ( ( qApp->desktop()->height() ) / 2 ) - ( m_aniSize / 2 ) ); startTimer( 300 ); m_waitTimer->start( m_timerLength * 1000, true ); QDialog::show(); } void OWait::hide() { killTimers(); m_waitTimer->stop(); frame = 0; QDialog::hide(); } void OWait::setTimerLength( int length ) { m_timerLength = length; } OWait::~OWait() { } diff --git a/libopie/pim/ocontactaccessbackend_xml.cpp b/libopie/pim/ocontactaccessbackend_xml.cpp index aae7fca..2373ad6 100644 --- a/libopie/pim/ocontactaccessbackend_xml.cpp +++ b/libopie/pim/ocontactaccessbackend_xml.cpp @@ -1,497 +1,498 @@ /* * XML Backend for the OPIE-Contact Database. * * 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. * ===================================================================== * * ===================================================================== * Version: $Id$ * ===================================================================== * History: * $Log$ + * Revision 1.10 2004/03/01 15:44:36 chicken + * fix includes + * * Revision 1.9 2003/09/22 14:31:16 eilers * Added first experimental incarnation of sql-backend for addressbook. * Some modifications to be able to compile the todo sql-backend. * A lot of changes fill follow... * * Revision 1.8 2003/08/30 15:28:26 eilers * Removed some unimportant debug output which causes slow down.. * * Revision 1.7 2003/08/01 12:30:16 eilers * Merging changes from BRANCH_1_0 to HEAD * * Revision 1.6 2003/07/07 16:19:47 eilers * Fixing serious bug in hasQuerySettings() * * Revision 1.5 2003/04/13 18:07:10 zecke * More API doc * QString -> const QString& * QString = 0l -> QString::null * * Revision 1.4 2003/03/21 14:32:54 mickeyl * g++ compliance fix: default arguments belong into the declaration, but not the definition * * Revision 1.3 2003/03/21 12:26:28 eilers * Fixing small bug: If we search a birthday from today to today, it returned * every contact .. * * Revision 1.2 2003/03/21 10:33:09 eilers * Merged speed optimized xml backend for contacts to main. * Added QDateTime to querybyexample. For instance, it is now possible to get * all Birthdays/Anniversaries between two dates. This should be used * to show all birthdays in the datebook.. * This change is sourcecode backward compatible but you have to upgrade * the binaries for today-addressbook. * * Revision 1.1.2.2 2003/02/11 12:17:28 eilers * Speed optimization. Removed the sequential search loops. * * Revision 1.1.2.1 2003/02/10 15:31:38 eilers * Writing offsets to debug output.. * * Revision 1.1 2003/02/09 15:05:01 eilers * Nothing happened.. Just some cleanup before I will start.. * * Revision 1.12 2003/01/03 16:58:03 eilers * Reenable debug output * * Revision 1.11 2003/01/03 12:31:28 eilers * Bugfix for calculating data diffs.. * * Revision 1.10 2003/01/02 14:27:12 eilers * Improved query by example: Search by date is possible.. First step * for a today plugin for birthdays.. * * Revision 1.9 2002/12/08 12:48:57 eilers * Moved journal-enum from ocontact into i the xml-backend.. * * Revision 1.8 2002/11/14 17:04:24 eilers * Sorting will now work if fullname is identical on some entries * * Revision 1.7 2002/11/13 15:02:46 eilers * Small Bug in sorted fixed * * Revision 1.6 2002/11/13 14:14:51 eilers * Added sorted for Contacts.. * * Revision 1.5 2002/11/01 15:10:42 eilers * Added regExp-search in database for all fields in a contact. * * Revision 1.4 2002/10/16 10:52:40 eilers * Added some docu to the interface and now using the cache infrastucture by zecke.. :) * * Revision 1.3 2002/10/14 16:21:54 eilers * Some minor interface updates * * Revision 1.2 2002/10/07 17:34:24 eilers * added OBackendFactory for advanced backend access * * 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 "ocontactaccessbackend_xml.h" #include <qasciidict.h> -#include <qdatetime.h> #include <qfile.h> #include <qfileinfo.h> #include <qregexp.h> #include <qarray.h> #include <qmap.h> -#include <qdatetime.h> #include <qpe/global.h> #include <opie/xmltree.h> #include "ocontactaccessbackend.h" #include "ocontactaccess.h" #include <stdlib.h> #include <errno.h> using namespace Opie; OContactAccessBackend_XML::OContactAccessBackend_XML ( const QString& appname, const QString& filename ): m_changed( false ) { // Just m_contactlist should call delete if an entry // is removed. m_contactList.setAutoDelete( true ); m_uidToContact.setAutoDelete( false ); m_appName = appname; /* Set journalfile name ... */ m_journalName = getenv("HOME"); m_journalName +="/.abjournal" + appname; /* Expecting to access the default filename if nothing else is set */ if ( filename.isEmpty() ){ m_fileName = Global::applicationFileName( "addressbook","addressbook.xml" ); } else m_fileName = filename; /* Load Database now */ load (); } bool OContactAccessBackend_XML::save() { if ( !m_changed ) return true; QString strNewFile = m_fileName + ".new"; QFile f( strNewFile ); if ( !f.open( IO_WriteOnly|IO_Raw ) ) return false; int total_written; int idx_offset = 0; QString out; // Write Header out = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><!DOCTYPE Addressbook ><AddressBook>\n" " <Groups>\n" " </Groups>\n" " <Contacts>\n"; QCString cstr = out.utf8(); f.writeBlock( cstr.data(), cstr.length() ); idx_offset += cstr.length(); out = ""; // Write all contacts QListIterator<OContact> it( m_contactList ); for ( ; it.current(); ++it ) { // qWarning(" Uid %d at Offset: %x", (*it)->uid(), idx_offset ); out += "<Contact "; (*it)->save( out ); out += "/>\n"; cstr = out.utf8(); total_written = f.writeBlock( cstr.data(), cstr.length() ); idx_offset += cstr.length(); if ( total_written != int(cstr.length()) ) { f.close(); QFile::remove( strNewFile ); return false; } out = ""; } out += " </Contacts>\n</AddressBook>\n"; // Write Footer cstr = out.utf8(); total_written = f.writeBlock( cstr.data(), cstr.length() ); if ( total_written != int( cstr.length() ) ) { f.close(); QFile::remove( strNewFile ); return false; } f.close(); // move the file over, I'm just going to use the system call // because, I don't feel like using QDir. if ( ::rename( strNewFile.latin1(), m_fileName.latin1() ) < 0 ) { qWarning( "problem renaming file %s to %s, errno: %d", strNewFile.latin1(), m_journalName.latin1(), errno ); // remove the tmp file... QFile::remove( strNewFile ); } /* The journalfile should be removed now... */ removeJournal(); m_changed = false; return true; } bool OContactAccessBackend_XML::load () { m_contactList.clear(); m_uidToContact.clear(); /* Load XML-File and journal if it exists */ if ( !load ( m_fileName, false ) ) return false; /* The returncode of the journalfile is ignored due to the * fact that it does not exist when this class is instantiated ! * But there may such a file exist, if the application crashed. * Therefore we try to load it to get the changes before the # * crash happened... */ load (m_journalName, true); return true; } void OContactAccessBackend_XML::clear () { m_contactList.clear(); m_uidToContact.clear(); m_changed = false; } bool OContactAccessBackend_XML::wasChangedExternally() { QFileInfo fi( m_fileName ); QDateTime lastmod = fi.lastModified (); return (lastmod != m_readtime); } QArray<int> OContactAccessBackend_XML::allRecords() const { QArray<int> uid_list( m_contactList.count() ); uint counter = 0; QListIterator<OContact> it( m_contactList ); for( ; it.current(); ++it ){ uid_list[counter++] = (*it)->uid(); } return ( uid_list ); } OContact OContactAccessBackend_XML::find ( int uid ) const { OContact foundContact; //Create empty contact OContact* found = m_uidToContact.find( QString().setNum( uid ) ); if ( found ){ foundContact = *found; } return ( foundContact ); } QArray<int> OContactAccessBackend_XML::queryByExample ( const OContact &query, int settings, const QDateTime& d ) { QArray<int> m_currentQuery( m_contactList.count() ); QListIterator<OContact> it( m_contactList ); uint arraycounter = 0; for( ; it.current(); ++it ){ /* Search all fields and compare them with query object. Store them into list * if all fields matches. */ QDate* queryDate = 0l; QDate* checkDate = 0l; bool allcorrect = true; for ( int i = 0; i < Qtopia::Groups; i++ ) { // Birthday and anniversary are special nonstring fields and should // be handled specially switch ( i ){ case Qtopia::Birthday: queryDate = new QDate( query.birthday() ); checkDate = new QDate( (*it)->birthday() ); case Qtopia::Anniversary: if ( queryDate == 0l ){ queryDate = new QDate( query.anniversary() ); checkDate = new QDate( (*it)->anniversary() ); } if ( queryDate->isValid() ){ if( checkDate->isValid() ){ if ( settings & OContactAccess::DateYear ){ if ( queryDate->year() != checkDate->year() ) allcorrect = false; } if ( settings & OContactAccess::DateMonth ){ if ( queryDate->month() != checkDate->month() ) allcorrect = false; } if ( settings & OContactAccess::DateDay ){ if ( queryDate->day() != checkDate->day() ) allcorrect = false; } if ( settings & OContactAccess::DateDiff ) { QDate current; // If we get an additional date, we // will take this date instead of // the current one.. if ( !d.date().isValid() ) current = QDate::currentDate(); else current = d.date(); // We have to equalize the year, otherwise // the search will fail.. checkDate->setYMD( current.year(), checkDate->month(), checkDate->day() ); if ( *checkDate < current ) checkDate->setYMD( current.year()+1, checkDate->month(), checkDate->day() ); // Check whether the birthday/anniversary date is between // the current/given date and the maximum date // ( maximum time range ) ! qWarning("Checking if %s is between %s and %s ! ", checkDate->toString().latin1(), current.toString().latin1(), queryDate->toString().latin1() ); if ( current.daysTo( *queryDate ) >= 0 ){ if ( !( ( *checkDate >= current ) && ( *checkDate <= *queryDate ) ) ){ allcorrect = false; qWarning (" Nope!.."); } } } } else{ // checkDate is invalid. Therefore this entry is always rejected allcorrect = false; } } delete queryDate; queryDate = 0l; delete checkDate; checkDate = 0l; break; default: /* Just compare fields which are not empty in the query object */ if ( !query.field(i).isEmpty() ){ switch ( settings & ~( OContactAccess::IgnoreCase | OContactAccess::DateDiff | OContactAccess::DateYear | OContactAccess::DateMonth | OContactAccess::DateDay | OContactAccess::MatchOne ) ){ case OContactAccess::RegExp:{ QRegExp expr ( query.field(i), !(settings & OContactAccess::IgnoreCase), false ); if ( expr.find ( (*it)->field(i), 0 ) == -1 ) allcorrect = false; } break; case OContactAccess::WildCards:{ QRegExp expr ( query.field(i), !(settings & OContactAccess::IgnoreCase), true ); if ( expr.find ( (*it)->field(i), 0 ) == -1 ) allcorrect = false; } break; case OContactAccess::ExactMatch:{ if (settings & OContactAccess::IgnoreCase){ if ( query.field(i).upper() != (*it)->field(i).upper() ) allcorrect = false; }else{ if ( query.field(i) != (*it)->field(i) ) allcorrect = false; } } break; } } } } if ( allcorrect ){ m_currentQuery[arraycounter++] = (*it)->uid(); } } // Shrink to fit.. m_currentQuery.resize(arraycounter); return m_currentQuery; } QArray<int> OContactAccessBackend_XML::matchRegexp( const QRegExp &r ) const { QArray<int> m_currentQuery( m_contactList.count() ); QListIterator<OContact> it( m_contactList ); uint arraycounter = 0; for( ; it.current(); ++it ){ if ( (*it)->match( r ) ){ m_currentQuery[arraycounter++] = (*it)->uid(); } } // Shrink to fit.. m_currentQuery.resize(arraycounter); return m_currentQuery; } const uint OContactAccessBackend_XML::querySettings() { return ( OContactAccess::WildCards | OContactAccess::IgnoreCase | OContactAccess::RegExp | OContactAccess::ExactMatch | OContactAccess::DateDiff | OContactAccess::DateYear | OContactAccess::DateMonth | OContactAccess::DateDay ); } bool OContactAccessBackend_XML::hasQuerySettings (uint querySettings) const { /* OContactAccess::IgnoreCase, DateDiff, DateYear, DateMonth, DateDay * may be added with any of the other settings. IgnoreCase should never used alone. * Wildcards, RegExp, ExactMatch should never used at the same time... */ // Step 1: Check whether the given settings are supported by this backend if ( ( querySettings & ( OContactAccess::IgnoreCase | OContactAccess::WildCards | OContactAccess::DateDiff | OContactAccess::DateYear | OContactAccess::DateMonth | OContactAccess::DateDay | OContactAccess::RegExp | OContactAccess::ExactMatch ) ) != querySettings ) return false; // Step 2: Check whether the given combinations are ok.. // IngoreCase alone is invalid if ( querySettings == OContactAccess::IgnoreCase ) return false; // WildCards, RegExp and ExactMatch should never used at the same time switch ( querySettings & ~( OContactAccess::IgnoreCase | OContactAccess::DateDiff | OContactAccess::DateYear | OContactAccess::DateMonth | OContactAccess::DateDay ) ){ case OContactAccess::RegExp: return ( true ); case OContactAccess::WildCards: return ( true ); case OContactAccess::ExactMatch: return ( true ); case 0: // one of the upper removed bits were set.. return ( true ); default: diff --git a/libopie/pim/otodo.cpp b/libopie/pim/otodo.cpp index 189bf94..b2c76f8 100644 --- a/libopie/pim/otodo.cpp +++ b/libopie/pim/otodo.cpp @@ -1,396 +1,395 @@ #include <qobject.h> #include <qshared.h> #include <qpe/palmtopuidgen.h> -#include <qpe/stringutil.h> #include <qpe/palmtoprecord.h> -#include <qpe/stringutil.h> #include <qpe/categories.h> #include <qpe/categoryselect.h> +#include <qpe/stringutil.h> #include "opimstate.h" #include "orecur.h" #include "opimmaintainer.h" #include "opimnotifymanager.h" #include "opimresolver.h" #include "otodo.h" struct OTodo::OTodoData : public QShared { OTodoData() : QShared() { recur = 0; state = 0; maintainer = 0; notifiers = 0; }; ~OTodoData() { delete recur; delete maintainer; delete notifiers; } QDate date; bool isCompleted:1; bool hasDate:1; int priority; QString desc; QString sum; QMap<QString, QString> extra; ushort prog; OPimState *state; ORecur *recur; OPimMaintainer *maintainer; QDate start; QDate completed; OPimNotifyManager *notifiers; }; OTodo::OTodo(const OTodo &event ) : OPimRecord( event ), data( event.data ) { data->ref(); // qWarning("ref up"); } OTodo::~OTodo() { // qWarning("~OTodo " ); if ( data->deref() ) { // qWarning("OTodo::dereffing"); delete data; data = 0l; } } OTodo::OTodo(bool completed, int priority, const QArray<int> &category, const QString& summary, const QString &description, ushort progress, bool hasDate, QDate date, int uid ) : OPimRecord( uid ) { // qWarning("OTodoData " + summary); setCategories( category ); data = new OTodoData; data->date = date; data->isCompleted = completed; data->hasDate = hasDate; data->priority = priority; data->sum = summary; data->prog = progress; data->desc = Qtopia::simplifyMultiLineSpace(description ); } OTodo::OTodo(bool completed, int priority, const QStringList &category, const QString& summary, const QString &description, ushort progress, bool hasDate, QDate date, int uid ) : OPimRecord( uid ) { // qWarning("OTodoData" + summary); setCategories( idsFromString( category.join(";") ) ); data = new OTodoData; data->date = date; data->isCompleted = completed; data->hasDate = hasDate; data->priority = priority; data->sum = summary; data->prog = progress; data->desc = Qtopia::simplifyMultiLineSpace(description ); } bool OTodo::match( const QRegExp ®Exp )const { if( QString::number( data->priority ).find( regExp ) != -1 ){ setLastHitField( Priority ); return true; }else if( data->hasDate && data->date.toString().find( regExp) != -1 ){ setLastHitField( HasDate ); return true; }else if(data->desc.find( regExp ) != -1 ){ setLastHitField( Description ); return true; }else if(data->sum.find( regExp ) != -1 ) { setLastHitField( Summary ); return true; } return false; } bool OTodo::isCompleted() const { return data->isCompleted; } bool OTodo::hasDueDate() const { return data->hasDate; } bool OTodo::hasStartDate()const { return data->start.isValid(); } bool OTodo::hasCompletedDate()const { return data->completed.isValid(); } int OTodo::priority()const { return data->priority; } QString OTodo::summary() const { return data->sum; } ushort OTodo::progress() const { return data->prog; } QDate OTodo::dueDate()const { return data->date; } QDate OTodo::startDate()const { return data->start; } QDate OTodo::completedDate()const { return data->completed; } QString OTodo::description()const { return data->desc; } bool OTodo::hasState() const{ if (!data->state ) return false; return ( data->state->state() != OPimState::Undefined ); } OPimState OTodo::state()const { if (!data->state ) { OPimState state; return state; } return (*data->state); } bool OTodo::hasRecurrence()const { if (!data->recur) return false; return data->recur->doesRecur(); } ORecur OTodo::recurrence()const { if (!data->recur) return ORecur(); return (*data->recur); } bool OTodo::hasMaintainer()const { if (!data->maintainer) return false; return (data->maintainer->mode() != OPimMaintainer::Undefined ); } OPimMaintainer OTodo::maintainer()const { if (!data->maintainer) return OPimMaintainer(); return (*data->maintainer); } void OTodo::setCompleted( bool completed ) { changeOrModify(); data->isCompleted = completed; } void OTodo::setHasDueDate( bool hasDate ) { changeOrModify(); data->hasDate = hasDate; } void OTodo::setDescription(const QString &desc ) { // qWarning( "desc " + desc ); changeOrModify(); data->desc = Qtopia::simplifyMultiLineSpace(desc ); } void OTodo::setSummary( const QString& sum ) { changeOrModify(); data->sum = sum; } void OTodo::setPriority(int prio ) { changeOrModify(); data->priority = prio; } void OTodo::setDueDate( const QDate& date ) { changeOrModify(); data->date = date; } void OTodo::setStartDate( const QDate& date ) { changeOrModify(); data->start = date; } void OTodo::setCompletedDate( const QDate& date ) { changeOrModify(); data->completed = date; } void OTodo::setState( const OPimState& state ) { changeOrModify(); if (data->state ) (*data->state) = state; else data->state = new OPimState( state ); } void OTodo::setRecurrence( const ORecur& rec) { changeOrModify(); if (data->recur ) (*data->recur) = rec; else data->recur = new ORecur( rec ); } void OTodo::setMaintainer( const OPimMaintainer& pim ) { changeOrModify(); if (data->maintainer ) (*data->maintainer) = pim; else data->maintainer = new OPimMaintainer( pim ); } bool OTodo::isOverdue( ) { if( data->hasDate && !data->isCompleted) return QDate::currentDate() > data->date; return false; } void OTodo::setProgress(ushort progress ) { changeOrModify(); data->prog = progress; } QString OTodo::toShortText() const { return summary(); } /*! Returns a richt text string */ QString OTodo::toRichText() const { QString text; QStringList catlist; // summary text += "<b><h3><img src=\"todo/TodoList\"> "; if ( !summary().isEmpty() ) { text += Qtopia::escapeString(summary() ).replace(QRegExp( "[\n]"), "" ); } text += "</h3></b><br><hr><br>"; // description if( !description().isEmpty() ){ text += "<b>" + QObject::tr( "Description:" ) + "</b><br>"; text += Qtopia::escapeString(description() ).replace(QRegExp( "[\n]"), "<br>" ) + "<br>"; } // priority int priorityval = priority(); text += "<b>" + QObject::tr( "Priority:") +" </b><img src=\"todo/priority" + QString::number( priorityval ) + "\"> "; switch ( priorityval ) { case 1 : text += QObject::tr( "Very high" ); break; case 2 : text += QObject::tr( "High" ); break; case 3 : text += QObject::tr( "Normal" ); break; case 4 : text += QObject::tr( "Low" ); break; case 5 : text += QObject::tr( "Very low" ); break; }; text += "<br>"; // progress text += "<b>" + QObject::tr( "Progress:") + " </b>" + QString::number( progress() ) + " %<br>"; // due date if (hasDueDate() ){ QDate dd = dueDate(); int off = QDate::currentDate().daysTo( dd ); text += "<b>" + QObject::tr( "Deadline:" ) + " </b><font color=\""; if ( off < 0 ) text += "#FF0000"; else if ( off == 0 ) text += "#FFFF00"; else if ( off > 0 ) text += "#00FF00"; text += "\">" + dd.toString() + "</font><br>"; } // categories text += "<b>" + QObject::tr( "Category:") + "</b> "; text += categoryNames( "Todo List" ).join(", "); text += "<br>"; return text; } bool OTodo::hasNotifiers()const { if (!data->notifiers) return false; return !data->notifiers->isEmpty(); } OPimNotifyManager& OTodo::notifiers() { if (!data->notifiers ) data->notifiers = new OPimNotifyManager; return (*data->notifiers); } const OPimNotifyManager& OTodo::notifiers()const{ if (!data->notifiers ) data->notifiers = new OPimNotifyManager; return (*data->notifiers); } bool OTodo::operator<( const OTodo &toDoEvent )const{ if( !hasDueDate() && !toDoEvent.hasDueDate() ) return true; if( !hasDueDate() && toDoEvent.hasDueDate() ) return false; if( hasDueDate() && toDoEvent.hasDueDate() ){ if( dueDate() == toDoEvent.dueDate() ){ // let's the priority decide return priority() < toDoEvent.priority(); }else{ return dueDate() < toDoEvent.dueDate(); } } return false; } bool OTodo::operator<=(const OTodo &toDoEvent )const { if( !hasDueDate() && !toDoEvent.hasDueDate() ) return true; if( !hasDueDate() && toDoEvent.hasDueDate() ) return true; if( hasDueDate() && toDoEvent.hasDueDate() ){ if( dueDate() == toDoEvent.dueDate() ){ // let's the priority decide return priority() <= toDoEvent.priority(); }else{ return dueDate() <= toDoEvent.dueDate(); } } return true; } bool OTodo::operator>(const OTodo &toDoEvent )const { if( !hasDueDate() && !toDoEvent.hasDueDate() ) return false; if( !hasDueDate() && toDoEvent.hasDueDate() ) return false; if( hasDueDate() && toDoEvent.hasDueDate() ){ if( dueDate() == toDoEvent.dueDate() ){ // let's the priority decide return priority() > toDoEvent.priority(); }else{ return dueDate() > toDoEvent.dueDate(); } } return false; } bool OTodo::operator>=(const OTodo &toDoEvent )const { |